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

1.364   ! brouard     1: /* $Id: imach.c,v 1.363 2024/06/28 09:31:55 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.360     brouard     3:   $Log: imach.c,v $
1.364   ! brouard     4:   Revision 1.363  2024/06/28 09:31:55  brouard
        !             5:   Summary: Adding log lines too
        !             6: 
1.363     brouard     7:   Revision 1.362  2024/06/28 08:00:31  brouard
                      8:   Summary: 0.99s6
                      9: 
                     10:   * imach.c (Module): s6 errors with age*age (harmless).
                     11: 
1.362     brouard    12:   Revision 1.361  2024/05/12 20:29:32  brouard
                     13:   Summary: Version 0.99s5
                     14: 
                     15:   * src/imach.c Version 0.99s5 In fact, the covariance of total life
                     16:   expectancy e.. with a partial life expectancy e.j is high,
                     17:   therefore the complete matrix of variance covariance has to be
                     18:   included in the formula of the standard error of the proportion of
                     19:   total life expectancy spent in a specific state:
                     20:   var(X/Y)=mu_x^2/mu_y^2*(sigma_x^2/mu_x^2 -2
                     21:   sigma_xy/mu_x/mu_y+sigma^2/mu_y^2).  Also an error with mle=-3
                     22:   made the program core dump. It is fixed in this version.
                     23: 
1.361     brouard    24:   Revision 1.360  2024/04/30 10:59:22  brouard
                     25:   Summary: Version 0.99s4 and estimation of std of e.j/e..
                     26: 
1.360     brouard    27:   Revision 1.359  2024/04/24 21:21:17  brouard
                     28:   Summary: First IMaCh version using Brent Praxis software based on Buckhardt and Gegenfürtner C codes
                     29: 
1.359     brouard    30:   Revision 1.6  2024/04/24 21:10:29  brouard
                     31:   Summary: First IMaCh version using Brent Praxis software based on Buckhardt and Gegenfürtner C codes
1.358     brouard    32: 
1.359     brouard    33:   Revision 1.5  2023/10/09 09:10:01  brouard
                     34:   Summary: trying to reconsider
1.357     brouard    35: 
1.359     brouard    36:   Revision 1.4  2023/06/22 12:50:51  brouard
                     37:   Summary: stil on going
1.357     brouard    38: 
1.359     brouard    39:   Revision 1.3  2023/06/22 11:28:07  brouard
                     40:   *** empty log message ***
1.356     brouard    41: 
1.359     brouard    42:   Revision 1.2  2023/06/22 11:22:40  brouard
                     43:   Summary: with svd but not working yet
1.355     brouard    44: 
1.354     brouard    45:   Revision 1.353  2023/05/08 18:48:22  brouard
                     46:   *** empty log message ***
                     47: 
1.353     brouard    48:   Revision 1.352  2023/04/29 10:46:21  brouard
                     49:   *** empty log message ***
                     50: 
1.352     brouard    51:   Revision 1.351  2023/04/29 10:43:47  brouard
                     52:   Summary: 099r45
                     53: 
1.351     brouard    54:   Revision 1.350  2023/04/24 11:38:06  brouard
                     55:   *** empty log message ***
                     56: 
1.350     brouard    57:   Revision 1.349  2023/01/31 09:19:37  brouard
                     58:   Summary: Improvements in models with age*Vn*Vm
                     59: 
1.348     brouard    60:   Revision 1.347  2022/09/18 14:36:44  brouard
                     61:   Summary: version 0.99r42
                     62: 
1.347     brouard    63:   Revision 1.346  2022/09/16 13:52:36  brouard
                     64:   * src/imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     65: 
1.346     brouard    66:   Revision 1.345  2022/09/16 13:40:11  brouard
                     67:   Summary: Version 0.99r41
                     68: 
                     69:   * imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     70: 
1.345     brouard    71:   Revision 1.344  2022/09/14 19:33:30  brouard
                     72:   Summary: version 0.99r40
                     73: 
                     74:   * imach.c (Module): Fixing names of variables in T_ (thanks to Feinuo)
                     75: 
1.344     brouard    76:   Revision 1.343  2022/09/14 14:22:16  brouard
                     77:   Summary: version 0.99r39
                     78: 
                     79:   * imach.c (Module): Version 0.99r39 with colored dummy covariates
                     80:   (fixed or time varying), using new last columns of
                     81:   ILK_parameter.txt file.
                     82: 
1.343     brouard    83:   Revision 1.342  2022/09/11 19:54:09  brouard
                     84:   Summary: 0.99r38
                     85: 
                     86:   * imach.c (Module): Adding timevarying products of any kinds,
                     87:   should work before shifting cotvar from ncovcol+nqv columns in
                     88:   order to have a correspondance between the column of cotvar and
                     89:   the id of column.
                     90:   (Module): Some cleaning and adding covariates in ILK.txt
                     91: 
1.342     brouard    92:   Revision 1.341  2022/09/11 07:58:42  brouard
                     93:   Summary: Version 0.99r38
                     94: 
                     95:   After adding change in cotvar.
                     96: 
1.341     brouard    97:   Revision 1.340  2022/09/11 07:53:11  brouard
                     98:   Summary: Version imach 0.99r37
                     99: 
                    100:   * imach.c (Module): Adding timevarying products of any kinds,
                    101:   should work before shifting cotvar from ncovcol+nqv columns in
                    102:   order to have a correspondance between the column of cotvar and
                    103:   the id of column.
                    104: 
1.340     brouard   105:   Revision 1.339  2022/09/09 17:55:22  brouard
                    106:   Summary: version 0.99r37
                    107: 
                    108:   * imach.c (Module): Many improvements for fixing products of fixed
                    109:   timevarying as well as fixed * fixed, and test with quantitative
                    110:   covariate.
                    111: 
1.339     brouard   112:   Revision 1.338  2022/09/04 17:40:33  brouard
                    113:   Summary: 0.99r36
                    114: 
                    115:   * imach.c (Module): Now the easy runs i.e. without result or
                    116:   model=1+age only did not work. The defautl combination should be 1
                    117:   and not 0 because everything hasn't been tranformed yet.
                    118: 
1.338     brouard   119:   Revision 1.337  2022/09/02 14:26:02  brouard
                    120:   Summary: version 0.99r35
                    121: 
                    122:   * src/imach.c: Version 0.99r35 because it outputs same results with
                    123:   1+age+V1+V1*age for females and 1+age for females only
                    124:   (education=1 noweight)
                    125: 
1.337     brouard   126:   Revision 1.336  2022/08/31 09:52:36  brouard
                    127:   *** empty log message ***
                    128: 
1.336     brouard   129:   Revision 1.335  2022/08/31 08:23:16  brouard
                    130:   Summary: improvements...
                    131: 
1.335     brouard   132:   Revision 1.334  2022/08/25 09:08:41  brouard
                    133:   Summary: In progress for quantitative
                    134: 
1.334     brouard   135:   Revision 1.333  2022/08/21 09:10:30  brouard
                    136:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                    137:   reassigning covariates: my first idea was that people will always
                    138:   use the first covariate V1 into the model but in fact they are
                    139:   producing data with many covariates and can use an equation model
                    140:   with some of the covariate; it means that in a model V2+V3 instead
                    141:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    142:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    143:   the equation model is restricted to two variables only (V2, V3)
                    144:   and the combination for V2 should be codtabm(k,1) instead of
                    145:   (codtabm(k,2), and the code should be
                    146:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    147:   made. All of these should be simplified once a day like we did in
                    148:   hpxij() for example by using precov[nres] which is computed in
                    149:   decoderesult for each nres of each resultline. Loop should be done
                    150:   on the equation model globally by distinguishing only product with
                    151:   age (which are changing with age) and no more on type of
                    152:   covariates, single dummies, single covariates.
                    153: 
1.333     brouard   154:   Revision 1.332  2022/08/21 09:06:25  brouard
                    155:   Summary: Version 0.99r33
                    156: 
                    157:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                    158:   reassigning covariates: my first idea was that people will always
                    159:   use the first covariate V1 into the model but in fact they are
                    160:   producing data with many covariates and can use an equation model
                    161:   with some of the covariate; it means that in a model V2+V3 instead
                    162:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    163:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    164:   the equation model is restricted to two variables only (V2, V3)
                    165:   and the combination for V2 should be codtabm(k,1) instead of
                    166:   (codtabm(k,2), and the code should be
                    167:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    168:   made. All of these should be simplified once a day like we did in
                    169:   hpxij() for example by using precov[nres] which is computed in
                    170:   decoderesult for each nres of each resultline. Loop should be done
                    171:   on the equation model globally by distinguishing only product with
                    172:   age (which are changing with age) and no more on type of
                    173:   covariates, single dummies, single covariates.
                    174: 
1.332     brouard   175:   Revision 1.331  2022/08/07 05:40:09  brouard
                    176:   *** empty log message ***
                    177: 
1.331     brouard   178:   Revision 1.330  2022/08/06 07:18:25  brouard
                    179:   Summary: last 0.99r31
                    180: 
                    181:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                    182: 
1.330     brouard   183:   Revision 1.329  2022/08/03 17:29:54  brouard
                    184:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                    185: 
1.329     brouard   186:   Revision 1.328  2022/07/27 17:40:48  brouard
                    187:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                    188: 
1.328     brouard   189:   Revision 1.327  2022/07/27 14:47:35  brouard
                    190:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                    191: 
1.327     brouard   192:   Revision 1.326  2022/07/26 17:33:55  brouard
                    193:   Summary: some test with nres=1
                    194: 
1.326     brouard   195:   Revision 1.325  2022/07/25 14:27:23  brouard
                    196:   Summary: r30
                    197: 
                    198:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                    199:   coredumped, revealed by Feiuno, thank you.
                    200: 
1.325     brouard   201:   Revision 1.324  2022/07/23 17:44:26  brouard
                    202:   *** empty log message ***
                    203: 
1.324     brouard   204:   Revision 1.323  2022/07/22 12:30:08  brouard
                    205:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    206: 
1.323     brouard   207:   Revision 1.322  2022/07/22 12:27:48  brouard
                    208:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    209: 
1.322     brouard   210:   Revision 1.321  2022/07/22 12:04:24  brouard
                    211:   Summary: r28
                    212: 
                    213:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    214: 
1.321     brouard   215:   Revision 1.320  2022/06/02 05:10:11  brouard
                    216:   *** empty log message ***
                    217: 
1.320     brouard   218:   Revision 1.319  2022/06/02 04:45:11  brouard
                    219:   * imach.c (Module): Adding the Wald tests from the log to the main
                    220:   htm for better display of the maximum likelihood estimators.
                    221: 
1.319     brouard   222:   Revision 1.318  2022/05/24 08:10:59  brouard
                    223:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                    224:   of confidencce intervals with product in the equation modelC
                    225: 
1.318     brouard   226:   Revision 1.317  2022/05/15 15:06:23  brouard
                    227:   * imach.c (Module):  Some minor improvements
                    228: 
1.317     brouard   229:   Revision 1.316  2022/05/11 15:11:31  brouard
                    230:   Summary: r27
                    231: 
1.316     brouard   232:   Revision 1.315  2022/05/11 15:06:32  brouard
                    233:   *** empty log message ***
                    234: 
1.315     brouard   235:   Revision 1.314  2022/04/13 17:43:09  brouard
                    236:   * imach.c (Module): Adding link to text data files
                    237: 
1.314     brouard   238:   Revision 1.313  2022/04/11 15:57:42  brouard
                    239:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    240: 
1.313     brouard   241:   Revision 1.312  2022/04/05 21:24:39  brouard
                    242:   *** empty log message ***
                    243: 
1.312     brouard   244:   Revision 1.311  2022/04/05 21:03:51  brouard
                    245:   Summary: Fixed quantitative covariates
                    246: 
                    247:          Fixed covariates (dummy or quantitative)
                    248:        with missing values have never been allowed but are ERRORS and
                    249:        program quits. Standard deviations of fixed covariates were
                    250:        wrongly computed. Mean and standard deviations of time varying
                    251:        covariates are still not computed.
                    252: 
1.311     brouard   253:   Revision 1.310  2022/03/17 08:45:53  brouard
                    254:   Summary: 99r25
                    255: 
                    256:   Improving detection of errors: result lines should be compatible with
                    257:   the model.
                    258: 
1.310     brouard   259:   Revision 1.309  2021/05/20 12:39:14  brouard
                    260:   Summary: Version 0.99r24
                    261: 
1.309     brouard   262:   Revision 1.308  2021/03/31 13:11:57  brouard
                    263:   Summary: Version 0.99r23
                    264: 
                    265: 
                    266:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    267: 
1.308     brouard   268:   Revision 1.307  2021/03/08 18:11:32  brouard
                    269:   Summary: 0.99r22 fixed bug on result:
                    270: 
1.307     brouard   271:   Revision 1.306  2021/02/20 15:44:02  brouard
                    272:   Summary: Version 0.99r21
                    273: 
                    274:   * imach.c (Module): Fix bug on quitting after result lines!
                    275:   (Module): Version 0.99r21
                    276: 
1.306     brouard   277:   Revision 1.305  2021/02/20 15:28:30  brouard
                    278:   * imach.c (Module): Fix bug on quitting after result lines!
                    279: 
1.305     brouard   280:   Revision 1.304  2021/02/12 11:34:20  brouard
                    281:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    282: 
1.304     brouard   283:   Revision 1.303  2021/02/11 19:50:15  brouard
                    284:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    285: 
1.303     brouard   286:   Revision 1.302  2020/02/22 21:00:05  brouard
                    287:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    288:   and life table from the data without any state)
                    289: 
1.302     brouard   290:   Revision 1.301  2019/06/04 13:51:20  brouard
                    291:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    292: 
1.301     brouard   293:   Revision 1.300  2019/05/22 19:09:45  brouard
                    294:   Summary: version 0.99r19 of May 2019
                    295: 
1.300     brouard   296:   Revision 1.299  2019/05/22 18:37:08  brouard
                    297:   Summary: Cleaned 0.99r19
                    298: 
1.299     brouard   299:   Revision 1.298  2019/05/22 18:19:56  brouard
                    300:   *** empty log message ***
                    301: 
1.298     brouard   302:   Revision 1.297  2019/05/22 17:56:10  brouard
                    303:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    304: 
1.297     brouard   305:   Revision 1.296  2019/05/20 13:03:18  brouard
                    306:   Summary: Projection syntax simplified
                    307: 
                    308: 
                    309:   We can now start projections, forward or backward, from the mean date
                    310:   of inteviews up to or down to a number of years of projection:
                    311:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    312:   or
                    313:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    314:   or
                    315:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    316:   or
                    317:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    318: 
1.296     brouard   319:   Revision 1.295  2019/05/18 09:52:50  brouard
                    320:   Summary: doxygen tex bug
                    321: 
1.295     brouard   322:   Revision 1.294  2019/05/16 14:54:33  brouard
                    323:   Summary: There was some wrong lines added
                    324: 
1.294     brouard   325:   Revision 1.293  2019/05/09 15:17:34  brouard
                    326:   *** empty log message ***
                    327: 
1.293     brouard   328:   Revision 1.292  2019/05/09 14:17:20  brouard
                    329:   Summary: Some updates
                    330: 
1.292     brouard   331:   Revision 1.291  2019/05/09 13:44:18  brouard
                    332:   Summary: Before ncovmax
                    333: 
1.291     brouard   334:   Revision 1.290  2019/05/09 13:39:37  brouard
                    335:   Summary: 0.99r18 unlimited number of individuals
                    336: 
                    337:   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.
                    338: 
1.290     brouard   339:   Revision 1.289  2018/12/13 09:16:26  brouard
                    340:   Summary: Bug for young ages (<-30) will be in r17
                    341: 
1.289     brouard   342:   Revision 1.288  2018/05/02 20:58:27  brouard
                    343:   Summary: Some bugs fixed
                    344: 
1.288     brouard   345:   Revision 1.287  2018/05/01 17:57:25  brouard
                    346:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    347: 
1.287     brouard   348:   Revision 1.286  2018/04/27 14:27:04  brouard
                    349:   Summary: some minor bugs
                    350: 
1.286     brouard   351:   Revision 1.285  2018/04/21 21:02:16  brouard
                    352:   Summary: Some bugs fixed, valgrind tested
                    353: 
1.285     brouard   354:   Revision 1.284  2018/04/20 05:22:13  brouard
                    355:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    356: 
1.284     brouard   357:   Revision 1.283  2018/04/19 14:49:16  brouard
                    358:   Summary: Some minor bugs fixed
                    359: 
1.283     brouard   360:   Revision 1.282  2018/02/27 22:50:02  brouard
                    361:   *** empty log message ***
                    362: 
1.282     brouard   363:   Revision 1.281  2018/02/27 19:25:23  brouard
                    364:   Summary: Adding second argument for quitting
                    365: 
1.281     brouard   366:   Revision 1.280  2018/02/21 07:58:13  brouard
                    367:   Summary: 0.99r15
                    368: 
                    369:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    370: 
1.280     brouard   371:   Revision 1.279  2017/07/20 13:35:01  brouard
                    372:   Summary: temporary working
                    373: 
1.279     brouard   374:   Revision 1.278  2017/07/19 14:09:02  brouard
                    375:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    376: 
1.278     brouard   377:   Revision 1.277  2017/07/17 08:53:49  brouard
                    378:   Summary: BOM files can be read now
                    379: 
1.277     brouard   380:   Revision 1.276  2017/06/30 15:48:31  brouard
                    381:   Summary: Graphs improvements
                    382: 
1.276     brouard   383:   Revision 1.275  2017/06/30 13:39:33  brouard
                    384:   Summary: Saito's color
                    385: 
1.275     brouard   386:   Revision 1.274  2017/06/29 09:47:08  brouard
                    387:   Summary: Version 0.99r14
                    388: 
1.274     brouard   389:   Revision 1.273  2017/06/27 11:06:02  brouard
                    390:   Summary: More documentation on projections
                    391: 
1.273     brouard   392:   Revision 1.272  2017/06/27 10:22:40  brouard
                    393:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    394: 
1.272     brouard   395:   Revision 1.271  2017/06/27 10:17:50  brouard
                    396:   Summary: Some bug with rint
                    397: 
1.271     brouard   398:   Revision 1.270  2017/05/24 05:45:29  brouard
                    399:   *** empty log message ***
                    400: 
1.270     brouard   401:   Revision 1.269  2017/05/23 08:39:25  brouard
                    402:   Summary: Code into subroutine, cleanings
                    403: 
1.269     brouard   404:   Revision 1.268  2017/05/18 20:09:32  brouard
                    405:   Summary: backprojection and confidence intervals of backprevalence
                    406: 
1.268     brouard   407:   Revision 1.267  2017/05/13 10:25:05  brouard
                    408:   Summary: temporary save for backprojection
                    409: 
1.267     brouard   410:   Revision 1.266  2017/05/13 07:26:12  brouard
                    411:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    412: 
1.266     brouard   413:   Revision 1.265  2017/04/26 16:22:11  brouard
                    414:   Summary: imach 0.99r13 Some bugs fixed
                    415: 
1.265     brouard   416:   Revision 1.264  2017/04/26 06:01:29  brouard
                    417:   Summary: Labels in graphs
                    418: 
1.264     brouard   419:   Revision 1.263  2017/04/24 15:23:15  brouard
                    420:   Summary: to save
                    421: 
1.263     brouard   422:   Revision 1.262  2017/04/18 16:48:12  brouard
                    423:   *** empty log message ***
                    424: 
1.262     brouard   425:   Revision 1.261  2017/04/05 10:14:09  brouard
                    426:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    427: 
1.261     brouard   428:   Revision 1.260  2017/04/04 17:46:59  brouard
                    429:   Summary: Gnuplot indexations fixed (humm)
                    430: 
1.260     brouard   431:   Revision 1.259  2017/04/04 13:01:16  brouard
                    432:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    433: 
1.259     brouard   434:   Revision 1.258  2017/04/03 10:17:47  brouard
                    435:   Summary: Version 0.99r12
                    436: 
                    437:   Some cleanings, conformed with updated documentation.
                    438: 
1.258     brouard   439:   Revision 1.257  2017/03/29 16:53:30  brouard
                    440:   Summary: Temp
                    441: 
1.257     brouard   442:   Revision 1.256  2017/03/27 05:50:23  brouard
                    443:   Summary: Temporary
                    444: 
1.256     brouard   445:   Revision 1.255  2017/03/08 16:02:28  brouard
                    446:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    447: 
1.255     brouard   448:   Revision 1.254  2017/03/08 07:13:00  brouard
                    449:   Summary: Fixing data parameter line
                    450: 
1.254     brouard   451:   Revision 1.253  2016/12/15 11:59:41  brouard
                    452:   Summary: 0.99 in progress
                    453: 
1.253     brouard   454:   Revision 1.252  2016/09/15 21:15:37  brouard
                    455:   *** empty log message ***
                    456: 
1.252     brouard   457:   Revision 1.251  2016/09/15 15:01:13  brouard
                    458:   Summary: not working
                    459: 
1.251     brouard   460:   Revision 1.250  2016/09/08 16:07:27  brouard
                    461:   Summary: continue
                    462: 
1.250     brouard   463:   Revision 1.249  2016/09/07 17:14:18  brouard
                    464:   Summary: Starting values from frequencies
                    465: 
1.249     brouard   466:   Revision 1.248  2016/09/07 14:10:18  brouard
                    467:   *** empty log message ***
                    468: 
1.248     brouard   469:   Revision 1.247  2016/09/02 11:11:21  brouard
                    470:   *** empty log message ***
                    471: 
1.247     brouard   472:   Revision 1.246  2016/09/02 08:49:22  brouard
                    473:   *** empty log message ***
                    474: 
1.246     brouard   475:   Revision 1.245  2016/09/02 07:25:01  brouard
                    476:   *** empty log message ***
                    477: 
1.245     brouard   478:   Revision 1.244  2016/09/02 07:17:34  brouard
                    479:   *** empty log message ***
                    480: 
1.244     brouard   481:   Revision 1.243  2016/09/02 06:45:35  brouard
                    482:   *** empty log message ***
                    483: 
1.243     brouard   484:   Revision 1.242  2016/08/30 15:01:20  brouard
                    485:   Summary: Fixing a lots
                    486: 
1.242     brouard   487:   Revision 1.241  2016/08/29 17:17:25  brouard
                    488:   Summary: gnuplot problem in Back projection to fix
                    489: 
1.241     brouard   490:   Revision 1.240  2016/08/29 07:53:18  brouard
                    491:   Summary: Better
                    492: 
1.240     brouard   493:   Revision 1.239  2016/08/26 15:51:03  brouard
                    494:   Summary: Improvement in Powell output in order to copy and paste
                    495: 
                    496:   Author:
                    497: 
1.239     brouard   498:   Revision 1.238  2016/08/26 14:23:35  brouard
                    499:   Summary: Starting tests of 0.99
                    500: 
1.238     brouard   501:   Revision 1.237  2016/08/26 09:20:19  brouard
                    502:   Summary: to valgrind
                    503: 
1.237     brouard   504:   Revision 1.236  2016/08/25 10:50:18  brouard
                    505:   *** empty log message ***
                    506: 
1.236     brouard   507:   Revision 1.235  2016/08/25 06:59:23  brouard
                    508:   *** empty log message ***
                    509: 
1.235     brouard   510:   Revision 1.234  2016/08/23 16:51:20  brouard
                    511:   *** empty log message ***
                    512: 
1.234     brouard   513:   Revision 1.233  2016/08/23 07:40:50  brouard
                    514:   Summary: not working
                    515: 
1.233     brouard   516:   Revision 1.232  2016/08/22 14:20:21  brouard
                    517:   Summary: not working
                    518: 
1.232     brouard   519:   Revision 1.231  2016/08/22 07:17:15  brouard
                    520:   Summary: not working
                    521: 
1.231     brouard   522:   Revision 1.230  2016/08/22 06:55:53  brouard
                    523:   Summary: Not working
                    524: 
1.230     brouard   525:   Revision 1.229  2016/07/23 09:45:53  brouard
                    526:   Summary: Completing for func too
                    527: 
1.229     brouard   528:   Revision 1.228  2016/07/22 17:45:30  brouard
                    529:   Summary: Fixing some arrays, still debugging
                    530: 
1.227     brouard   531:   Revision 1.226  2016/07/12 18:42:34  brouard
                    532:   Summary: temp
                    533: 
1.226     brouard   534:   Revision 1.225  2016/07/12 08:40:03  brouard
                    535:   Summary: saving but not running
                    536: 
1.225     brouard   537:   Revision 1.224  2016/07/01 13:16:01  brouard
                    538:   Summary: Fixes
                    539: 
1.224     brouard   540:   Revision 1.223  2016/02/19 09:23:35  brouard
                    541:   Summary: temporary
                    542: 
1.223     brouard   543:   Revision 1.222  2016/02/17 08:14:50  brouard
                    544:   Summary: Probably last 0.98 stable version 0.98r6
                    545: 
1.222     brouard   546:   Revision 1.221  2016/02/15 23:35:36  brouard
                    547:   Summary: minor bug
                    548: 
1.220     brouard   549:   Revision 1.219  2016/02/15 00:48:12  brouard
                    550:   *** empty log message ***
                    551: 
1.219     brouard   552:   Revision 1.218  2016/02/12 11:29:23  brouard
                    553:   Summary: 0.99 Back projections
                    554: 
1.218     brouard   555:   Revision 1.217  2015/12/23 17:18:31  brouard
                    556:   Summary: Experimental backcast
                    557: 
1.217     brouard   558:   Revision 1.216  2015/12/18 17:32:11  brouard
                    559:   Summary: 0.98r4 Warning and status=-2
                    560: 
                    561:   Version 0.98r4 is now:
                    562:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    563:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    564:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    565: 
1.216     brouard   566:   Revision 1.215  2015/12/16 08:52:24  brouard
                    567:   Summary: 0.98r4 working
                    568: 
1.215     brouard   569:   Revision 1.214  2015/12/16 06:57:54  brouard
                    570:   Summary: temporary not working
                    571: 
1.214     brouard   572:   Revision 1.213  2015/12/11 18:22:17  brouard
                    573:   Summary: 0.98r4
                    574: 
1.213     brouard   575:   Revision 1.212  2015/11/21 12:47:24  brouard
                    576:   Summary: minor typo
                    577: 
1.212     brouard   578:   Revision 1.211  2015/11/21 12:41:11  brouard
                    579:   Summary: 0.98r3 with some graph of projected cross-sectional
                    580: 
                    581:   Author: Nicolas Brouard
                    582: 
1.211     brouard   583:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   584:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   585:   Summary: Adding ftolpl parameter
                    586:   Author: N Brouard
                    587: 
                    588:   We had difficulties to get smoothed confidence intervals. It was due
                    589:   to the period prevalence which wasn't computed accurately. The inner
                    590:   parameter ftolpl is now an outer parameter of the .imach parameter
                    591:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    592:   computation are long.
                    593: 
1.209     brouard   594:   Revision 1.208  2015/11/17 14:31:57  brouard
                    595:   Summary: temporary
                    596: 
1.208     brouard   597:   Revision 1.207  2015/10/27 17:36:57  brouard
                    598:   *** empty log message ***
                    599: 
1.207     brouard   600:   Revision 1.206  2015/10/24 07:14:11  brouard
                    601:   *** empty log message ***
                    602: 
1.206     brouard   603:   Revision 1.205  2015/10/23 15:50:53  brouard
                    604:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    605: 
1.205     brouard   606:   Revision 1.204  2015/10/01 16:20:26  brouard
                    607:   Summary: Some new graphs of contribution to likelihood
                    608: 
1.204     brouard   609:   Revision 1.203  2015/09/30 17:45:14  brouard
                    610:   Summary: looking at better estimation of the hessian
                    611: 
                    612:   Also a better criteria for convergence to the period prevalence And
                    613:   therefore adding the number of years needed to converge. (The
                    614:   prevalence in any alive state shold sum to one
                    615: 
1.203     brouard   616:   Revision 1.202  2015/09/22 19:45:16  brouard
                    617:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    618: 
1.202     brouard   619:   Revision 1.201  2015/09/15 17:34:58  brouard
                    620:   Summary: 0.98r0
                    621: 
                    622:   - Some new graphs like suvival functions
                    623:   - Some bugs fixed like model=1+age+V2.
                    624: 
1.201     brouard   625:   Revision 1.200  2015/09/09 16:53:55  brouard
                    626:   Summary: Big bug thanks to Flavia
                    627: 
                    628:   Even model=1+age+V2. did not work anymore
                    629: 
1.200     brouard   630:   Revision 1.199  2015/09/07 14:09:23  brouard
                    631:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    632: 
1.199     brouard   633:   Revision 1.198  2015/09/03 07:14:39  brouard
                    634:   Summary: 0.98q5 Flavia
                    635: 
1.198     brouard   636:   Revision 1.197  2015/09/01 18:24:39  brouard
                    637:   *** empty log message ***
                    638: 
1.197     brouard   639:   Revision 1.196  2015/08/18 23:17:52  brouard
                    640:   Summary: 0.98q5
                    641: 
1.196     brouard   642:   Revision 1.195  2015/08/18 16:28:39  brouard
                    643:   Summary: Adding a hack for testing purpose
                    644: 
                    645:   After reading the title, ftol and model lines, if the comment line has
                    646:   a q, starting with #q, the answer at the end of the run is quit. It
                    647:   permits to run test files in batch with ctest. The former workaround was
                    648:   $ echo q | imach foo.imach
                    649: 
1.195     brouard   650:   Revision 1.194  2015/08/18 13:32:00  brouard
                    651:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    652: 
1.194     brouard   653:   Revision 1.193  2015/08/04 07:17:42  brouard
                    654:   Summary: 0.98q4
                    655: 
1.193     brouard   656:   Revision 1.192  2015/07/16 16:49:02  brouard
                    657:   Summary: Fixing some outputs
                    658: 
1.192     brouard   659:   Revision 1.191  2015/07/14 10:00:33  brouard
                    660:   Summary: Some fixes
                    661: 
1.191     brouard   662:   Revision 1.190  2015/05/05 08:51:13  brouard
                    663:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    664: 
                    665:   Fix 1+age+.
                    666: 
1.190     brouard   667:   Revision 1.189  2015/04/30 14:45:16  brouard
                    668:   Summary: 0.98q2
                    669: 
1.189     brouard   670:   Revision 1.188  2015/04/30 08:27:53  brouard
                    671:   *** empty log message ***
                    672: 
1.188     brouard   673:   Revision 1.187  2015/04/29 09:11:15  brouard
                    674:   *** empty log message ***
                    675: 
1.187     brouard   676:   Revision 1.186  2015/04/23 12:01:52  brouard
                    677:   Summary: V1*age is working now, version 0.98q1
                    678: 
                    679:   Some codes had been disabled in order to simplify and Vn*age was
                    680:   working in the optimization phase, ie, giving correct MLE parameters,
                    681:   but, as usual, outputs were not correct and program core dumped.
                    682: 
1.186     brouard   683:   Revision 1.185  2015/03/11 13:26:42  brouard
                    684:   Summary: Inclusion of compile and links command line for Intel Compiler
                    685: 
1.185     brouard   686:   Revision 1.184  2015/03/11 11:52:39  brouard
                    687:   Summary: Back from Windows 8. Intel Compiler
                    688: 
1.184     brouard   689:   Revision 1.183  2015/03/10 20:34:32  brouard
                    690:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    691: 
                    692:   We use directest instead of original Powell test; probably no
                    693:   incidence on the results, but better justifications;
                    694:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    695:   wrong results.
                    696: 
1.183     brouard   697:   Revision 1.182  2015/02/12 08:19:57  brouard
                    698:   Summary: Trying to keep directest which seems simpler and more general
                    699:   Author: Nicolas Brouard
                    700: 
1.182     brouard   701:   Revision 1.181  2015/02/11 23:22:24  brouard
                    702:   Summary: Comments on Powell added
                    703: 
                    704:   Author:
                    705: 
1.181     brouard   706:   Revision 1.180  2015/02/11 17:33:45  brouard
                    707:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    708: 
1.180     brouard   709:   Revision 1.179  2015/01/04 09:57:06  brouard
                    710:   Summary: back to OS/X
                    711: 
1.179     brouard   712:   Revision 1.178  2015/01/04 09:35:48  brouard
                    713:   *** empty log message ***
                    714: 
1.178     brouard   715:   Revision 1.177  2015/01/03 18:40:56  brouard
                    716:   Summary: Still testing ilc32 on OSX
                    717: 
1.177     brouard   718:   Revision 1.176  2015/01/03 16:45:04  brouard
                    719:   *** empty log message ***
                    720: 
1.176     brouard   721:   Revision 1.175  2015/01/03 16:33:42  brouard
                    722:   *** empty log message ***
                    723: 
1.175     brouard   724:   Revision 1.174  2015/01/03 16:15:49  brouard
                    725:   Summary: Still in cross-compilation
                    726: 
1.174     brouard   727:   Revision 1.173  2015/01/03 12:06:26  brouard
                    728:   Summary: trying to detect cross-compilation
                    729: 
1.173     brouard   730:   Revision 1.172  2014/12/27 12:07:47  brouard
                    731:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    732: 
1.172     brouard   733:   Revision 1.171  2014/12/23 13:26:59  brouard
                    734:   Summary: Back from Visual C
                    735: 
                    736:   Still problem with utsname.h on Windows
                    737: 
1.171     brouard   738:   Revision 1.170  2014/12/23 11:17:12  brouard
                    739:   Summary: Cleaning some \%% back to %%
                    740: 
                    741:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    742: 
1.170     brouard   743:   Revision 1.169  2014/12/22 23:08:31  brouard
                    744:   Summary: 0.98p
                    745: 
                    746:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    747: 
1.169     brouard   748:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   749:   Summary: update
1.169     brouard   750: 
1.168     brouard   751:   Revision 1.167  2014/12/22 13:50:56  brouard
                    752:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    753: 
                    754:   Testing on Linux 64
                    755: 
1.167     brouard   756:   Revision 1.166  2014/12/22 11:40:47  brouard
                    757:   *** empty log message ***
                    758: 
1.166     brouard   759:   Revision 1.165  2014/12/16 11:20:36  brouard
                    760:   Summary: After compiling on Visual C
                    761: 
                    762:   * imach.c (Module): Merging 1.61 to 1.162
                    763: 
1.165     brouard   764:   Revision 1.164  2014/12/16 10:52:11  brouard
                    765:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    766: 
                    767:   * imach.c (Module): Merging 1.61 to 1.162
                    768: 
1.164     brouard   769:   Revision 1.163  2014/12/16 10:30:11  brouard
                    770:   * imach.c (Module): Merging 1.61 to 1.162
                    771: 
1.163     brouard   772:   Revision 1.162  2014/09/25 11:43:39  brouard
                    773:   Summary: temporary backup 0.99!
                    774: 
1.162     brouard   775:   Revision 1.1  2014/09/16 11:06:58  brouard
                    776:   Summary: With some code (wrong) for nlopt
                    777: 
                    778:   Author:
                    779: 
                    780:   Revision 1.161  2014/09/15 20:41:41  brouard
                    781:   Summary: Problem with macro SQR on Intel compiler
                    782: 
1.161     brouard   783:   Revision 1.160  2014/09/02 09:24:05  brouard
                    784:   *** empty log message ***
                    785: 
1.160     brouard   786:   Revision 1.159  2014/09/01 10:34:10  brouard
                    787:   Summary: WIN32
                    788:   Author: Brouard
                    789: 
1.159     brouard   790:   Revision 1.158  2014/08/27 17:11:51  brouard
                    791:   *** empty log message ***
                    792: 
1.158     brouard   793:   Revision 1.157  2014/08/27 16:26:55  brouard
                    794:   Summary: Preparing windows Visual studio version
                    795:   Author: Brouard
                    796: 
                    797:   In order to compile on Visual studio, time.h is now correct and time_t
                    798:   and tm struct should be used. difftime should be used but sometimes I
                    799:   just make the differences in raw time format (time(&now).
                    800:   Trying to suppress #ifdef LINUX
                    801:   Add xdg-open for __linux in order to open default browser.
                    802: 
1.157     brouard   803:   Revision 1.156  2014/08/25 20:10:10  brouard
                    804:   *** empty log message ***
                    805: 
1.156     brouard   806:   Revision 1.155  2014/08/25 18:32:34  brouard
                    807:   Summary: New compile, minor changes
                    808:   Author: Brouard
                    809: 
1.155     brouard   810:   Revision 1.154  2014/06/20 17:32:08  brouard
                    811:   Summary: Outputs now all graphs of convergence to period prevalence
                    812: 
1.154     brouard   813:   Revision 1.153  2014/06/20 16:45:46  brouard
                    814:   Summary: If 3 live state, convergence to period prevalence on same graph
                    815:   Author: Brouard
                    816: 
1.153     brouard   817:   Revision 1.152  2014/06/18 17:54:09  brouard
                    818:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    819: 
1.152     brouard   820:   Revision 1.151  2014/06/18 16:43:30  brouard
                    821:   *** empty log message ***
                    822: 
1.151     brouard   823:   Revision 1.150  2014/06/18 16:42:35  brouard
                    824:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    825:   Author: brouard
                    826: 
1.150     brouard   827:   Revision 1.149  2014/06/18 15:51:14  brouard
                    828:   Summary: Some fixes in parameter files errors
                    829:   Author: Nicolas Brouard
                    830: 
1.149     brouard   831:   Revision 1.148  2014/06/17 17:38:48  brouard
                    832:   Summary: Nothing new
                    833:   Author: Brouard
                    834: 
                    835:   Just a new packaging for OS/X version 0.98nS
                    836: 
1.148     brouard   837:   Revision 1.147  2014/06/16 10:33:11  brouard
                    838:   *** empty log message ***
                    839: 
1.147     brouard   840:   Revision 1.146  2014/06/16 10:20:28  brouard
                    841:   Summary: Merge
                    842:   Author: Brouard
                    843: 
                    844:   Merge, before building revised version.
                    845: 
1.146     brouard   846:   Revision 1.145  2014/06/10 21:23:15  brouard
                    847:   Summary: Debugging with valgrind
                    848:   Author: Nicolas Brouard
                    849: 
                    850:   Lot of changes in order to output the results with some covariates
                    851:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    852:   improve the code.
                    853:   No more memory valgrind error but a lot has to be done in order to
                    854:   continue the work of splitting the code into subroutines.
                    855:   Also, decodemodel has been improved. Tricode is still not
                    856:   optimal. nbcode should be improved. Documentation has been added in
                    857:   the source code.
                    858: 
1.144     brouard   859:   Revision 1.143  2014/01/26 09:45:38  brouard
                    860:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    861: 
                    862:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    863:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    864: 
1.143     brouard   865:   Revision 1.142  2014/01/26 03:57:36  brouard
                    866:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    867: 
                    868:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    869: 
1.142     brouard   870:   Revision 1.141  2014/01/26 02:42:01  brouard
                    871:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    872: 
1.141     brouard   873:   Revision 1.140  2011/09/02 10:37:54  brouard
                    874:   Summary: times.h is ok with mingw32 now.
                    875: 
1.140     brouard   876:   Revision 1.139  2010/06/14 07:50:17  brouard
                    877:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    878:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    879: 
1.139     brouard   880:   Revision 1.138  2010/04/30 18:19:40  brouard
                    881:   *** empty log message ***
                    882: 
1.138     brouard   883:   Revision 1.137  2010/04/29 18:11:38  brouard
                    884:   (Module): Checking covariates for more complex models
                    885:   than V1+V2. A lot of change to be done. Unstable.
                    886: 
1.137     brouard   887:   Revision 1.136  2010/04/26 20:30:53  brouard
                    888:   (Module): merging some libgsl code. Fixing computation
                    889:   of likelione (using inter/intrapolation if mle = 0) in order to
                    890:   get same likelihood as if mle=1.
                    891:   Some cleaning of code and comments added.
                    892: 
1.136     brouard   893:   Revision 1.135  2009/10/29 15:33:14  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.135     brouard   896:   Revision 1.134  2009/10/29 13:18:53  brouard
                    897:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    898: 
1.134     brouard   899:   Revision 1.133  2009/07/06 10:21:25  brouard
                    900:   just nforces
                    901: 
1.133     brouard   902:   Revision 1.132  2009/07/06 08:22:05  brouard
                    903:   Many tings
                    904: 
1.132     brouard   905:   Revision 1.131  2009/06/20 16:22:47  brouard
                    906:   Some dimensions resccaled
                    907: 
1.131     brouard   908:   Revision 1.130  2009/05/26 06:44:34  brouard
                    909:   (Module): Max Covariate is now set to 20 instead of 8. A
                    910:   lot of cleaning with variables initialized to 0. Trying to make
                    911:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    912: 
1.130     brouard   913:   Revision 1.129  2007/08/31 13:49:27  lievre
                    914:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    915: 
1.129     lievre    916:   Revision 1.128  2006/06/30 13:02:05  brouard
                    917:   (Module): Clarifications on computing e.j
                    918: 
1.128     brouard   919:   Revision 1.127  2006/04/28 18:11:50  brouard
                    920:   (Module): Yes the sum of survivors was wrong since
                    921:   imach-114 because nhstepm was no more computed in the age
                    922:   loop. Now we define nhstepma in the age loop.
                    923:   (Module): In order to speed up (in case of numerous covariates) we
                    924:   compute health expectancies (without variances) in a first step
                    925:   and then all the health expectancies with variances or standard
                    926:   deviation (needs data from the Hessian matrices) which slows the
                    927:   computation.
                    928:   In the future we should be able to stop the program is only health
                    929:   expectancies and graph are needed without standard deviations.
                    930: 
1.127     brouard   931:   Revision 1.126  2006/04/28 17:23:28  brouard
                    932:   (Module): Yes the sum of survivors was wrong since
                    933:   imach-114 because nhstepm was no more computed in the age
                    934:   loop. Now we define nhstepma in the age loop.
                    935:   Version 0.98h
                    936: 
1.126     brouard   937:   Revision 1.125  2006/04/04 15:20:31  lievre
                    938:   Errors in calculation of health expectancies. Age was not initialized.
                    939:   Forecasting file added.
                    940: 
                    941:   Revision 1.124  2006/03/22 17:13:53  lievre
                    942:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    943:   The log-likelihood is printed in the log file
                    944: 
                    945:   Revision 1.123  2006/03/20 10:52:43  brouard
                    946:   * imach.c (Module): <title> changed, corresponds to .htm file
                    947:   name. <head> headers where missing.
                    948: 
                    949:   * imach.c (Module): Weights can have a decimal point as for
                    950:   English (a comma might work with a correct LC_NUMERIC environment,
                    951:   otherwise the weight is truncated).
                    952:   Modification of warning when the covariates values are not 0 or
                    953:   1.
                    954:   Version 0.98g
                    955: 
                    956:   Revision 1.122  2006/03/20 09:45:41  brouard
                    957:   (Module): Weights can have a decimal point as for
                    958:   English (a comma might work with a correct LC_NUMERIC environment,
                    959:   otherwise the weight is truncated).
                    960:   Modification of warning when the covariates values are not 0 or
                    961:   1.
                    962:   Version 0.98g
                    963: 
                    964:   Revision 1.121  2006/03/16 17:45:01  lievre
                    965:   * imach.c (Module): Comments concerning covariates added
                    966: 
                    967:   * imach.c (Module): refinements in the computation of lli if
                    968:   status=-2 in order to have more reliable computation if stepm is
                    969:   not 1 month. Version 0.98f
                    970: 
                    971:   Revision 1.120  2006/03/16 15:10:38  lievre
                    972:   (Module): refinements in the computation of lli if
                    973:   status=-2 in order to have more reliable computation if stepm is
                    974:   not 1 month. Version 0.98f
                    975: 
                    976:   Revision 1.119  2006/03/15 17:42:26  brouard
                    977:   (Module): Bug if status = -2, the loglikelihood was
                    978:   computed as likelihood omitting the logarithm. Version O.98e
                    979: 
                    980:   Revision 1.118  2006/03/14 18:20:07  brouard
                    981:   (Module): varevsij Comments added explaining the second
                    982:   table of variances if popbased=1 .
                    983:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    984:   (Module): Function pstamp added
                    985:   (Module): Version 0.98d
                    986: 
                    987:   Revision 1.117  2006/03/14 17:16:22  brouard
                    988:   (Module): varevsij Comments added explaining the second
                    989:   table of variances if popbased=1 .
                    990:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    991:   (Module): Function pstamp added
                    992:   (Module): Version 0.98d
                    993: 
                    994:   Revision 1.116  2006/03/06 10:29:27  brouard
                    995:   (Module): Variance-covariance wrong links and
                    996:   varian-covariance of ej. is needed (Saito).
                    997: 
                    998:   Revision 1.115  2006/02/27 12:17:45  brouard
                    999:   (Module): One freematrix added in mlikeli! 0.98c
                   1000: 
                   1001:   Revision 1.114  2006/02/26 12:57:58  brouard
                   1002:   (Module): Some improvements in processing parameter
                   1003:   filename with strsep.
                   1004: 
                   1005:   Revision 1.113  2006/02/24 14:20:24  brouard
                   1006:   (Module): Memory leaks checks with valgrind and:
                   1007:   datafile was not closed, some imatrix were not freed and on matrix
                   1008:   allocation too.
                   1009: 
                   1010:   Revision 1.112  2006/01/30 09:55:26  brouard
                   1011:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                   1012: 
                   1013:   Revision 1.111  2006/01/25 20:38:18  brouard
                   1014:   (Module): Lots of cleaning and bugs added (Gompertz)
                   1015:   (Module): Comments can be added in data file. Missing date values
                   1016:   can be a simple dot '.'.
                   1017: 
                   1018:   Revision 1.110  2006/01/25 00:51:50  brouard
                   1019:   (Module): Lots of cleaning and bugs added (Gompertz)
                   1020: 
                   1021:   Revision 1.109  2006/01/24 19:37:15  brouard
                   1022:   (Module): Comments (lines starting with a #) are allowed in data.
                   1023: 
                   1024:   Revision 1.108  2006/01/19 18:05:42  lievre
                   1025:   Gnuplot problem appeared...
                   1026:   To be fixed
                   1027: 
                   1028:   Revision 1.107  2006/01/19 16:20:37  brouard
                   1029:   Test existence of gnuplot in imach path
                   1030: 
                   1031:   Revision 1.106  2006/01/19 13:24:36  brouard
                   1032:   Some cleaning and links added in html output
                   1033: 
                   1034:   Revision 1.105  2006/01/05 20:23:19  lievre
                   1035:   *** empty log message ***
                   1036: 
                   1037:   Revision 1.104  2005/09/30 16:11:43  lievre
                   1038:   (Module): sump fixed, loop imx fixed, and simplifications.
                   1039:   (Module): If the status is missing at the last wave but we know
                   1040:   that the person is alive, then we can code his/her status as -2
                   1041:   (instead of missing=-1 in earlier versions) and his/her
                   1042:   contributions to the likelihood is 1 - Prob of dying from last
                   1043:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                   1044:   the healthy state at last known wave). Version is 0.98
                   1045: 
                   1046:   Revision 1.103  2005/09/30 15:54:49  lievre
                   1047:   (Module): sump fixed, loop imx fixed, and simplifications.
                   1048: 
                   1049:   Revision 1.102  2004/09/15 17:31:30  brouard
                   1050:   Add the possibility to read data file including tab characters.
                   1051: 
                   1052:   Revision 1.101  2004/09/15 10:38:38  brouard
                   1053:   Fix on curr_time
                   1054: 
                   1055:   Revision 1.100  2004/07/12 18:29:06  brouard
                   1056:   Add version for Mac OS X. Just define UNIX in Makefile
                   1057: 
                   1058:   Revision 1.99  2004/06/05 08:57:40  brouard
                   1059:   *** empty log message ***
                   1060: 
                   1061:   Revision 1.98  2004/05/16 15:05:56  brouard
                   1062:   New version 0.97 . First attempt to estimate force of mortality
                   1063:   directly from the data i.e. without the need of knowing the health
                   1064:   state at each age, but using a Gompertz model: log u =a + b*age .
                   1065:   This is the basic analysis of mortality and should be done before any
                   1066:   other analysis, in order to test if the mortality estimated from the
                   1067:   cross-longitudinal survey is different from the mortality estimated
                   1068:   from other sources like vital statistic data.
                   1069: 
                   1070:   The same imach parameter file can be used but the option for mle should be -3.
                   1071: 
1.324     brouard  1072:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard  1073:   former routines in order to include the new code within the former code.
                   1074: 
                   1075:   The output is very simple: only an estimate of the intercept and of
                   1076:   the slope with 95% confident intervals.
                   1077: 
                   1078:   Current limitations:
                   1079:   A) Even if you enter covariates, i.e. with the
                   1080:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                   1081:   B) There is no computation of Life Expectancy nor Life Table.
                   1082: 
                   1083:   Revision 1.97  2004/02/20 13:25:42  lievre
                   1084:   Version 0.96d. Population forecasting command line is (temporarily)
                   1085:   suppressed.
                   1086: 
                   1087:   Revision 1.96  2003/07/15 15:38:55  brouard
                   1088:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                   1089:   rewritten within the same printf. Workaround: many printfs.
                   1090: 
                   1091:   Revision 1.95  2003/07/08 07:54:34  brouard
                   1092:   * imach.c (Repository):
                   1093:   (Repository): Using imachwizard code to output a more meaningful covariance
                   1094:   matrix (cov(a12,c31) instead of numbers.
                   1095: 
                   1096:   Revision 1.94  2003/06/27 13:00:02  brouard
                   1097:   Just cleaning
                   1098: 
                   1099:   Revision 1.93  2003/06/25 16:33:55  brouard
                   1100:   (Module): On windows (cygwin) function asctime_r doesn't
                   1101:   exist so I changed back to asctime which exists.
                   1102:   (Module): Version 0.96b
                   1103: 
                   1104:   Revision 1.92  2003/06/25 16:30:45  brouard
                   1105:   (Module): On windows (cygwin) function asctime_r doesn't
                   1106:   exist so I changed back to asctime which exists.
                   1107: 
                   1108:   Revision 1.91  2003/06/25 15:30:29  brouard
                   1109:   * imach.c (Repository): Duplicated warning errors corrected.
                   1110:   (Repository): Elapsed time after each iteration is now output. It
                   1111:   helps to forecast when convergence will be reached. Elapsed time
                   1112:   is stamped in powell.  We created a new html file for the graphs
                   1113:   concerning matrix of covariance. It has extension -cov.htm.
                   1114: 
                   1115:   Revision 1.90  2003/06/24 12:34:15  brouard
                   1116:   (Module): Some bugs corrected for windows. Also, when
                   1117:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1118:   of the covariance matrix to be input.
                   1119: 
                   1120:   Revision 1.89  2003/06/24 12:30:52  brouard
                   1121:   (Module): Some bugs corrected for windows. Also, when
                   1122:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1123:   of the covariance matrix to be input.
                   1124: 
                   1125:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1126:   * 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.
                   1127: 
                   1128:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1129:   Version 0.96
                   1130: 
                   1131:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1132:   (Module): Change position of html and gnuplot routines and added
                   1133:   routine fileappend.
                   1134: 
                   1135:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1136:   * imach.c (Repository): Check when date of death was earlier that
                   1137:   current date of interview. It may happen when the death was just
                   1138:   prior to the death. In this case, dh was negative and likelihood
                   1139:   was wrong (infinity). We still send an "Error" but patch by
                   1140:   assuming that the date of death was just one stepm after the
                   1141:   interview.
                   1142:   (Repository): Because some people have very long ID (first column)
                   1143:   we changed int to long in num[] and we added a new lvector for
                   1144:   memory allocation. But we also truncated to 8 characters (left
                   1145:   truncation)
                   1146:   (Repository): No more line truncation errors.
                   1147: 
                   1148:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1149:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1150:   place. It differs from routine "prevalence" which may be called
                   1151:   many times. Probs is memory consuming and must be used with
                   1152:   parcimony.
                   1153:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1154: 
                   1155:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1156:   *** empty log message ***
                   1157: 
                   1158:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1159:   Add log in  imach.c and  fullversion number is now printed.
                   1160: 
                   1161: */
                   1162: /*
                   1163:    Interpolated Markov Chain
                   1164: 
                   1165:   Short summary of the programme:
                   1166:   
1.227     brouard  1167:   This program computes Healthy Life Expectancies or State-specific
                   1168:   (if states aren't health statuses) Expectancies from
                   1169:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1170: 
                   1171:   -1- a first survey ("cross") where individuals from different ages
                   1172:   are interviewed on their health status or degree of disability (in
                   1173:   the case of a health survey which is our main interest)
                   1174: 
                   1175:   -2- at least a second wave of interviews ("longitudinal") which
                   1176:   measure each change (if any) in individual health status.  Health
                   1177:   expectancies are computed from the time spent in each health state
                   1178:   according to a model. More health states you consider, more time is
                   1179:   necessary to reach the Maximum Likelihood of the parameters involved
                   1180:   in the model.  The simplest model is the multinomial logistic model
                   1181:   where pij is the probability to be observed in state j at the second
                   1182:   wave conditional to be observed in state i at the first
                   1183:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1184:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1185:   have a more complex model than "constant and age", you should modify
                   1186:   the program where the markup *Covariates have to be included here
                   1187:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1188:   convergence.
                   1189: 
                   1190:   The advantage of this computer programme, compared to a simple
                   1191:   multinomial logistic model, is clear when the delay between waves is not
                   1192:   identical for each individual. Also, if a individual missed an
                   1193:   intermediate interview, the information is lost, but taken into
                   1194:   account using an interpolation or extrapolation.  
                   1195: 
                   1196:   hPijx is the probability to be observed in state i at age x+h
                   1197:   conditional to the observed state i at age x. The delay 'h' can be
                   1198:   split into an exact number (nh*stepm) of unobserved intermediate
                   1199:   states. This elementary transition (by month, quarter,
                   1200:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1201:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1202:   and the contribution of each individual to the likelihood is simply
                   1203:   hPijx.
                   1204: 
                   1205:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1206:   of the life expectancies. It also computes the period (stable) prevalence.
                   1207: 
                   1208: Back prevalence and projections:
1.227     brouard  1209: 
                   1210:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1211:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1212:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1213:    mobilavproj)
                   1214: 
                   1215:     Computes the back prevalence limit for any combination of
                   1216:     covariate values k at any age between ageminpar and agemaxpar and
                   1217:     returns it in **bprlim. In the loops,
                   1218: 
                   1219:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1220:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1221: 
                   1222:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1223:    Computes for any combination of covariates k and any age between bage and fage 
                   1224:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1225:                        oldm=oldms;savm=savms;
1.227     brouard  1226: 
1.267     brouard  1227:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1228:      Computes the transition matrix starting at age 'age' over
                   1229:      'nhstepm*hstepm*stepm' months (i.e. until
                   1230:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1231:      nhstepm*hstepm matrices. 
                   1232: 
                   1233:      Returns p3mat[i][j][h] after calling
                   1234:      p3mat[i][j][h]=matprod2(newm,
                   1235:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1236:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1237:      oldm);
1.226     brouard  1238: 
                   1239: Important routines
                   1240: 
                   1241: - func (or funcone), computes logit (pij) distinguishing
                   1242:   o fixed variables (single or product dummies or quantitative);
                   1243:   o varying variables by:
                   1244:    (1) wave (single, product dummies, quantitative), 
                   1245:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1246:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1247:        % varying dummy (not done) or quantitative (not done);
                   1248: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1249:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1250: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.364   ! brouard  1251:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, eliminating 1 1 if
1.226     brouard  1252:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1253: 
1.226     brouard  1254: 
                   1255:   
1.324     brouard  1256:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1257:            Institut national d'études démographiques, Paris.
1.126     brouard  1258:   This software have been partly granted by Euro-REVES, a concerted action
                   1259:   from the European Union.
                   1260:   It is copyrighted identically to a GNU software product, ie programme and
                   1261:   software can be distributed freely for non commercial use. Latest version
                   1262:   can be accessed at http://euroreves.ined.fr/imach .
                   1263: 
                   1264:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1265:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1266:   
                   1267:   **********************************************************************/
                   1268: /*
                   1269:   main
                   1270:   read parameterfile
                   1271:   read datafile
                   1272:   concatwav
                   1273:   freqsummary
                   1274:   if (mle >= 1)
                   1275:     mlikeli
                   1276:   print results files
                   1277:   if mle==1 
                   1278:      computes hessian
                   1279:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1280:       begin-prev-date,...
                   1281:   open gnuplot file
                   1282:   open html file
1.145     brouard  1283:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1284:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1285:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1286:     freexexit2 possible for memory heap.
                   1287: 
                   1288:   h Pij x                         | pij_nom  ficrestpij
                   1289:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1290:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1291:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1292: 
                   1293:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1294:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1295:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1296:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1297:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1298: 
1.126     brouard  1299:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1300:   health expectancies
                   1301:   Variance-covariance of DFLE
                   1302:   prevalence()
                   1303:    movingaverage()
                   1304:   varevsij() 
                   1305:   if popbased==1 varevsij(,popbased)
                   1306:   total life expectancies
                   1307:   Variance of period (stable) prevalence
                   1308:  end
                   1309: */
                   1310: 
1.187     brouard  1311: /* #define DEBUG */
                   1312: /* #define DEBUGBRENT */
1.203     brouard  1313: /* #define DEBUGLINMIN */
                   1314: /* #define DEBUGHESS */
                   1315: #define DEBUGHESSIJ
1.224     brouard  1316: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1317: #define POWELL /* Instead of NLOPT */
1.224     brouard  1318: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1319: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1320: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1321: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.359     brouard  1322: /* #define POWELLORIGINCONJUGATE  /\* Don't use conjugate but biggest decrease if valuable *\/ */
                   1323: /* #define NOTMINFIT */
1.126     brouard  1324: 
                   1325: #include <math.h>
                   1326: #include <stdio.h>
                   1327: #include <stdlib.h>
                   1328: #include <string.h>
1.226     brouard  1329: #include <ctype.h>
1.159     brouard  1330: 
                   1331: #ifdef _WIN32
                   1332: #include <io.h>
1.172     brouard  1333: #include <windows.h>
                   1334: #include <tchar.h>
1.159     brouard  1335: #else
1.126     brouard  1336: #include <unistd.h>
1.159     brouard  1337: #endif
1.126     brouard  1338: 
                   1339: #include <limits.h>
                   1340: #include <sys/types.h>
1.171     brouard  1341: 
                   1342: #if defined(__GNUC__)
                   1343: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1344: #endif
                   1345: 
1.126     brouard  1346: #include <sys/stat.h>
                   1347: #include <errno.h>
1.159     brouard  1348: /* extern int errno; */
1.126     brouard  1349: 
1.157     brouard  1350: /* #ifdef LINUX */
                   1351: /* #include <time.h> */
                   1352: /* #include "timeval.h" */
                   1353: /* #else */
                   1354: /* #include <sys/time.h> */
                   1355: /* #endif */
                   1356: 
1.126     brouard  1357: #include <time.h>
                   1358: 
1.136     brouard  1359: #ifdef GSL
                   1360: #include <gsl/gsl_errno.h>
                   1361: #include <gsl/gsl_multimin.h>
                   1362: #endif
                   1363: 
1.167     brouard  1364: 
1.162     brouard  1365: #ifdef NLOPT
                   1366: #include <nlopt.h>
                   1367: typedef struct {
                   1368:   double (* function)(double [] );
                   1369: } myfunc_data ;
                   1370: #endif
                   1371: 
1.126     brouard  1372: /* #include <libintl.h> */
                   1373: /* #define _(String) gettext (String) */
                   1374: 
1.349     brouard  1375: #define MAXLINE 16384 /* Was 256 and 1024 and 2048. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1376: 
                   1377: #define GNUPLOTPROGRAM "gnuplot"
1.343     brouard  1378: #define GNUPLOTVERSION 5.1
                   1379: double gnuplotversion=GNUPLOTVERSION;
1.126     brouard  1380: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1381: #define FILENAMELENGTH 256
1.126     brouard  1382: 
                   1383: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1384: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1385: 
1.349     brouard  1386: #define MAXPARM 216 /**< Maximum number of parameters for the optimization was 128 */
1.144     brouard  1387: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1388: 
                   1389: #define NINTERVMAX 8
1.144     brouard  1390: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1391: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1392: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1393: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1394: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1395: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1396: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1397: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1398: /* #define AGESUP 130 */
1.288     brouard  1399: /* #define AGESUP 150 */
                   1400: #define AGESUP 200
1.268     brouard  1401: #define AGEINF 0
1.218     brouard  1402: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1403: #define AGEBASE 40
1.194     brouard  1404: #define AGEOVERFLOW 1.e20
1.164     brouard  1405: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1406: #ifdef _WIN32
                   1407: #define DIRSEPARATOR '\\'
                   1408: #define CHARSEPARATOR "\\"
                   1409: #define ODIRSEPARATOR '/'
                   1410: #else
1.126     brouard  1411: #define DIRSEPARATOR '/'
                   1412: #define CHARSEPARATOR "/"
                   1413: #define ODIRSEPARATOR '\\'
                   1414: #endif
                   1415: 
1.364   ! brouard  1416: /* $Id: imach.c,v 1.363 2024/06/28 09:31:55 brouard Exp $ */
1.126     brouard  1417: /* $State: Exp $ */
1.196     brouard  1418: #include "version.h"
                   1419: char version[]=__IMACH_VERSION__;
1.360     brouard  1420: 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.364   ! brouard  1421: char fullversion[]="$Revision: 1.363 $ $Date: 2024/06/28 09:31:55 $"; 
1.126     brouard  1422: char strstart[80];
                   1423: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1424: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.342     brouard  1425: int debugILK=0; /* debugILK is set by a #d in a comment line */
1.187     brouard  1426: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1427: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1428: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
1.335     brouard  1429: 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  1430: 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  1431: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1432: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1433: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
1.349     brouard  1434: int cptcovprodage=0; /**< Number of fixed covariates with age: V3*age or V2*V3*age 1 */
                   1435: int cptcovprodvage=0; /**< Number of varying covariates with age: V7*age or V7*V6*age */
                   1436: int cptcovdageprod=0; /**< Number of doubleproducts with age, since 0.99r44 only: age*Vn*Vm for gnuplot printing*/
1.145     brouard  1437: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335     brouard  1438: 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  1439: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1440: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.339     brouard  1441: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
1.349     brouard  1442: 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 */
                   1443: 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 */
                   1444: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (single or product, dummy or quantitative) in the model */
                   1445: 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  1446: int nsd=0; /**< Total number of single dummy variables (output) */
                   1447: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1448: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1449: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1450: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1451: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1452: int cptcov=0; /* Working variable */
1.334     brouard  1453: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1454: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1455: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1456: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1457: int nlstate=2; /* Number of live states */
                   1458: int ndeath=1; /* Number of dead states */
1.130     brouard  1459: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.339     brouard  1460: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
                   1461: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
1.126     brouard  1462: int popbased=0;
                   1463: 
                   1464: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1465: int maxwav=0; /* Maxim number of waves */
                   1466: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1467: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
1.359     brouard  1468: int gipmx = 0;
                   1469: double gsw = 0; /* Global variables on the number of contributions
1.126     brouard  1470:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1471: int mle=1, weightopt=0;
1.126     brouard  1472: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1473: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1474: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1475:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1476: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1477: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1478: 
1.130     brouard  1479: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1480: double **matprod2(); /* test */
1.126     brouard  1481: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1482: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1483: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1484: 
1.136     brouard  1485: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1486: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1487: FILE *ficlog, *ficrespow;
1.130     brouard  1488: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1489: double fretone; /* Only one call to likelihood */
1.130     brouard  1490: long ipmx=0; /* Number of contributions */
1.126     brouard  1491: double sw; /* Sum of weights */
                   1492: char filerespow[FILENAMELENGTH];
                   1493: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1494: FILE *ficresilk;
                   1495: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1496: FILE *ficresprobmorprev;
                   1497: FILE *fichtm, *fichtmcov; /* Html File */
                   1498: FILE *ficreseij;
                   1499: char filerese[FILENAMELENGTH];
                   1500: FILE *ficresstdeij;
                   1501: char fileresstde[FILENAMELENGTH];
                   1502: FILE *ficrescveij;
                   1503: char filerescve[FILENAMELENGTH];
                   1504: FILE  *ficresvij;
                   1505: char fileresv[FILENAMELENGTH];
1.269     brouard  1506: 
1.126     brouard  1507: char title[MAXLINE];
1.234     brouard  1508: char model[MAXLINE]; /**< The model line */
1.217     brouard  1509: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1510: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1511: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1512: char command[FILENAMELENGTH];
                   1513: int  outcmd=0;
                   1514: 
1.217     brouard  1515: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1516: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1517: char filelog[FILENAMELENGTH]; /* Log file */
                   1518: char filerest[FILENAMELENGTH];
                   1519: char fileregp[FILENAMELENGTH];
                   1520: char popfile[FILENAMELENGTH];
                   1521: 
                   1522: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1523: 
1.157     brouard  1524: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1525: /* struct timezone tzp; */
                   1526: /* extern int gettimeofday(); */
                   1527: struct tm tml, *gmtime(), *localtime();
                   1528: 
                   1529: extern time_t time();
                   1530: 
                   1531: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1532: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
1.349     brouard  1533: time_t   rlast_btime; /* raw time */
1.157     brouard  1534: struct tm tm;
                   1535: 
1.126     brouard  1536: char strcurr[80], strfor[80];
                   1537: 
                   1538: char *endptr;
                   1539: long lval;
                   1540: double dval;
                   1541: 
1.362     brouard  1542: /* This for praxis gegen */
                   1543:   /* int prin=1; */
                   1544:   double h0=0.25;
                   1545:   double macheps;
                   1546:   double ffmin;
                   1547: 
1.126     brouard  1548: #define NR_END 1
                   1549: #define FREE_ARG char*
                   1550: #define FTOL 1.0e-10
                   1551: 
                   1552: #define NRANSI 
1.240     brouard  1553: #define ITMAX 200
                   1554: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1555: 
                   1556: #define TOL 2.0e-4 
                   1557: 
                   1558: #define CGOLD 0.3819660 
                   1559: #define ZEPS 1.0e-10 
                   1560: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1561: 
                   1562: #define GOLD 1.618034 
                   1563: #define GLIMIT 100.0 
                   1564: #define TINY 1.0e-20 
                   1565: 
                   1566: static double maxarg1,maxarg2;
                   1567: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1568: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1569:   
                   1570: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1571: #define rint(a) floor(a+0.5)
1.166     brouard  1572: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1573: #define mytinydouble 1.0e-16
1.166     brouard  1574: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1575: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1576: /* static double dsqrarg; */
                   1577: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1578: static double sqrarg;
                   1579: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1580: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1581: int agegomp= AGEGOMP;
                   1582: 
                   1583: int imx; 
                   1584: int stepm=1;
                   1585: /* Stepm, step in month: minimum step interpolation*/
                   1586: 
                   1587: int estepm;
                   1588: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1589: 
                   1590: int m,nb;
                   1591: long *num;
1.197     brouard  1592: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1593: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1594:                   covariate for which somebody answered excluding 
                   1595:                   undefined. Usually 2: 0 and 1. */
                   1596: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1597:                             covariate for which somebody answered including 
                   1598:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1599: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1600: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1601: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1602: 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  1603: double *ageexmed,*agecens;
                   1604: double dateintmean=0;
1.296     brouard  1605:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1606:   double anprojf, mprojf, jprojf;
1.126     brouard  1607: 
1.296     brouard  1608:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1609:   double anbackf, mbackf, jbackf;
                   1610:   double jintmean,mintmean,aintmean;  
1.126     brouard  1611: double *weight;
                   1612: int **s; /* Status */
1.141     brouard  1613: double *agedc;
1.145     brouard  1614: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1615:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1616:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1617: double **coqvar; /* Fixed quantitative covariate nqv */
1.341     brouard  1618: double ***cotvar; /* Time varying covariate start at ncovcol + nqv + (1 to ntv) */
1.225     brouard  1619: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1620: double  idx; 
                   1621: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1622: /* Some documentation */
                   1623:       /*   Design original data
                   1624:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1625:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1626:        *                                                             ntv=3     nqtv=1
1.330     brouard  1627:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1628:        * For time varying covariate, quanti or dummies
                   1629:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
1.341     brouard  1630:        *       cotvar[wav][ncovcol+nqv+ iv(1 to nqtv)][i]= [(1 to nqtv)][i]=(V12) quanti
1.319     brouard  1631:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1632:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1633:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1634:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1635:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1636:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1637:        */
                   1638: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1639: /* 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
                   1640:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1641:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1642: */
1.349     brouard  1643: /*           V5+V4+ V3+V4*V3 +V5*age+V2 +V1*V2+V1*age+V1+V4*V3*age */
                   1644: /*    kmodel  1  2   3    4     5     6    7     8     9    10 */
                   1645: /*Typevar[k]=  0  0   0   2     1    0    2     1     0    3 *//*0 for simple covariate (dummy, quantitative,*/
                   1646:                                                                /* fixed or varying), 1 for age product, 2 for*/
                   1647:                                                                /* product without age, 3 for age and double product   */
                   1648: /*Dummy[k]=    1  0   0   1     3    1    1     2     0     3  *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1649:                                                                 /*(single or product without age), 2 dummy*/
                   1650:                                                                /* with age product, 3 quant with age product*/
                   1651: /*Tvar[k]=     5  4   3   6     5    2    7     1     1     6 */
                   1652: /*    nsd         1   2                               3 */ /* Counting single dummies covar fixed or tv */
                   1653: /*TnsdVar[Tvar]   1   2                               3 */ 
                   1654: /*Tvaraff[nsd]    4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1655: /*TvarsD[nsd]     4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1656: /*TvarsDind[nsd]  2   3                               9 */ /* position K of single dummy cova */
                   1657: /*    nsq      1                     2                  */ /* Counting single quantit tv */
                   1658: /* TvarsQ[k]   5                     2                  */ /* Number of single quantitative cova */
                   1659: /* TvarsQind   1                     6                  */ /* position K of single quantitative cova */
                   1660: /* Tprod[i]=k             1               2             */ /* Position in model of the ith prod without age */
                   1661: /* cptcovage                    1               2         3 */ /* Counting cov*age in the model equation */
                   1662: /* Tage[cptcovage]=k            5               8         10 */ /* Position in the model of ith cov*age */
1.350     brouard  1663: /* 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"*/
                   1664: /*  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  1665: /*  p Tvard[2][1]@21 = {7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0 <repeats 11 times>} */
1.350     brouard  1666: /* 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}*/
                   1667: /* 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  1668: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2               */ /* Position in model of the ith prod without age */
1.330     brouard  1669: /* 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  1670: /* 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  1671: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1672: /* Type                    */
                   1673: /* V         1  2  3  4  5 */
                   1674: /*           F  F  V  V  V */
                   1675: /*           D  Q  D  D  Q */
                   1676: /*                         */
                   1677: int *TvarsD;
1.330     brouard  1678: int *TnsdVar;
1.234     brouard  1679: int *TvarsDind;
                   1680: int *TvarsQ;
                   1681: int *TvarsQind;
                   1682: 
1.318     brouard  1683: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1684: int nresult=0;
1.258     brouard  1685: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1686: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1687: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1688: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1689: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1690: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1691: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1692: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1693: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1694: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1695: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1696: 
                   1697: /* 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
                   1698:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1699:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1700: */
1.234     brouard  1701: /* 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  1702: 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 */
                   1703: 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 */
                   1704: 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 */
                   1705: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1706: 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 */
                   1707: 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  1708: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1709: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1710: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1711: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1712: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1713: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1714: 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 */
                   1715: 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  1716: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1717: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
1.349     brouard  1718: int *TvarVVA; /* We count ncovvt time varying covariates (single or products with age) and put their name into TvarVVA */
                   1719: int *TvarVVAind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1720: int *TvarAVVA; /* We count ALL ncovta time varying covariates (single or products with age) and put their name into TvarVVA */
                   1721: int *TvarAVVAind; /* We count ALL ncovta time varying covariates (single or products without age) and put their name into TvarVV */
1.339     brouard  1722:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  1723:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age */
                   1724:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   1725:       /* TvarVV={3,1,3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */        
                   1726:       /* 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  1727: int *Tvarsel; /**< Selected covariates for output */
                   1728: double *Tvalsel; /**< Selected modality value of covariate for output */
1.349     brouard  1729: 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  1730: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1731: 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  1732: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1733: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1734: int *Tage;
1.227     brouard  1735: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1736: 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  1737: 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*/ 
                   1738: 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  1739: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1740: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1741: int **Tvard;
1.330     brouard  1742: int **Tvardk;
1.227     brouard  1743: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1744: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1745: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1746:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1747:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1748: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1749: double *lsurv, *lpop, *tpop;
                   1750: 
1.231     brouard  1751: #define FD 1; /* Fixed dummy covariate */
                   1752: #define FQ 2; /* Fixed quantitative covariate */
                   1753: #define FP 3; /* Fixed product covariate */
                   1754: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1755: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1756: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1757: #define VD 10; /* Varying dummy covariate */
                   1758: #define VQ 11; /* Varying quantitative covariate */
                   1759: #define VP 12; /* Varying product covariate */
                   1760: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1761: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1762: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1763: #define APFD 16; /* Age product * fixed dummy covariate */
                   1764: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1765: #define APVD 18; /* Age product * varying dummy covariate */
                   1766: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1767: 
                   1768: #define FTYPE 1; /* Fixed covariate */
                   1769: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1770: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1771: 
                   1772: struct kmodel{
                   1773:        int maintype; /* main type */
                   1774:        int subtype; /* subtype */
                   1775: };
                   1776: struct kmodel modell[NCOVMAX];
                   1777: 
1.143     brouard  1778: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1779: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1780: 
                   1781: /**************** split *************************/
                   1782: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1783: {
                   1784:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1785:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1786:   */ 
                   1787:   char *ss;                            /* pointer */
1.186     brouard  1788:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1789: 
                   1790:   l1 = strlen(path );                  /* length of path */
                   1791:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1792:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1793:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1794:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1795:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1796:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1797:     /* get current working directory */
                   1798:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1799: #ifdef WIN32
                   1800:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1801: #else
                   1802:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1803: #endif
1.126     brouard  1804:       return( GLOCK_ERROR_GETCWD );
                   1805:     }
                   1806:     /* got dirc from getcwd*/
                   1807:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1808:   } else {                             /* strip directory from path */
1.126     brouard  1809:     ss++;                              /* after this, the filename */
                   1810:     l2 = strlen( ss );                 /* length of filename */
                   1811:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1812:     strcpy( name, ss );                /* save file name */
                   1813:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1814:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1815:     printf(" DIRC2 = %s \n",dirc);
                   1816:   }
                   1817:   /* We add a separator at the end of dirc if not exists */
                   1818:   l1 = strlen( dirc );                 /* length of directory */
                   1819:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1820:     dirc[l1] =  DIRSEPARATOR;
                   1821:     dirc[l1+1] = 0; 
                   1822:     printf(" DIRC3 = %s \n",dirc);
                   1823:   }
                   1824:   ss = strrchr( name, '.' );           /* find last / */
                   1825:   if (ss >0){
                   1826:     ss++;
                   1827:     strcpy(ext,ss);                    /* save extension */
                   1828:     l1= strlen( name);
                   1829:     l2= strlen(ss)+1;
                   1830:     strncpy( finame, name, l1-l2);
                   1831:     finame[l1-l2]= 0;
                   1832:   }
                   1833: 
                   1834:   return( 0 );                         /* we're done */
                   1835: }
                   1836: 
                   1837: 
                   1838: /******************************************/
                   1839: 
                   1840: void replace_back_to_slash(char *s, char*t)
                   1841: {
                   1842:   int i;
                   1843:   int lg=0;
                   1844:   i=0;
                   1845:   lg=strlen(t);
                   1846:   for(i=0; i<= lg; i++) {
                   1847:     (s[i] = t[i]);
                   1848:     if (t[i]== '\\') s[i]='/';
                   1849:   }
                   1850: }
                   1851: 
1.132     brouard  1852: char *trimbb(char *out, char *in)
1.137     brouard  1853: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1854:   char *s;
                   1855:   s=out;
                   1856:   while (*in != '\0'){
1.137     brouard  1857:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1858:       in++;
                   1859:     }
                   1860:     *out++ = *in++;
                   1861:   }
                   1862:   *out='\0';
                   1863:   return s;
                   1864: }
                   1865: 
1.351     brouard  1866: char *trimbtab(char *out, char *in)
                   1867: { /* Trim  blanks or tabs in line but keeps first blanks if line starts with blanks */
                   1868:   char *s;
                   1869:   s=out;
                   1870:   while (*in != '\0'){
                   1871:     while( (*in == ' ' || *in == '\t')){ /* && *(in+1) != '\0'){*/
                   1872:       in++;
                   1873:     }
                   1874:     *out++ = *in++;
                   1875:   }
                   1876:   *out='\0';
                   1877:   return s;
                   1878: }
                   1879: 
1.187     brouard  1880: /* char *substrchaine(char *out, char *in, char *chain) */
                   1881: /* { */
                   1882: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1883: /*   char *s, *t; */
                   1884: /*   t=in;s=out; */
                   1885: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1886: /*     *out++ = *in++; */
                   1887: /*   } */
                   1888: 
                   1889: /*   /\* *in matches *chain *\/ */
                   1890: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1891: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1892: /*   } */
                   1893: /*   in--; chain--; */
                   1894: /*   while ( (*in != '\0')){ */
                   1895: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1896: /*     *out++ = *in++; */
                   1897: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1898: /*   } */
                   1899: /*   *out='\0'; */
                   1900: /*   out=s; */
                   1901: /*   return out; */
                   1902: /* } */
                   1903: char *substrchaine(char *out, char *in, char *chain)
                   1904: {
                   1905:   /* Substract chain 'chain' from 'in', return and output 'out' */
1.349     brouard  1906:   /* in="V1+V1*age+age*age+V2", chain="+age*age" out="V1+V1*age+V2" */
1.187     brouard  1907: 
                   1908:   char *strloc;
                   1909: 
1.349     brouard  1910:   strcpy (out, in);                   /* out="V1+V1*age+age*age+V2" */
                   1911:   strloc = strstr(out, chain); /* strloc points to out at "+age*age+V2"  */
                   1912:   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  1913:   if(strloc != NULL){ 
1.349     brouard  1914:     /* will affect out */ /* strloc+strlen(chain)=|+V2 = "V1+V1*age+age*age|+V2" */ /* Will also work in Unicodek */
                   1915:     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)*/
                   1916:     /* equivalent to strcpy (strloc, strloc +strlen(chain)) if no overlap; Copies from "+V2" to V1+V1*age+ */
1.187     brouard  1917:   }
1.349     brouard  1918:   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  1919:   return out;
                   1920: }
                   1921: 
                   1922: 
1.145     brouard  1923: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1924: {
1.187     brouard  1925:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.349     brouard  1926:      and alocc starts after first occurence of char 'occ' : ex cutl(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1927:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1928:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1929:   */
1.160     brouard  1930:   char *s, *t;
1.145     brouard  1931:   t=in;s=in;
                   1932:   while ((*in != occ) && (*in != '\0')){
                   1933:     *alocc++ = *in++;
                   1934:   }
                   1935:   if( *in == occ){
                   1936:     *(alocc)='\0';
                   1937:     s=++in;
                   1938:   }
                   1939:  
                   1940:   if (s == t) {/* occ not found */
                   1941:     *(alocc-(in-s))='\0';
                   1942:     in=s;
                   1943:   }
                   1944:   while ( *in != '\0'){
                   1945:     *blocc++ = *in++;
                   1946:   }
                   1947: 
                   1948:   *blocc='\0';
                   1949:   return t;
                   1950: }
1.137     brouard  1951: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1952: {
1.187     brouard  1953:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1954:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1955:      gives blocc="abcdef2ghi" and alocc="j".
                   1956:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1957:   */
                   1958:   char *s, *t;
                   1959:   t=in;s=in;
                   1960:   while (*in != '\0'){
                   1961:     while( *in == occ){
                   1962:       *blocc++ = *in++;
                   1963:       s=in;
                   1964:     }
                   1965:     *blocc++ = *in++;
                   1966:   }
                   1967:   if (s == t) /* occ not found */
                   1968:     *(blocc-(in-s))='\0';
                   1969:   else
                   1970:     *(blocc-(in-s)-1)='\0';
                   1971:   in=s;
                   1972:   while ( *in != '\0'){
                   1973:     *alocc++ = *in++;
                   1974:   }
                   1975: 
                   1976:   *alocc='\0';
                   1977:   return s;
                   1978: }
                   1979: 
1.126     brouard  1980: int nbocc(char *s, char occ)
                   1981: {
                   1982:   int i,j=0;
                   1983:   int lg=20;
                   1984:   i=0;
                   1985:   lg=strlen(s);
                   1986:   for(i=0; i<= lg; i++) {
1.234     brouard  1987:     if  (s[i] == occ ) j++;
1.126     brouard  1988:   }
                   1989:   return j;
                   1990: }
                   1991: 
1.349     brouard  1992: int nboccstr(char *textin, char *chain)
                   1993: {
                   1994:   /* Counts the number of occurence of "chain"  in string textin */
                   1995:   /*  in="+V7*V4+age*V2+age*V3+age*V4"  chain="age" */
                   1996:   char *strloc;
                   1997:   
                   1998:   int i,j=0;
                   1999: 
                   2000:   i=0;
                   2001: 
                   2002:   strloc=textin; /* strloc points to "^+V7*V4+age+..." in textin */
                   2003:   for(;;) {
                   2004:     strloc= strstr(strloc,chain); /* strloc points to first character of chain in textin if found. Example strloc points^ to "+V7*V4+^age" in textin  */
                   2005:     if(strloc != NULL){
                   2006:       strloc = strloc+strlen(chain); /* strloc points to "+V7*V4+age^" in textin */
                   2007:       j++;
                   2008:     }else
                   2009:       break;
                   2010:   }
                   2011:   return j;
                   2012:   
                   2013: }
1.137     brouard  2014: /* void cutv(char *u,char *v, char*t, char occ) */
                   2015: /* { */
                   2016: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   2017: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   2018: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   2019: /*   int i,lg,j,p=0; */
                   2020: /*   i=0; */
                   2021: /*   lg=strlen(t); */
                   2022: /*   for(j=0; j<=lg-1; j++) { */
                   2023: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   2024: /*   } */
1.126     brouard  2025: 
1.137     brouard  2026: /*   for(j=0; j<p; j++) { */
                   2027: /*     (u[j] = t[j]); */
                   2028: /*   } */
                   2029: /*      u[p]='\0'; */
1.126     brouard  2030: 
1.137     brouard  2031: /*    for(j=0; j<= lg; j++) { */
                   2032: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   2033: /*   } */
                   2034: /* } */
1.126     brouard  2035: 
1.160     brouard  2036: #ifdef _WIN32
                   2037: char * strsep(char **pp, const char *delim)
                   2038: {
                   2039:   char *p, *q;
                   2040:          
                   2041:   if ((p = *pp) == NULL)
                   2042:     return 0;
                   2043:   if ((q = strpbrk (p, delim)) != NULL)
                   2044:   {
                   2045:     *pp = q + 1;
                   2046:     *q = '\0';
                   2047:   }
                   2048:   else
                   2049:     *pp = 0;
                   2050:   return p;
                   2051: }
                   2052: #endif
                   2053: 
1.126     brouard  2054: /********************** nrerror ********************/
                   2055: 
                   2056: void nrerror(char error_text[])
                   2057: {
                   2058:   fprintf(stderr,"ERREUR ...\n");
                   2059:   fprintf(stderr,"%s\n",error_text);
                   2060:   exit(EXIT_FAILURE);
                   2061: }
                   2062: /*********************** vector *******************/
                   2063: double *vector(int nl, int nh)
                   2064: {
                   2065:   double *v;
                   2066:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   2067:   if (!v) nrerror("allocation failure in vector");
                   2068:   return v-nl+NR_END;
                   2069: }
                   2070: 
                   2071: /************************ free vector ******************/
                   2072: void free_vector(double*v, int nl, int nh)
                   2073: {
                   2074:   free((FREE_ARG)(v+nl-NR_END));
                   2075: }
                   2076: 
                   2077: /************************ivector *******************************/
                   2078: int *ivector(long nl,long nh)
                   2079: {
                   2080:   int *v;
                   2081:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   2082:   if (!v) nrerror("allocation failure in ivector");
                   2083:   return v-nl+NR_END;
                   2084: }
                   2085: 
                   2086: /******************free ivector **************************/
                   2087: void free_ivector(int *v, long nl, long nh)
                   2088: {
                   2089:   free((FREE_ARG)(v+nl-NR_END));
                   2090: }
                   2091: 
                   2092: /************************lvector *******************************/
                   2093: long *lvector(long nl,long nh)
                   2094: {
                   2095:   long *v;
                   2096:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   2097:   if (!v) nrerror("allocation failure in ivector");
                   2098:   return v-nl+NR_END;
                   2099: }
                   2100: 
                   2101: /******************free lvector **************************/
                   2102: void free_lvector(long *v, long nl, long nh)
                   2103: {
                   2104:   free((FREE_ARG)(v+nl-NR_END));
                   2105: }
                   2106: 
                   2107: /******************* imatrix *******************************/
                   2108: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   2109:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   2110: { 
                   2111:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   2112:   int **m; 
                   2113:   
                   2114:   /* allocate pointers to rows */ 
                   2115:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   2116:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   2117:   m += NR_END; 
                   2118:   m -= nrl; 
                   2119:   
                   2120:   
                   2121:   /* allocate rows and set pointers to them */ 
                   2122:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   2123:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   2124:   m[nrl] += NR_END; 
                   2125:   m[nrl] -= ncl; 
                   2126:   
                   2127:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   2128:   
                   2129:   /* return pointer to array of pointers to rows */ 
                   2130:   return m; 
                   2131: } 
                   2132: 
                   2133: /****************** free_imatrix *************************/
                   2134: void free_imatrix(m,nrl,nrh,ncl,nch)
                   2135:       int **m;
                   2136:       long nch,ncl,nrh,nrl; 
                   2137:      /* free an int matrix allocated by imatrix() */ 
                   2138: { 
                   2139:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   2140:   free((FREE_ARG) (m+nrl-NR_END)); 
                   2141: } 
                   2142: 
                   2143: /******************* matrix *******************************/
                   2144: double **matrix(long nrl, long nrh, long ncl, long nch)
                   2145: {
                   2146:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   2147:   double **m;
                   2148: 
                   2149:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2150:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2151:   m += NR_END;
                   2152:   m -= nrl;
                   2153: 
                   2154:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2155:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2156:   m[nrl] += NR_END;
                   2157:   m[nrl] -= ncl;
                   2158: 
                   2159:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2160:   return m;
1.145     brouard  2161:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   2162: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   2163: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  2164:    */
                   2165: }
                   2166: 
                   2167: /*************************free matrix ************************/
                   2168: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   2169: {
                   2170:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2171:   free((FREE_ARG)(m+nrl-NR_END));
                   2172: }
                   2173: 
                   2174: /******************* ma3x *******************************/
                   2175: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   2176: {
                   2177:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   2178:   double ***m;
                   2179: 
                   2180:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2181:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2182:   m += NR_END;
                   2183:   m -= nrl;
                   2184: 
                   2185:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2186:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2187:   m[nrl] += NR_END;
                   2188:   m[nrl] -= ncl;
                   2189: 
                   2190:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2191: 
                   2192:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   2193:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2194:   m[nrl][ncl] += NR_END;
                   2195:   m[nrl][ncl] -= nll;
                   2196:   for (j=ncl+1; j<=nch; j++) 
                   2197:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2198:   
                   2199:   for (i=nrl+1; i<=nrh; i++) {
                   2200:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2201:     for (j=ncl+1; j<=nch; j++) 
                   2202:       m[i][j]=m[i][j-1]+nlay;
                   2203:   }
                   2204:   return m; 
                   2205:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2206:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2207:   */
                   2208: }
                   2209: 
                   2210: /*************************free ma3x ************************/
                   2211: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2212: {
                   2213:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2214:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2215:   free((FREE_ARG)(m+nrl-NR_END));
                   2216: }
                   2217: 
                   2218: /*************** function subdirf ***********/
                   2219: char *subdirf(char fileres[])
                   2220: {
                   2221:   /* Caution optionfilefiname is hidden */
                   2222:   strcpy(tmpout,optionfilefiname);
                   2223:   strcat(tmpout,"/"); /* Add to the right */
                   2224:   strcat(tmpout,fileres);
                   2225:   return tmpout;
                   2226: }
                   2227: 
                   2228: /*************** function subdirf2 ***********/
                   2229: char *subdirf2(char fileres[], char *preop)
                   2230: {
1.314     brouard  2231:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2232:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2233:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2234:   /* Caution optionfilefiname is hidden */
                   2235:   strcpy(tmpout,optionfilefiname);
                   2236:   strcat(tmpout,"/");
                   2237:   strcat(tmpout,preop);
                   2238:   strcat(tmpout,fileres);
                   2239:   return tmpout;
                   2240: }
                   2241: 
                   2242: /*************** function subdirf3 ***********/
                   2243: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2244: {
                   2245:   
                   2246:   /* Caution optionfilefiname is hidden */
                   2247:   strcpy(tmpout,optionfilefiname);
                   2248:   strcat(tmpout,"/");
                   2249:   strcat(tmpout,preop);
                   2250:   strcat(tmpout,preop2);
                   2251:   strcat(tmpout,fileres);
                   2252:   return tmpout;
                   2253: }
1.213     brouard  2254:  
                   2255: /*************** function subdirfext ***********/
                   2256: char *subdirfext(char fileres[], char *preop, char *postop)
                   2257: {
                   2258:   
                   2259:   strcpy(tmpout,preop);
                   2260:   strcat(tmpout,fileres);
                   2261:   strcat(tmpout,postop);
                   2262:   return tmpout;
                   2263: }
1.126     brouard  2264: 
1.213     brouard  2265: /*************** function subdirfext3 ***********/
                   2266: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2267: {
                   2268:   
                   2269:   /* Caution optionfilefiname is hidden */
                   2270:   strcpy(tmpout,optionfilefiname);
                   2271:   strcat(tmpout,"/");
                   2272:   strcat(tmpout,preop);
                   2273:   strcat(tmpout,fileres);
                   2274:   strcat(tmpout,postop);
                   2275:   return tmpout;
                   2276: }
                   2277:  
1.162     brouard  2278: char *asc_diff_time(long time_sec, char ascdiff[])
                   2279: {
                   2280:   long sec_left, days, hours, minutes;
                   2281:   days = (time_sec) / (60*60*24);
                   2282:   sec_left = (time_sec) % (60*60*24);
                   2283:   hours = (sec_left) / (60*60) ;
                   2284:   sec_left = (sec_left) %(60*60);
                   2285:   minutes = (sec_left) /60;
                   2286:   sec_left = (sec_left) % (60);
                   2287:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2288:   return ascdiff;
                   2289: }
                   2290: 
1.126     brouard  2291: /***************** f1dim *************************/
                   2292: extern int ncom; 
                   2293: extern double *pcom,*xicom;
                   2294: extern double (*nrfunc)(double []); 
                   2295:  
                   2296: double f1dim(double x) 
                   2297: { 
                   2298:   int j; 
                   2299:   double f;
                   2300:   double *xt; 
                   2301:  
                   2302:   xt=vector(1,ncom); 
                   2303:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2304:   f=(*nrfunc)(xt); 
                   2305:   free_vector(xt,1,ncom); 
                   2306:   return f; 
                   2307: } 
                   2308: 
                   2309: /*****************brent *************************/
                   2310: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2311: {
                   2312:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2313:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2314:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2315:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2316:    * returned function value. 
                   2317:   */
1.126     brouard  2318:   int iter; 
                   2319:   double a,b,d,etemp;
1.159     brouard  2320:   double fu=0,fv,fw,fx;
1.164     brouard  2321:   double ftemp=0.;
1.126     brouard  2322:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2323:   double e=0.0; 
                   2324:  
                   2325:   a=(ax < cx ? ax : cx); 
                   2326:   b=(ax > cx ? ax : cx); 
                   2327:   x=w=v=bx; 
                   2328:   fw=fv=fx=(*f)(x); 
                   2329:   for (iter=1;iter<=ITMAX;iter++) { 
                   2330:     xm=0.5*(a+b); 
                   2331:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2332:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2333:     printf(".");fflush(stdout);
                   2334:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2335: #ifdef DEBUGBRENT
1.126     brouard  2336:     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);
                   2337:     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);
                   2338:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2339: #endif
                   2340:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2341:       *xmin=x; 
                   2342:       return fx; 
                   2343:     } 
                   2344:     ftemp=fu;
                   2345:     if (fabs(e) > tol1) { 
                   2346:       r=(x-w)*(fx-fv); 
                   2347:       q=(x-v)*(fx-fw); 
                   2348:       p=(x-v)*q-(x-w)*r; 
                   2349:       q=2.0*(q-r); 
                   2350:       if (q > 0.0) p = -p; 
                   2351:       q=fabs(q); 
                   2352:       etemp=e; 
                   2353:       e=d; 
                   2354:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2355:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2356:       else { 
1.224     brouard  2357:                                d=p/q; 
                   2358:                                u=x+d; 
                   2359:                                if (u-a < tol2 || b-u < tol2) 
                   2360:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2361:       } 
                   2362:     } else { 
                   2363:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2364:     } 
                   2365:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2366:     fu=(*f)(u); 
                   2367:     if (fu <= fx) { 
                   2368:       if (u >= x) a=x; else b=x; 
                   2369:       SHFT(v,w,x,u) 
1.183     brouard  2370:       SHFT(fv,fw,fx,fu) 
                   2371:     } else { 
                   2372:       if (u < x) a=u; else b=u; 
                   2373:       if (fu <= fw || w == x) { 
1.224     brouard  2374:                                v=w; 
                   2375:                                w=u; 
                   2376:                                fv=fw; 
                   2377:                                fw=fu; 
1.183     brouard  2378:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2379:                                v=u; 
                   2380:                                fv=fu; 
1.183     brouard  2381:       } 
                   2382:     } 
1.126     brouard  2383:   } 
                   2384:   nrerror("Too many iterations in brent"); 
                   2385:   *xmin=x; 
                   2386:   return fx; 
                   2387: } 
                   2388: 
                   2389: /****************** mnbrak ***********************/
                   2390: 
                   2391: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2392:            double (*func)(double)) 
1.183     brouard  2393: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2394: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2395: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2396: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2397:    */
1.126     brouard  2398:   double ulim,u,r,q, dum;
                   2399:   double fu; 
1.187     brouard  2400: 
                   2401:   double scale=10.;
                   2402:   int iterscale=0;
                   2403: 
                   2404:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2405:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2406: 
                   2407: 
                   2408:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2409:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2410:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2411:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2412:   /* } */
                   2413: 
1.126     brouard  2414:   if (*fb > *fa) { 
                   2415:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2416:     SHFT(dum,*fb,*fa,dum) 
                   2417:   } 
1.126     brouard  2418:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2419:   *fc=(*func)(*cx); 
1.183     brouard  2420: #ifdef DEBUG
1.224     brouard  2421:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2422:   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  2423: #endif
1.224     brouard  2424:   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  2425:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2426:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2427:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2428:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2429:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2430:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2431:       fu=(*func)(u); 
1.163     brouard  2432: #ifdef DEBUG
                   2433:       /* f(x)=A(x-u)**2+f(u) */
                   2434:       double A, fparabu; 
                   2435:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2436:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2437:       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);
                   2438:       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  2439:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2440:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2441:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2442:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2443: #endif 
1.184     brouard  2444: #ifdef MNBRAKORIGINAL
1.183     brouard  2445: #else
1.191     brouard  2446: /*       if (fu > *fc) { */
                   2447: /* #ifdef DEBUG */
                   2448: /*       printf("mnbrak4  fu > fc \n"); */
                   2449: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2450: /* #endif */
                   2451: /*     /\* 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 *\\/  *\/ */
                   2452: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2453: /*     dum=u; /\* Shifting c and u *\/ */
                   2454: /*     u = *cx; */
                   2455: /*     *cx = dum; */
                   2456: /*     dum = fu; */
                   2457: /*     fu = *fc; */
                   2458: /*     *fc =dum; */
                   2459: /*       } else { /\* end *\/ */
                   2460: /* #ifdef DEBUG */
                   2461: /*       printf("mnbrak3  fu < fc \n"); */
                   2462: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2463: /* #endif */
                   2464: /*     dum=u; /\* Shifting c and u *\/ */
                   2465: /*     u = *cx; */
                   2466: /*     *cx = dum; */
                   2467: /*     dum = fu; */
                   2468: /*     fu = *fc; */
                   2469: /*     *fc =dum; */
                   2470: /*       } */
1.224     brouard  2471: #ifdef DEBUGMNBRAK
                   2472:                 double A, fparabu; 
                   2473:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2474:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2475:      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);
                   2476:      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  2477: #endif
1.191     brouard  2478:       dum=u; /* Shifting c and u */
                   2479:       u = *cx;
                   2480:       *cx = dum;
                   2481:       dum = fu;
                   2482:       fu = *fc;
                   2483:       *fc =dum;
1.183     brouard  2484: #endif
1.162     brouard  2485:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2486: #ifdef DEBUG
1.224     brouard  2487:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2488:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2489: #endif
1.126     brouard  2490:       fu=(*func)(u); 
                   2491:       if (fu < *fc) { 
1.183     brouard  2492: #ifdef DEBUG
1.224     brouard  2493:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2494:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2495: #endif
                   2496:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2497:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2498: #ifdef DEBUG
                   2499:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2500: #endif
                   2501:       } 
1.162     brouard  2502:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2503: #ifdef DEBUG
1.224     brouard  2504:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2505:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2506: #endif
1.126     brouard  2507:       u=ulim; 
                   2508:       fu=(*func)(u); 
1.183     brouard  2509:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2510: #ifdef DEBUG
1.224     brouard  2511:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2512:       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  2513: #endif
1.126     brouard  2514:       u=(*cx)+GOLD*(*cx-*bx); 
                   2515:       fu=(*func)(u); 
1.224     brouard  2516: #ifdef DEBUG
                   2517:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2518:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2519: #endif
1.183     brouard  2520:     } /* end tests */
1.126     brouard  2521:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2522:     SHFT(*fa,*fb,*fc,fu) 
                   2523: #ifdef DEBUG
1.224     brouard  2524:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2525:       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  2526: #endif
                   2527:   } /* 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  2528: } 
                   2529: 
                   2530: /*************** linmin ************************/
1.162     brouard  2531: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2532: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2533: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2534: the value of func at the returned location p . This is actually all accomplished by calling the
                   2535: routines mnbrak and brent .*/
1.126     brouard  2536: int ncom; 
                   2537: double *pcom,*xicom;
                   2538: double (*nrfunc)(double []); 
                   2539:  
1.224     brouard  2540: #ifdef LINMINORIGINAL
1.126     brouard  2541: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2542: #else
                   2543: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2544: #endif
1.126     brouard  2545: { 
                   2546:   double brent(double ax, double bx, double cx, 
                   2547:               double (*f)(double), double tol, double *xmin); 
                   2548:   double f1dim(double x); 
                   2549:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2550:              double *fc, double (*func)(double)); 
                   2551:   int j; 
                   2552:   double xx,xmin,bx,ax; 
                   2553:   double fx,fb,fa;
1.187     brouard  2554: 
1.203     brouard  2555: #ifdef LINMINORIGINAL
                   2556: #else
                   2557:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2558: #endif
                   2559:   
1.126     brouard  2560:   ncom=n; 
                   2561:   pcom=vector(1,n); 
                   2562:   xicom=vector(1,n); 
                   2563:   nrfunc=func; 
                   2564:   for (j=1;j<=n;j++) { 
                   2565:     pcom[j]=p[j]; 
1.202     brouard  2566:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2567:   } 
1.187     brouard  2568: 
1.203     brouard  2569: #ifdef LINMINORIGINAL
                   2570:   xx=1.;
                   2571: #else
                   2572:   axs=0.0;
                   2573:   xxs=1.;
                   2574:   do{
                   2575:     xx= xxs;
                   2576: #endif
1.187     brouard  2577:     ax=0.;
                   2578:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2579:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2580:     /* 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))   */
                   2581:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2582:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2583:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2584:     /* 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  2585: #ifdef LINMINORIGINAL
                   2586: #else
                   2587:     if (fx != fx){
1.224     brouard  2588:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2589:                        printf("|");
                   2590:                        fprintf(ficlog,"|");
1.203     brouard  2591: #ifdef DEBUGLINMIN
1.224     brouard  2592:                        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  2593: #endif
                   2594:     }
1.224     brouard  2595:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2596: #endif
                   2597:   
1.191     brouard  2598: #ifdef DEBUGLINMIN
                   2599:   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  2600:   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  2601: #endif
1.224     brouard  2602: #ifdef LINMINORIGINAL
                   2603: #else
1.317     brouard  2604:   if(fb == fx){ /* Flat function in the direction */
                   2605:     xmin=xx;
1.224     brouard  2606:     *flat=1;
1.317     brouard  2607:   }else{
1.224     brouard  2608:     *flat=0;
                   2609: #endif
                   2610:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2611:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2612:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2613:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2614:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2615:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2616: #ifdef DEBUG
1.224     brouard  2617:   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);
                   2618:   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);
                   2619: #endif
                   2620: #ifdef LINMINORIGINAL
                   2621: #else
                   2622:                        }
1.126     brouard  2623: #endif
1.191     brouard  2624: #ifdef DEBUGLINMIN
                   2625:   printf("linmin end ");
1.202     brouard  2626:   fprintf(ficlog,"linmin end ");
1.191     brouard  2627: #endif
1.126     brouard  2628:   for (j=1;j<=n;j++) { 
1.203     brouard  2629: #ifdef LINMINORIGINAL
                   2630:     xi[j] *= xmin; 
                   2631: #else
                   2632: #ifdef DEBUGLINMIN
                   2633:     if(xxs <1.0)
                   2634:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2635: #endif
                   2636:     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) */
                   2637: #ifdef DEBUGLINMIN
                   2638:     if(xxs <1.0)
                   2639:       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 );
                   2640: #endif
                   2641: #endif
1.187     brouard  2642:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2643:   } 
1.191     brouard  2644: #ifdef DEBUGLINMIN
1.203     brouard  2645:   printf("\n");
1.191     brouard  2646:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2647:   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  2648:   for (j=1;j<=n;j++) { 
1.202     brouard  2649:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2650:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2651:     if(j % ncovmodel == 0){
1.191     brouard  2652:       printf("\n");
1.202     brouard  2653:       fprintf(ficlog,"\n");
                   2654:     }
1.191     brouard  2655:   }
1.203     brouard  2656: #else
1.191     brouard  2657: #endif
1.126     brouard  2658:   free_vector(xicom,1,n); 
                   2659:   free_vector(pcom,1,n); 
                   2660: } 
                   2661: 
1.359     brouard  2662: /**** praxis gegen ****/
                   2663: 
                   2664: /* This has been tested by Visual C from Microsoft and works */
                   2665: /* meaning tha valgrind could be wrong */
                   2666: /*********************************************************************/
                   2667: /*     f u n c t i o n     p r a x i s                              */
                   2668: /*                                                                   */
                   2669: /* praxis is a general purpose routine for the minimization of a     */
                   2670: /* function in several variables. the algorithm used is a modifi-    */
                   2671: /* cation of conjugate gradient search method by powell. the changes */
                   2672: /* are due to r.p. brent, who gives an algol-w program, which served */
                   2673: /* as a basis for this function.                                     */
                   2674: /*                                                                   */
                   2675: /* references:                                                       */
                   2676: /*     - powell, m.j.d., 1964. an efficient method for finding       */
                   2677: /*       the minimum of a function in several variables without      */
                   2678: /*       calculating derivatives, computer journal, 7, 155-162       */
                   2679: /*     - brent, r.p., 1973. algorithms for minimization without      */
                   2680: /*       derivatives, prentice hall, englewood cliffs.               */
                   2681: /*                                                                   */
                   2682: /*     problems, suggestions or improvements are always wellcome     */
                   2683: /*                       karl gegenfurtner   07/08/87                */
                   2684: /*                                           c - version             */
                   2685: /*********************************************************************/
                   2686: /*                                                                   */
                   2687: /* usage: min = praxis(tol, macheps, h, n, prin, x, func)      */
                   2688: /* macheps has been suppressed because it is replaced by DBL_EPSILON */
                   2689: /* and if it was an argument of praxis (as it is in original brent)  */
                   2690: /* it should be declared external */
                   2691: /* usage: min = praxis(tol, h, n, prin, x, func)      */
                   2692: /* was    min = praxis(fun, x, n);                                   */
                   2693: /*                                                                   */
                   2694: /*  fun        the function to be minimized. fun is called from      */
                   2695: /*             praxis with x and n as arguments                      */
                   2696: /*  x          a double array containing the initial guesses for     */
                   2697: /*             the minimum, which will contain the solution on       */
                   2698: /*             return                                                */
                   2699: /*  n          an integer specifying the number of unknown           */
                   2700: /*             parameters                                            */
                   2701: /*  min        praxis returns the least calculated value of fun      */
                   2702: /*                                                                   */
                   2703: /* some additional global variables control some more aspects of     */
                   2704: /* the inner workings of praxis. setting them is optional, they      */
                   2705: /* are all set to some reasonable default values given below.        */
                   2706: /*                                                                   */
                   2707: /*   prin      controls the printed output from the routine.         */
                   2708: /*             0 -> no output                                        */
                   2709: /*             1 -> print only starting and final values             */
                   2710: /*             2 -> detailed map of the minimization process         */
                   2711: /*             3 -> print also eigenvalues and vectors of the        */
                   2712: /*                  search directions                                */
                   2713: /*             the default value is 1                                */
                   2714: /*  tol        is the tolerance allowed for the precision of the     */
                   2715: /*             solution. praxis returns if the criterion             */
                   2716: /*             2 * ||x[k]-x[k-1]|| <= sqrt(macheps) * ||x[k]|| + tol */
                   2717: /*             is fulfilled more than ktm times.                     */
                   2718: /*             the default value depends on the machine precision    */
                   2719: /*  ktm        see just above. default is 1, and a value of 4 leads  */
                   2720: /*             to a very(!) cautious stopping criterion.             */
                   2721: /*  h0 or step       is a steplength parameter and should be set equal     */
                   2722: /*             to the expected distance from the solution.           */
                   2723: /*             exceptionally small or large values of step lead to   */
                   2724: /*             slower convergence on the first few iterations        */
                   2725: /*             the default value for step is 1.0                     */
                   2726: /*  scbd       is a scaling parameter. 1.0 is the default and        */
                   2727: /*             indicates no scaling. if the scales for the different */
                   2728: /*             parameters are very different, scbd should be set to  */
                   2729: /*             a value of about 10.0.                                */
                   2730: /*  illc       should be set to true (1) if the problem is known to  */
                   2731: /*             be ill-conditioned. the default is false (0). this    */
                   2732: /*             variable is automatically set, when praxis finds      */
                   2733: /*             the problem to be ill-conditioned during iterations.  */
                   2734: /*  maxfun     is the maximum number of calls to fun allowed. praxis */
                   2735: /*             will return after maxfun calls to fun even when the   */
                   2736: /*             minimum is not yet found. the default value of 0      */
                   2737: /*             indicates no limit on the number of calls.            */
                   2738: /*             this return condition is only checked every n         */
                   2739: /*             iterations.                                           */
                   2740: /*                                                                   */
                   2741: /*********************************************************************/
                   2742: 
                   2743: #include <math.h>
                   2744: #include <stdio.h>
                   2745: #include <stdlib.h>
                   2746: #include <float.h> /* for DBL_EPSILON */
                   2747: /* #include "machine.h" */
                   2748: 
                   2749: 
                   2750: /* extern void minfit(int n, double eps, double tol, double **ab, double q[]); */
                   2751: /* extern void minfit(int n, double eps, double tol, double ab[N][N], double q[]); */
                   2752: /* control parameters */
                   2753: /* control parameters */
                   2754: #define SQREPSILON 1.0e-19
                   2755: /* #define EPSILON 1.0e-8 */ /* in main */
                   2756: 
                   2757: double tol = SQREPSILON,
                   2758:        scbd = 1.0,
                   2759:        step = 1.0;
                   2760: int    ktm = 1,
                   2761:        /* prin = 2, */
                   2762:        maxfun = 0,
                   2763:        illc = 0;
                   2764:        
                   2765: /* some global variables */
                   2766: static int i, j, k, k2, nl, nf, kl, kt;
                   2767: /* static double s; */
                   2768: double sl, dn, dmin,
                   2769:        fx, f1, lds, ldt, sf, df,
                   2770:        qf1, qd0, qd1, qa, qb, qc,
                   2771:        m2, m4, small_windows, vsmall, large, 
                   2772:        vlarge, ldfac, t2;
                   2773: /* static double d[N], y[N], z[N], */
                   2774: /*        q0[N], q1[N], v[N][N]; */
                   2775: 
                   2776: static double *d, *y, *z;
                   2777: static double  *q0, *q1, **v;
                   2778: double *tflin; /* used in flin: return (*fun)(tflin, n); */
                   2779: double *e; /* used in minfit, don't konw how to free memory and thus made global */
                   2780: /* static double s, sl, dn, dmin, */
                   2781: /*        fx, f1, lds, ldt, sf, df, */
                   2782: /*        qf1, qd0, qd1, qa, qb, qc, */
                   2783: /*        m2, m4, small, vsmall, large,  */
                   2784: /*        vlarge, ldfac, t2; */
                   2785: /* static double d[N], y[N], z[N], */
                   2786: /*        q0[N], q1[N], v[N][N]; */
                   2787: 
                   2788: /* these will be set by praxis to point to it's arguments */
                   2789: static int prin; /* added */
                   2790: static int n;
                   2791: static double *x;
                   2792: static double (*fun)();
                   2793: /* static double (*fun)(double *x, int n); */
                   2794: 
                   2795: /* these will be set by praxis to the global control parameters */
                   2796: /* static double h, macheps, t; */
                   2797: extern double macheps;
                   2798: static double h;
                   2799: static double t;
                   2800: 
                   2801: static double 
                   2802: drandom()      /* return random no between 0 and 1 */
                   2803: {
                   2804:    return (double)(rand()%(8192*2))/(double)(8192*2);
                   2805: }
                   2806: 
                   2807: static void sort()             /* d and v in descending order */
                   2808: {
                   2809:    int k, i, j;
                   2810:    double s;
                   2811: 
                   2812:    for (i=1; i<=n-1; i++) {
                   2813:        k = i; s = d[i];
                   2814:        for (j=i+1; j<=n; j++) {
                   2815:            if (d[j] > s) {
                   2816:              k = j;
                   2817:              s = d[j];
                   2818:           }
                   2819:        }
                   2820:        if (k > i) {
                   2821:          d[k] = d[i];
                   2822:          d[i] = s;
                   2823:          for (j=1; j<=n; j++) {
                   2824:              s = v[j][i];
                   2825:              v[j][i] = v[j][k];
                   2826:              v[j][k] = s;
                   2827:          }
                   2828:        }
                   2829:    }
                   2830: }
                   2831: 
                   2832: double randbrent ( int *naught )
                   2833: {
                   2834:   double ran1, ran3[127], half;
                   2835:   int ran2, q, r, i, j;
                   2836:   int init=0; /* false */
                   2837:   double rr;
                   2838:   /* REAL*8 RAN1,RAN3(127),HALF */
                   2839: 
                   2840:   /*     INTEGER RAN2,Q,R */
                   2841:   /*     LOGICAL INIT */
                   2842:   /*     DATA INIT/.FALSE./ */
                   2843:   /*     IF (INIT) GO TO 3 */
                   2844:   if(!init){ 
                   2845: /*       R = MOD(NAUGHT,8190) + 1 *//* 1804289383 rand () */
                   2846:     r = *naught % 8190 + 1;/* printf(" naught r %d %d",*naught,r); */
                   2847:     ran2=127;
                   2848:     for(i=ran2; i>0; i--){
                   2849: /*       RAN2 = 128 */
                   2850: /*       DO 2 I=1,127 */
                   2851:       ran2 = ran2-1;
                   2852: /*          RAN2 = RAN2 - 1 */
                   2853:       ran1 = -pow(2.0,55);
                   2854: /*          RAN1 = -2.D0**55 */
                   2855: /*          DO 1 J=1,7 */
                   2856:       for(j=1; j<=7;j++){
                   2857: /*             R = MOD(1756*R,8191) */
                   2858:        r = (1756*r) % 8191;/* printf(" i=%d (1756*r)%8191=%d",j,r); */
                   2859:        q=r/32;
                   2860: /*             Q = R/32 */
                   2861: /* 1           RAN1 = (RAN1 + Q)*(1.0D0/256) */
                   2862:        ran1 =(ran1+q)*(1.0/256);
                   2863:       }
                   2864: /* 2        RAN3(RAN2) = RAN1 */
                   2865:       ran3[ran2] = ran1; /* printf(" ran2=%d ran1=%.7g \n",ran2,ran1); */ 
                   2866:     }
                   2867: /*       INIT = .TRUE. */
                   2868:     init=1;
                   2869: /* 3     IF (RAN2.EQ.1) RAN2 = 128 */
                   2870:   }
                   2871:   if(ran2 == 0) ran2 = 126;
                   2872:   else ran2 = ran2 -1;
                   2873:   /* RAN2 = RAN2 - 1 */
                   2874:   /* RAN1 = RAN1 + RAN3(RAN2) */
                   2875:   ran1 = ran1 + ran3[ran2];/* printf("BIS ran2=%d ran1=%.7g \n",ran2,ran1);  */
                   2876:   half= 0.5;
                   2877:   /* HALF = .5D0 */
                   2878:   /* IF (RAN1.GE.0.D0) HALF = -HALF */
                   2879:   if(ran1 >= 0.) half =-half;
                   2880:   ran1 = ran1 +half;
                   2881:   ran3[ran2] = ran1;
                   2882:   rr= ran1+0.5;
                   2883:   /* RAN1 = RAN1 + HALF */
                   2884:   /*   RAN3(RAN2) = RAN1 */
                   2885:   /*   RANDOM = RAN1 + .5D0 */
                   2886: /*   r = ( ( double ) ( *seed ) ) * 4.656612875E-10; */
                   2887:   return rr;
                   2888: }
                   2889: static void matprint(char *s, double **v, int m, int n)
                   2890: /* char *s; */
                   2891: /* double v[N][N]; */
                   2892: {
                   2893: #define INCX 8
                   2894:   int i;
                   2895:  
                   2896:   int i2hi;
                   2897:   int ihi;
                   2898:   int ilo;
                   2899:   int i2lo;
                   2900:   int jlo=1;
                   2901:   int j;
                   2902:   int j2hi;
                   2903:   int jhi;
                   2904:   int j2lo;
                   2905:   ilo=1;
                   2906:   ihi=n;
                   2907:   jlo=1;
                   2908:   jhi=n;
                   2909:   
                   2910:   printf ("\n" );
                   2911:   printf ("%s\n", s );
                   2912:   for ( j2lo = jlo; j2lo <= jhi; j2lo = j2lo + INCX )
                   2913:   {
                   2914:     j2hi = j2lo + INCX - 1;
                   2915:     if ( n < j2hi )
                   2916:     {
                   2917:       j2hi = n;
                   2918:     }
                   2919:     if ( jhi < j2hi )
                   2920:     {
                   2921:       j2hi = jhi;
                   2922:     }
                   2923: 
                   2924:     /* fprintf ( ficlog, "\n" ); */
                   2925:     printf ("\n" );
                   2926: /*
                   2927:   For each column J in the current range...
                   2928: 
                   2929:   Write the header.
                   2930: */
                   2931:     /* fprintf ( ficlog, "  Col:  "); */
                   2932:     printf ("Col:");
                   2933:     for ( j = j2lo; j <= j2hi; j++ )
                   2934:     {
                   2935:       /* fprintf ( ficlog, "  %7d     ", j - 1 ); */
                   2936:       /* printf (" %9d      ", j - 1 ); */
                   2937:       printf (" %9d      ", j );
                   2938:     }
                   2939:     /* fprintf ( ficlog, "\n" ); */
                   2940:     /* fprintf ( ficlog, "  Row\n" ); */
                   2941:     /* fprintf ( ficlog, "\n" ); */
                   2942:     printf ("\n" );
                   2943:     printf ("  Row\n" );
                   2944:     printf ("\n" );
                   2945: /*
                   2946:   Determine the range of the rows in this strip.
                   2947: */
                   2948:     if ( 1 < ilo ){
                   2949:       i2lo = ilo;
                   2950:     }else{
                   2951:       i2lo = 1;
                   2952:     }
                   2953:     if ( m < ihi ){
                   2954:       i2hi = m;
                   2955:     }else{
                   2956:       i2hi = ihi;
                   2957:     }
                   2958: 
                   2959:     for ( i = i2lo; i <= i2hi; i++ ){
                   2960: /*
                   2961:   Print out (up to) 5 entries in row I, that lie in the current strip.
                   2962: */
                   2963:       /* fprintf ( ficlog, "%5d:", i - 1 ); */
                   2964:       /* printf ("%5d:", i - 1 ); */
                   2965:       printf ("%5d:", i );
                   2966:       for ( j = j2lo; j <= j2hi; j++ )
                   2967:       {
                   2968:         /* fprintf ( ficlog, "  %14g", a[i-1+(j-1)*m] ); */
                   2969:         /* printf ("%14.7g  ", a[i-1+(j-1)*m] ); */
                   2970:            /* printf("%14.7f  ", v[i-1][j-1]); */
                   2971:            printf("%14.7f  ", v[i][j]);
                   2972:         /* fprintf ( stdout, "  %14g", a[i-1+(j-1)*m] ); */
                   2973:       }
                   2974:       /* fprintf ( ficlog, "\n" ); */
                   2975:       printf ("\n" );
                   2976:     }
                   2977:   }
                   2978:  
                   2979:    /* printf("%s\n", s); */
                   2980:    /* for (k=0; k<n; k++) { */
                   2981:    /*     for (i=0; i<n; i++) { */
                   2982:    /*         /\* printf("%20.10e ", v[k][i]); *\/ */
                   2983:    /*     } */
                   2984:    /*     printf("\n"); */
                   2985:    /* } */
                   2986: #undef INCX  
                   2987: }
                   2988: 
                   2989: void vecprint(char *s, double *x, int n)
                   2990: /* char *s; */
                   2991: /* double x[N]; */
                   2992: {
                   2993:    int i=0;
                   2994:    
                   2995:    printf(" %s", s);
                   2996:    /* for (i=0; i<n; i++) */
                   2997:    for (i=1; i<=n; i++)
                   2998:      printf ("  %14.7g",  x[i] );
                   2999:      /* printf("  %8d: %14g\n", i, x[i]); */
                   3000:    printf ("\n" ); 
                   3001: }
                   3002: 
                   3003: static void print()            /* print a line of traces */
                   3004: {
                   3005:  
                   3006: 
                   3007:    printf("\n");
                   3008:    /* printf("... chi square reduced to ... %20.10e\n", fx); */
                   3009:    /* printf("... after %u function calls ...\n", nf); */
                   3010:    /* printf("... including %u linear searches ...\n", nl); */
                   3011:    printf("%10d    %10d%14.7g",nl, nf, fx);
                   3012:    vecprint("... current values of x ...", x, n);
                   3013: }
                   3014: /* static void print2(int n, double *x, int prin, double fx, int nf, int nl) */ /* print a line of traces */
                   3015: static void print2() /* print a line of traces */
                   3016: {
                   3017:   int i; double fmin=0.;
                   3018: 
                   3019:    /* printf("\n"); */
                   3020:    /* printf("... chi square reduced to ... %20.10e\n", fx); */
                   3021:    /* printf("... after %u function calls ...\n", nf); */
                   3022:    /* printf("... including %u linear searches ...\n", nl); */
                   3023:    /* printf("%10d    %10d%14.7g",nl, nf, fx); */
1.363     brouard  3024:   /* printf ( "\n" ); */
1.359     brouard  3025:   printf ( "  Linear searches      %d", nl );
1.364   ! brouard  3026:   fprintf (ficlog, "  Linear searches      %d", nl );
1.359     brouard  3027:   /* printf ( "  Linear searches      %d\n", nl ); */
                   3028:   /* printf ( "  Function evaluations %d\n", nf ); */
                   3029:   /* printf ( "  Function value FX = %g\n", fx ); */
                   3030:   printf ( "  Function evaluations %d", nf );
                   3031:   printf ( "  Function value FX = %.12lf\n", fx );
1.363     brouard  3032:   fprintf (ficlog, "  Function evaluations %d", nf );
                   3033:   fprintf (ficlog, "  Function value FX = %.12lf\n", fx );
1.359     brouard  3034: #ifdef DEBUGPRAX
                   3035:    printf("n=%d prin=%d\n",n,prin);
                   3036: #endif
1.363     brouard  3037:    /* if(fx <= fmin) printf(" UNDEFINED "); else  printf("%14.7g",log(fx-fmin)); */
1.359     brouard  3038:    if ( n <= 4 || 2 < prin )
                   3039:    {
                   3040:      /* for(i=1;i<=n;i++)printf("%14.7g",x[i-1]); */
1.363     brouard  3041:      for(i=1;i<=n;i++){
1.364   ! brouard  3042:        printf(" %14.7g",x[i]);
        !          3043:        fprintf(ficlog," %14.7g",x[i]);
1.363     brouard  3044:      }
1.359     brouard  3045:      /* r8vec_print ( n, x, "  X:" ); */
                   3046:    }
                   3047:    printf("\n");
1.363     brouard  3048:    fprintf(ficlog,"\n");
1.359     brouard  3049:  }
                   3050: 
                   3051: 
                   3052: /* #ifdef MSDOS */
                   3053: /* static double tflin[N]; */
                   3054: /* #endif */
                   3055: 
                   3056: static double flin(double l, int j)
                   3057: /* double l; */
                   3058: {
                   3059:    int i;
                   3060:    /* #ifndef MSDOS */
                   3061:    /*    double tflin[N]; */
                   3062:    /* #endif    */
                   3063:    /* double *tflin; */ /* Be careful to put tflin on a vector n */
                   3064: 
                   3065:    /* j is used from 0 to n-1 and can be -1 for parabolic search */
                   3066: 
                   3067:    /* if (j != -1) {           /\* linear search *\/ */
                   3068:    if (j > 0) {                /* linear search */
                   3069:      /* for (i=0; i<n; i++){ */
                   3070:      for (i=1; i<=n; i++){
                   3071:           tflin[i] = x[i] + l *v[i][j];
                   3072: #ifdef DEBUGPRAX
                   3073:          /* 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); */
                   3074:          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);
                   3075: #endif
                   3076:      }
                   3077:    }
                   3078:    else {                      /* search along parabolic space curve */
                   3079:       qa = l*(l-qd1)/(qd0*(qd0+qd1));
                   3080:       qb = (l+qd0)*(qd1-l)/(qd0*qd1);
                   3081:       qc = l*(l+qd0)/(qd1*(qd0+qd1));
                   3082: #ifdef DEBUGPRAX      
                   3083:       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);
                   3084: #endif
                   3085:       /* for (i=0; i<n; i++){ */
                   3086:       for (i=1; i<=n; i++){
                   3087:           tflin[i] = qa*q0[i]+qb*x[i]+qc*q1[i];
                   3088: #ifdef DEBUGPRAX
                   3089:           /* 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]); */
                   3090:           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]);
                   3091: #endif
                   3092:       }
                   3093:    }
                   3094:    nf++;
                   3095: 
                   3096: #ifdef NR_SHIFT
                   3097:       return (*fun)((tflin-1), n);
                   3098: #else
                   3099:      /* return (*fun)(tflin, n);*/
                   3100:       return (*fun)(tflin);
                   3101: #endif
                   3102: }
                   3103: 
                   3104: void minny(int j, int nits, double *d2, double *x1, double f1, int fk)
                   3105: /* double *d2, *x1, f1; */
                   3106: {
                   3107: /* here j is from 0 to n-1 and can be -1 for parabolic search  */
                   3108:   /*      MINIMIZES F FROM X IN THE DIRECTION V(*,J) */
                   3109:           /*      UNLESS J<1, WHEN A QUADRATIC SEARCH IS DONE */
                   3110:           /*      IN THE PLANE DEFINED BY Q0, Q1 AND X. */
                   3111:           /*      D2 AN APPROXIMATION TO HALF F'' (OR ZERO), */
                   3112:           /*      X1 AN ESTIMATE OF DISTANCE TO MINIMUM, */
                   3113:           /*      RETURNED AS THE DISTANCE FOUND. */
                   3114:           /*       IF FK = TRUE THEN F1 IS FLIN(X1), OTHERWISE */
                   3115:           /*       X1 AND F1 ARE IGNORED ON ENTRY UNLESS FINAL */
                   3116:           /*       FX > F1. NITS CONTROLS THE NUMBER OF TIMES */
                   3117:           /*       AN ATTEMPT IS MADE TO HALVE THE INTERVAL. */
                   3118:           /* SIDE EFFECTS: USES AND ALTERS X, FX, NF, NL. */
                   3119:           /*       IF J < 1 USES VARIABLES Q... . */
                   3120:          /*       USES H, N, T, M2, M4, LDT, DMIN, MACHEPS; */
                   3121:    int k, i, dz;
                   3122:    double x2, xm, f0, f2, fm, d1, t2, sf1, sx1;
                   3123:    double s;
                   3124:    double macheps;
                   3125:    macheps=pow(16.0,-13.0);
                   3126:    sf1 = f1; sx1 = *x1;
                   3127:    k = 0; xm = 0.0; fm = f0 = fx; dz = *d2 < macheps;
                   3128:    /* h=1.0;*/ /* To be revised */
                   3129: #ifdef DEBUGPRAX
                   3130:    /* printf("min macheps=%14g h=%14g step=%14g t=%14g fx=%14g\n",macheps,h, step,t, fx);  */
                   3131:    /* Where is fx coming from */
                   3132:    printf("   min macheps=%14g h=%14g  t=%14g fx=%.9lf dirj=%d\n",macheps, h, t, fx, j);
                   3133:    matprint("  min vectors:",v,n,n);
                   3134: #endif
                   3135:    /* find step size */
                   3136:    s = 0.;
                   3137:    /* for (i=0; i<n; i++) s += x[i]*x[i]; */
                   3138:    for (i=1; i<=n; i++) s += x[i]*x[i];
                   3139:    s = sqrt(s);
                   3140:    if (dz)
                   3141:       t2 = m4*sqrt(fabs(fx)/dmin + s*ldt) + m2*ldt;
                   3142:    else
                   3143:       t2 = m4*sqrt(fabs(fx)/(*d2) + s*ldt) + m2*ldt;
                   3144:    s = s*m4 + t;
                   3145:    if (dz && t2 > s) t2 = s;
                   3146:    if (t2 < small_windows) t2 = small_windows;
                   3147:    if (t2 > 0.01*h) t2 = 0.01 * h;
                   3148:    if (fk && f1 <= fm) {
                   3149:       xm = *x1;
                   3150:       fm = f1;
                   3151:    }
                   3152: #ifdef DEBUGPRAX
                   3153:    printf("   additional flin X1=%14.7f t2=%14.7f *f1=%14.7f fm=%14.7f fk=%d\n",*x1,t2,f1,fm,fk);
                   3154: #endif   
                   3155:    if (!fk || fabs(*x1) < t2) {
                   3156:      *x1 = (*x1 >= 0 ? t2 : -t2); 
                   3157:       /* *x1 = (*x1 > 0 ? t2 : -t2); */ /* kind of error */
                   3158: #ifdef DEBUGPRAX
                   3159:      printf("    additional flin X1=%16.10e dirj=%d fk=%d\n",*x1, j, fk);
                   3160: #endif
                   3161:       f1 = flin(*x1, j);
                   3162: #ifdef DEBUGPRAX
                   3163:     printf("    after flin f1=%18.12e dirj=%d fk=%d\n",f1, j,fk);
                   3164: #endif
                   3165:    }
                   3166:    if (f1 <= fm) {
                   3167:       xm = *x1;
                   3168:       fm = f1;
                   3169:    }
                   3170: L0: /*L0 loop or next */
                   3171: /*
                   3172:   Evaluate FLIN at another point and estimate the second derivative.
                   3173: */
                   3174:    if (dz) {
                   3175:       x2 = (f0 < f1 ? -(*x1) : 2*(*x1));
                   3176: #ifdef DEBUGPRAX
                   3177:       printf("     additional second flin x2=%14.8e x1=%14.8e f0=%14.8e f1=%18.12e dirj=%d\n",x2,*x1,f0,f1,j);
                   3178: #endif
                   3179:       f2 = flin(x2, j);
                   3180: #ifdef DEBUGPRAX
                   3181:       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);
                   3182: #endif
                   3183:       if (f2 <= fm) {
                   3184:          xm = x2;
                   3185:         fm = f2;
                   3186:       }
                   3187:       /* d2 is the curvature or double difference f1 doesn't seem to be accurately computed */
                   3188:       *d2 = (x2*(f1-f0) - (*x1)*(f2-f0))/((*x1)*x2*((*x1)-x2));
                   3189: #ifdef DEBUGPRAX
                   3190:       double d11,d12;
                   3191:       d11=(f1-f0)/(*x1);d12=(f2-f0)/x2;
                   3192:       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)));
                   3193:       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);
                   3194:       double ff1=7.783920622852e+04;
                   3195:       double f1mf0=9.0344736236e-05;
                   3196:       *d2 = (f1mf0)/ (*x1)/((*x1)-x2) - (f2-f0)/x2/((*x1)-x2);
                   3197:       /* *d2 = (ff1-f0)/ (*x1)/((*x1)-x2) - (f2-f0)/x2/((*x1)-x2); */
                   3198:       printf(" simpliff computing *d2=%16.10e f1mf0=%18.12e,f1=f0+f1mf0=%18.12e\n",*d2,f1mf0,f0+f1mf0);
                   3199:       *d2 = ((f1-f0)/ (*x1) - (f2-f0)/x2)/((*x1)-x2);
                   3200:       printf(" overlifi computing *d2=%16.10e\n",*d2);
                   3201: #endif
                   3202:       *d2 = ((f1-f0)/ (*x1) - (f2-f0)/x2)/((*x1)-x2);      
                   3203:    }
                   3204: #ifdef DEBUGPRAX
                   3205:       printf("    additional second flin xm=%14.8e fm=%14.8e *d2=%14.8e\n",xm, fm,*d2);
                   3206: #endif
                   3207:    /*
                   3208:      Estimate the first derivative at 0.
                   3209:    */
                   3210:    d1 = (f1-f0)/(*x1) - *x1**d2; dz = 1;
                   3211:    /*
                   3212:       Predict the minimum.
                   3213:     */
                   3214:    if (*d2 <= small_windows) {
                   3215:      x2 = (d1 < 0 ? h : -h);
                   3216:    }
                   3217:    else {
                   3218:       x2 = - 0.5*d1/(*d2);
                   3219:    }
                   3220: #ifdef DEBUGPRAX
                   3221:     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);
                   3222: #endif
                   3223:     if (fabs(x2) > h)
                   3224:       x2 = (x2 > 0 ? h : -h);
                   3225: L1:  /* L1 or try loop */
                   3226: #ifdef DEBUGPRAX
                   3227:     printf("   AT predicted minimum flin x2=%14.8e x1=%14.8e K=%14d NITS=%14d dirj=%d\n",x2,*x1,k,nits,j);
                   3228: #endif
                   3229:    f2 = flin(x2, j); /* x[i]+x2*v[i][j] */
                   3230: #ifdef DEBUGPRAX
                   3231:    printf("   after flin f0=%14.8e f1=%14.8e f2=%14.8e fm=%14.8e\n",f0,f1,f2, fm);
                   3232: #endif
                   3233:    if ((k < nits) && (f2 > f0)) {
                   3234: #ifdef DEBUGPRAX
                   3235:      printf("  NO SUCCESS SO TRY AGAIN;\n");
                   3236: #endif
                   3237:      k++;
                   3238:      if ((f0 < f1) && (*x1*x2 > 0.0))
                   3239:        goto L0; /* or next */
                   3240:      x2 *= 0.5;
                   3241:      goto L1;
                   3242:    }
                   3243:    nl++;
                   3244: #ifdef DEBUGPRAX
                   3245:    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);
                   3246: #endif
                   3247:    if (f2 > fm) x2 = xm; else fm = f2;
                   3248:    if (fabs(x2*(x2-*x1)) > small_windows) {
                   3249:       *d2 = (x2*(f1-f0) - *x1*(fm-f0))/(*x1*x2*(*x1-x2));
                   3250:    }
                   3251:    else {
                   3252:       if (k > 0) *d2 = 0;
                   3253:    }
                   3254: #ifdef DEBUGPRAX
1.362     brouard  3255:    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  3256: #endif
                   3257:    if (*d2 <= small_windows) *d2 = small_windows;
                   3258:    *x1 = x2; fx = fm;
                   3259:    if (sf1 < fx) {
                   3260:       fx = sf1;
                   3261:       *x1 = sx1;
                   3262:    }
                   3263:   /*
                   3264:     Update X for linear search.
                   3265:   */
                   3266: #ifdef DEBUGPRAX
                   3267:    printf("  end of min x1=%14.8e fx=%14.8e d2=%14.8e\n",*x1, fx, *d2);
                   3268: #endif
                   3269:    
                   3270:    /* if (j != -1) */
                   3271:    /*    for (i=0; i<n; i++) */
                   3272:    /*        x[i] += (*x1)*v[i][j]; */
                   3273:    if (j > 0)
                   3274:       for (i=1; i<=n; i++)
                   3275:           x[i] += (*x1)*v[i][j];
                   3276: }
                   3277: 
                   3278: void quad()    /* look for a minimum along the curve q0, q1, q2        */
                   3279: {
                   3280:    int i;
                   3281:    double l, s;
                   3282: 
                   3283:    s = fx; fx = qf1; qf1 = s; qd1 = 0.0;
                   3284:    /* for (i=0; i<n; i++) { */
                   3285:    for (i=1; i<=n; i++) {
                   3286:        s = x[i]; l = q1[i]; x[i] = l; q1[i] = s;
                   3287:        qd1 = qd1 + (s-l)*(s-l);
                   3288:    }
                   3289:    s = 0.0; qd1 = sqrt(qd1); l = qd1;
                   3290: #ifdef DEBUGPRAX
                   3291:   printf("  QUAD after sqrt qd1=%14.8e \n",qd1);
                   3292: #endif
                   3293:  
                   3294:    if (qd0>0.0 && qd1>0.0 &&nl>=3*n*n) {
                   3295: #ifdef DEBUGPRAX
                   3296:      printf(" QUAD before min value=%14.8e \n",qf1);
                   3297: #endif
                   3298:       /* min(-1, 2, &s, &l, qf1, 1); */
                   3299:       minny(0, 2, &s, &l, qf1, 1);
                   3300:       qa = l*(l-qd1)/(qd0*(qd0+qd1));
                   3301:       qb = (l+qd0)*(qd1-l)/(qd0*qd1);
                   3302:       qc = l*(l+qd0)/(qd1*(qd0+qd1));
                   3303:    }
                   3304:    else {
                   3305:       fx = qf1; qa = qb = 0.0; qc = 1.0;
                   3306:    }
                   3307: #ifdef DEBUGPRAX
                   3308:   printf("after eventual min qd0=%14.8e qd1=%14.8e nl=%d\n",qd0, qd1,nl);
                   3309: #endif
                   3310:    qd0 = qd1;
                   3311:    /* for (i=0; i<n; i++) { */
                   3312:    for (i=1; i<=n; i++) {
                   3313:        s = q0[i]; q0[i] = x[i];
                   3314:        x[i] = qa*s + qb*x[i] + qc*q1[i];
                   3315:    }
                   3316: #ifdef DEBUGQUAD
                   3317:    vecprint ( " X after QUAD:" , x, n );
                   3318: #endif
                   3319: }
                   3320: 
                   3321: /* void minfit(int n, double eps, double tol, double ab[N][N], double q[]) */
                   3322: void minfit(int n, double eps, double tol, double **ab, double q[])
                   3323: /* int n; */
                   3324: /* double eps, tol, ab[N][N], q[N]; */
                   3325: {
                   3326:    int l, kt, l2, i, j, k;
                   3327:    double c, f, g, h, s, x, y, z;
                   3328:    /* double eps; */
                   3329: /* #ifndef MSDOS */
                   3330: /*    double e[N];             /\* plenty of stack on a vax *\/ */
                   3331: /* #endif */
                   3332:    /* double *e; */
                   3333:    /* e=vector(0,n-1); /\* should be freed somewhere but gotos *\/ */
                   3334:    
                   3335:    /* householder's reduction to bidiagonal form */
                   3336: 
                   3337:    if(n==1){
                   3338:      /* q[1-1]=ab[1-1][1-1]; */
                   3339:      /* ab[1-1][1-1]=1.0; */
                   3340:      q[1]=ab[1][1];
                   3341:      ab[1][1]=1.0;
                   3342:      return; /* added from hardt */
                   3343:    }
                   3344:    /* eps=macheps; */ /* added */
                   3345:    x = g = 0.0;
                   3346: #ifdef DEBUGPRAX
                   3347:    matprint (" HOUSE holder:", ab, n, n);
                   3348: #endif
                   3349: 
                   3350:    /* for (i=0; i<n; i++) {  /\* FOR I := 1 UNTIL N DO *\/ */
                   3351:    for (i=1; i<=n; i++) {  /* FOR I := 1 UNTIL N DO */
                   3352:      e[i] = g; s = 0.0; l = i+1;
                   3353:      /* for (j=i; j<n; j++)  /\* FOR J := I UNTIL N DO S := S*AB(J,I)**2; *\/ /\* not correct *\/ */
                   3354:      for (j=i; j<=n; j++)  /* FOR J := I UNTIL N DO S := S*AB(J,I)**2; */ /* not correct */
                   3355:        s += ab[j][i] * ab[j][i];
                   3356: #ifdef DEBUGPRAXFIN
                   3357:      printf("i=%d s=%d %.7g tol=%.7g",i,s,tol);
                   3358: #endif
                   3359:      if (s < tol) {
                   3360:        g = 0.0;
                   3361:      }
                   3362:      else {
                   3363:        /* f = ab[i][i]; */
                   3364:        f = ab[i][i];
                   3365:        if (f < 0.0) 
                   3366:         g = sqrt(s);
                   3367:        else
                   3368:         g = -sqrt(s);
                   3369:        /* h = f*g - s; ab[i][i] = f - g; */
                   3370:        h = f*g - s; ab[i][i] = f - g;
                   3371:        /* for (j=l; j<n; j++) { */ /* FOR J := L UNTIL N DO */ /* wrong */
                   3372:        for (j=l; j<=n; j++) {
                   3373:         f = 0.0;
                   3374:         /* for (k=i; k<n; k++) /\* FOR K := I UNTIL N DO *\/ /\* wrong *\/ */
                   3375:         for (k=i; k<=n; k++) /* FOR K := I UNTIL N DO */
                   3376:           /* f += ab[k][i] * ab[k][j]; */
                   3377:           f += ab[k][i] * ab[k][j];
                   3378:         f /= h;
                   3379:         for (k=i; k<=n; k++) /* FOR K := I UNTIL N DO */
                   3380:           /* for (k=i; k<n; k++)/\* FOR K := I UNTIL N DO *\/ /\* wrong *\/ */
                   3381:           ab[k][j] += f * ab[k][i];
                   3382:         /* ab[k][j] += f * ab[k][i]; */
                   3383: #ifdef DEBUGPRAX
                   3384:         printf("Holder J=%d F=%.7g",j,f);
                   3385: #endif
                   3386:        }
                   3387:      } /* end s */
                   3388:      /* q[i] = g; s = 0.0; */
                   3389:      q[i] = g; s = 0.0;
                   3390: #ifdef DEBUGPRAX
                   3391:      printf(" I Q=%d %.7g",i,q[i]);
                   3392: #endif   
                   3393:        
                   3394:      /* if (i < n) */
                   3395:      /* if (i <= n)  /\* I is always lower or equal to n wasn't in golub reinsch*\/ */
                   3396:      /* for (j=l; j<n; j++) */
                   3397:      for (j=l; j<=n; j++)
                   3398:        s += ab[i][j] * ab[i][j];
                   3399:      /* s += ab[i][j] * ab[i][j]; */
                   3400:      if (s < tol) {
                   3401:        g = 0.0;
                   3402:      }
                   3403:      else {
                   3404:        if(i<n)
                   3405:         /* f = ab[i][i+1]; */ /* Brent golub overflow */
                   3406:         f = ab[i][i+1];
                   3407:        if (f < 0.0)
                   3408:         g = sqrt(s);
                   3409:        else 
                   3410:         g = - sqrt(s);
                   3411:        h = f*g - s;
                   3412:        /* h = f*g - s; ab[i][i+1] = f - g; */ /* Overflow for i=n Error in Golub too but not Burkardt*/
                   3413:        /* for (j=l; j<n; j++) */
                   3414:        /*     e[j] = ab[i][j]/h; */
                   3415:        if(i<n){
                   3416:         ab[i][i+1] = f - g;
                   3417:         for (j=l; j<=n; j++)
                   3418:           e[j] = ab[i][j]/h;
                   3419:         /* for (j=l; j<n; j++) { */
                   3420:         for (j=l; j<=n; j++) {
                   3421:           s = 0.0;
                   3422:           /* for (k=l; k<n; k++) s += ab[j][k]*ab[i][k]; */
                   3423:           for (k=l; k<=n; k++) s += ab[j][k]*ab[i][k];
                   3424:           /* for (k=l; k<n; k++) ab[j][k] += s * e[k]; */
                   3425:           for (k=l; k<=n; k++) ab[j][k] += s * e[k];
                   3426:         } /* END J */
                   3427:        } /* END i <n */
                   3428:      } /* end s */
                   3429:        /* y = fabs(q[i]) + fabs(e[i]); */
                   3430:      y = fabs(q[i]) + fabs(e[i]);
                   3431:      if (y > x) x = y;
                   3432: #ifdef DEBUGPRAX
                   3433:      printf(" I Y=%d %.7g",i,y);
                   3434: #endif
                   3435: #ifdef DEBUGPRAX
                   3436:      printf(" i=%d e(i) %.7g",i,e[i]);
                   3437: #endif
                   3438:    } /* end i */
                   3439:    /*
                   3440:      Accumulation of right hand transformations */
                   3441:    /* for (i=n-1; i >= 0; i--) { */ /* FOR I := N STEP -1 UNTIL 1 DO */
                   3442:    /* We should avoid the overflow in Golub */
                   3443:    /* ab[n-1][n-1] = 1.0; */
                   3444:    /* g = e[n-1]; */
                   3445:    ab[n][n] = 1.0;
                   3446:    g = e[n];
                   3447:    l = n;
                   3448: 
                   3449:    /* for (i=n; i >= 1; i--) { */
                   3450:    for (i=n-1; i >= 1; i--) { /* n-1 loops, different from brent and golub*/
                   3451:      if (g != 0.0) {
                   3452:        /* h = ab[i-1][i]*g; */
                   3453:        h = ab[i][i+1]*g;
                   3454:        for (j=l; j<=n; j++) ab[j][i] = ab[i][j] / h;
                   3455:        for (j=l; j<=n; j++) {
                   3456:         /* h = ab[i][i+1]*g; */
                   3457:         /* for (j=l; j<n; j++) ab[j][i] = ab[i][j] / h; */
                   3458:         /* for (j=l; j<n; j++) { */
                   3459:         s = 0.0;
                   3460:         /* for (k=l; k<n; k++) s += ab[i][k] * ab[k][j]; */
                   3461:         /* for (k=l; k<n; k++) ab[k][j] += s * ab[k][i]; */
                   3462:         for (k=l; k<=n; k++) s += ab[i][k] * ab[k][j];
                   3463:         for (k=l; k<=n; k++) ab[k][j] += s * ab[k][i];
                   3464:        }/* END J */
                   3465:      }/* END G */
                   3466:      /* for (j=l; j<n; j++) */
                   3467:      /*     ab[i][j] = ab[j][i] = 0.0; */
                   3468:      /* ab[i][i] = 1.0; g = e[i]; l = i; */
                   3469:      for (j=l; j<=n; j++)
                   3470:        ab[i][j] = ab[j][i] = 0.0;
                   3471:      ab[i][i] = 1.0; g = e[i]; l = i;
                   3472:    }/* END I */
                   3473: #ifdef DEBUGPRAX
                   3474:    matprint (" HOUSE accumulation:",ab,n, n );
                   3475: #endif
                   3476: 
                   3477:    /* diagonalization to bidiagonal form */
                   3478:    eps *= x;
                   3479:    /* for (k=n-1; k>= 0; k--) { */
                   3480:    for (k=n; k>= 1; k--) {
                   3481:      kt = 0;
                   3482: TestFsplitting:
                   3483: #ifdef DEBUGPRAX
                   3484:      printf(" TestFsplitting: k=%d kt=%d\n",k,kt);
                   3485:      /* for(i=1;i<=n;i++)printf(" e(%d)=%.14f",i,e[i]);printf("\n"); */
                   3486: #endif     
                   3487:      kt = kt+1; 
                   3488: /* TestFsplitting: */
                   3489:      /* if (++kt > 30) { */
                   3490:      if (kt > 30) { 
                   3491:        e[k] = 0.0;
                   3492:        fprintf(stderr, "\n+++ MINFIT - Fatal error\n");
                   3493:        fprintf ( stderr, "  The QR algorithm failed to converge.\n" );
                   3494:      }
                   3495:      /* for (l2=k; l2>=0; l2--) { */
                   3496:      for (l2=k; l2>=1; l2--) {
                   3497:        l = l2;
                   3498: #ifdef DEBUGPRAX
                   3499:        printf(" l e(l)< eps %d %.7g %.7g ",l,e[l], eps);
                   3500: #endif
                   3501:        /* if (fabs(e[l]) <= eps) */
                   3502:        if (fabs(e[l]) <= eps)
                   3503:         goto TestFconvergence;
                   3504:        /* if (fabs(q[l-1]) <= eps)*/ /* missing if ( 1 < l ){ *//* printf(" q(l-1)< eps %d %.7g %.7g ",l-1,q[l-2], eps); */
                   3505:        if (fabs(q[l-1]) <= eps)
                   3506:         break; /* goto Cancellation; */
                   3507:      }
                   3508:    Cancellation:
                   3509: #ifdef DEBUGPRAX
                   3510:      printf(" Cancellation:\n");
                   3511: #endif     
                   3512:      c = 0.0; s = 1.0;
                   3513:      for (i=l; i<=k; i++) {
                   3514:        f = s * e[i]; e[i] *= c;
                   3515:        /* f = s * e[i]; e[i] *= c; */
                   3516:        if (fabs(f) <= eps)
                   3517:         goto TestFconvergence;
                   3518:        /* g = q[i]; */
                   3519:        g = q[i];
                   3520:        if (fabs(f) < fabs(g)) {
                   3521:         double fg = f/g;
                   3522:         h = fabs(g)*sqrt(1.0+fg*fg);
                   3523:        }
                   3524:        else {
                   3525:         double gf = g/f;
                   3526:         h = (f!=0.0 ? fabs(f)*sqrt(1.0+gf*gf) : 0.0);
                   3527:        }
                   3528:        /*    COMMENT: THE ABOVE REPLACES Q(I):=H:=LONGSQRT(G*G+F*F) */
                   3529:        /* WHICH MAY GIVE INCORRECT RESULTS IF THE */
                   3530:        /* SQUARES UNDERFLOW OR IF F = G = 0; */
                   3531:        
                   3532:        /* q[i] = h; */
                   3533:        q[i] = h;
                   3534:        if (h == 0.0) { h = 1.0; g = 1.0; }
                   3535:        c = g/h; s = -f/h;
                   3536:      }
                   3537: TestFconvergence:
                   3538:  #ifdef DEBUGPRAX
                   3539:      printf(" TestFconvergence: l=%d k=%d\n",l,k);
                   3540: #endif     
                   3541:      /* z = q[k]; */
                   3542:      z = q[k];
                   3543:      if (l == k)
                   3544:        goto Convergence;
                   3545:      /* shift from bottom 2x2 minor */
                   3546:      /* x = q[l]; y = q[k-l]; g = e[k-1]; h = e[k]; */ /* Error */
                   3547:      x = q[l]; y = q[k-1]; g = e[k-1]; h = e[k];
                   3548:      f = ((y-z)*(y+z) + (g-h)*(g+h)) / (2.0*h*y);
                   3549:      g = sqrt(f*f+1.0);
                   3550:      if (f <= 0.0)
                   3551:        f = ((x-z)*(x+z) + h*(y/(f-g)-h))/x;
                   3552:      else
                   3553:        f = ((x-z)*(x+z) + h*(y/(f+g)-h))/x;
                   3554:      /* next qr transformation */
                   3555:      s = c = 1.0;
                   3556:      for (i=l+1; i<=k; i++) {
                   3557: #ifdef DEBUGPRAXQR
                   3558:        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]);
                   3559: #endif     
                   3560:        /* g = e[i]; y = q[i]; h = s*g; g *= c; */
                   3561:        g = e[i]; y = q[i]; h = s*g; g *= c;
                   3562:        if (fabs(f) < fabs(h)) {
                   3563:         double fh = f/h;
                   3564:         z = fabs(h) * sqrt(1.0 + fh*fh);
                   3565:        }
                   3566:        else {
                   3567:         double hf = h/f;
                   3568:         z = (f!=0.0 ? fabs(f)*sqrt(1.0+hf*hf) : 0.0);
                   3569:        }
                   3570:        /* e[i-1] = z; */
                   3571:        e[i-1] = z;
                   3572: #ifdef DEBUGPRAXQR
                   3573:        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]);
                   3574: #endif     
                   3575:        if (z == 0.0) 
                   3576:         f = z = 1.0;
                   3577:        c = f/z; s = h/z;
                   3578:        f = x*c + g*s; g = - x*s + g*c; h = y*s;
                   3579:        y *= c;
                   3580:        /* for (j=0; j<n; j++) { */
                   3581:        /*     x = ab[j][i-1]; z = ab[j][i]; */
                   3582:        /*     ab[j][i-1] = x*c + z*s; */
                   3583:        /*     ab[j][i] = - x*s + z*c; */
                   3584:        /* } */
                   3585:        for (j=1; j<=n; j++) {
                   3586:         x = ab[j][i-1]; z = ab[j][i];
                   3587:         ab[j][i-1] = x*c + z*s;
                   3588:         ab[j][i] = - x*s + z*c;
                   3589:        }
                   3590:        if (fabs(f) < fabs(h)) {
                   3591:         double fh = f/h;
                   3592:         z = fabs(h) * sqrt(1.0 + fh*fh);
                   3593:        }
                   3594:        else {
                   3595:         double hf = h/f;
                   3596:         z = (f!=0.0 ? fabs(f)*sqrt(1.0+hf*hf) : 0.0);
                   3597:        }
                   3598: #ifdef DEBUGPRAXQR
                   3599:        printf(" qr transformation z f h=%.7g %.7g %.7g i=%d k=%d\n",z,f,h, i, k);
                   3600: #endif
                   3601:        q[i-1] = z;
                   3602:        if (z == 0.0)
                   3603:         z = f = 1.0;
                   3604:        c = f/z; s = h/z;
                   3605:        f = c*g + s*y;  /* f can be very small */
                   3606:        x = - s*g + c*y;
                   3607:      }
                   3608:      /* e[l] = 0.0; e[k] = f; q[k] = x; */
                   3609:      e[l] = 0.0; e[k] = f; q[k] = x;
                   3610: #ifdef DEBUGPRAXQR
                   3611:      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);
                   3612: #endif
                   3613:      goto TestFsplitting;
                   3614:    Convergence:
                   3615: #ifdef DEBUGPRAX
                   3616:      printf(" Convergence:\n");
                   3617: #endif     
                   3618:      if (z < 0.0) {
                   3619:        /* q[k] = - z; */
                   3620:        /* for (j=0; j<n; j++) ab[j][k] = - ab[j][k]; */
                   3621:        q[k] = - z;
                   3622:        for (j=1; j<=n; j++) ab[j][k] = - ab[j][k];
                   3623:      }/* END Z */
                   3624:    }/* END K */
                   3625: } /* END MINFIT */
                   3626: 
                   3627: 
                   3628: double praxis(double tol, double macheps, double h0, int _n, int _prin, double *_x, double (*_fun)(double *_x))
                   3629: /* double praxis(double tol, double macheps, double h0, int _n, int _prin, double *_x, double (*_fun)(double *_x, int _n)) */
                   3630: /* double praxis(double (*_fun)(), double _x[], int _n) */
                   3631: /* double (*_fun)(); */
                   3632: /* double _x[N]; */
                   3633: /* double (*_fun)(); */
                   3634: /* double _x[N]; */
                   3635: {
                   3636:    /* init global extern variables and parameters */
                   3637:    /* double *d, *y, *z, */
                   3638:    /*   *q0, *q1, **v; */
                   3639:    /* double *tflin; /\* used in flin: return (*fun)(tflin, n); *\/ */
                   3640:    /* double *e; /\* used in minfit, don't konw how to free memory and thus made global *\/ */
                   3641: 
                   3642:   
                   3643:   int seed; /* added */
                   3644:   int biter=0;
                   3645:   double r;
                   3646:   double randbrent( int (*));
                   3647:   double s, sf;
                   3648:   
                   3649:    h = h0; /* step; */
                   3650:    t = tol;
                   3651:    scbd = 1.0;
                   3652:    illc = 0;
                   3653:    ktm = 1;
                   3654: 
                   3655:    macheps = DBL_EPSILON;
                   3656:    /* prin=4; */
                   3657: #ifdef DEBUGPRAX
                   3658:    printf("Praxis macheps=%14g h=%14g step=%14g tol=%14g\n",macheps,h, h0,tol); 
                   3659: #endif
                   3660:    n = _n;
                   3661:    x = _x;
                   3662:    prin = _prin;
                   3663:    fun = _fun;
                   3664:    d=vector(1, n);
                   3665:    y=vector(1, n);
                   3666:    z=vector(1, n);
                   3667:    q0=vector(1, n);
                   3668:    q1=vector(1, n);
                   3669:    e=vector(1, n);
                   3670:    tflin=vector(1, n);
                   3671:    v=matrix(1, n, 1, n);
                   3672:    for(i=1;i<=n;i++){d[i]=y[i]=z[i]=q0[0]=e[i]=tflin[i]=0.;}
                   3673:    small_windows = (macheps) * (macheps); vsmall = small_windows*small_windows;
                   3674:    large = 1.0/small_windows; vlarge = 1.0/vsmall;
                   3675:    m2 = sqrt(macheps); m4 = sqrt(m2);
                   3676:    seed = 123456789; /* added */
                   3677:    ldfac = (illc ? 0.1 : 0.01);
                   3678:    for(i=1;i<=n;i++) z[i]=0.; /* Was missing in Gegenfurtner as well as Brent's algol or fortran  */
                   3679:    nl = kt = 0; nf = 1;
                   3680: #ifdef NR_SHIFT
                   3681:    fx = (*fun)((x-1), n);
                   3682: #else
                   3683:    fx = (*fun)(x);
                   3684: #endif
                   3685:    qf1 = fx;
                   3686:    t2 = small_windows + fabs(t); t = t2; dmin = small_windows;
                   3687: #ifdef DEBUGPRAX
                   3688:    printf("praxis2 macheps=%14g h=%14g step=%14g small=%14g t=%14g\n",macheps,h, h0,small_windows, t); 
                   3689: #endif
                   3690:    if (h < 100.0*t) h = 100.0*t;
                   3691: #ifdef DEBUGPRAX
                   3692:    printf("praxis3 macheps=%14g h=%14g step=%14g small=%14g t=%14g\n",macheps,h, h0,small_windows, t); 
                   3693: #endif
                   3694:    ldt = h;
                   3695:    /* for (i=0; i<n; i++) for (j=0; j<n; j++) */
                   3696:    for (i=1; i<=n; i++) for (j=1; j<=n; j++)
                   3697:        v[i][j] = (i == j ? 1.0 : 0.0);
                   3698:    d[1] = 0.0; qd0 = 0.0;
                   3699:    /* for (i=0; i<n; i++) q1[i] = x[i]; */
                   3700:    for (i=1; i<=n; i++) q1[i] = x[i];
                   3701:    if (prin > 1) {
                   3702:       printf("\n------------- enter function praxis -----------\n");
                   3703:       printf("... current parameter settings ...\n");
                   3704:       printf("... scaling ... %20.10e\n", scbd);
                   3705:       printf("...   tol   ... %20.10e\n", t);
                   3706:       printf("... maxstep ... %20.10e\n", h);
                   3707:       printf("...   illc  ... %20u\n", illc);
                   3708:       printf("...   ktm   ... %20u\n", ktm);
                   3709:       printf("... maxfun  ... %20u\n", maxfun);
                   3710:    }
                   3711:    if (prin) print2();
                   3712: 
                   3713: mloop:
                   3714:     biter++;  /* Added to count the loops */
                   3715:    /* sf = d[0]; */
                   3716:    /* s = d[0] = 0.0; */
                   3717:     printf("\n Big iteration %d \n",biter);
                   3718:     fprintf(ficlog,"\n Big iteration %d \n",biter);
                   3719:     sf = d[1];
                   3720:    s = d[1] = 0.0;
                   3721: 
                   3722:    /* minimize along first direction V(*,1) */
                   3723: #ifdef DEBUGPRAX
                   3724:    printf("  Minimize along the first direction V(*,1). illc=%d\n",illc);
                   3725:    /* fprintf(ficlog,"  Minimize along the first direction V(*,1).\n"); */
                   3726: #endif
                   3727: #ifdef DEBUGPRAX2
                   3728:    printf("praxis4 macheps=%14g h=%14g step=%14g small=%14g t=%14g\n",macheps,h, h0,small_windows, t); 
                   3729: #endif
                   3730:    /* min(0, 2, &d[0], &s, fx, 0); /\* mac heps not global *\/ */
1.362     brouard  3731:    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  3732: #ifdef DEBUGPRAX
                   3733:    printf("praxis5 macheps=%14g h=%14g looks at sign of s=%14g fx=%14g\n",macheps,h, s,fx); 
                   3734: #endif
                   3735:    if (s <= 0.0)
                   3736:       /* for (i=0; i < n; i++) */
                   3737:       for (i=1; i <= n; i++)
                   3738:           v[i][1] = -v[i][1];
                   3739:    /* if ((sf <= (0.9 * d[0])) || ((0.9 * sf) >= d[0])) */
                   3740:    if ((sf <= (0.9 * d[1])) || ((0.9 * sf) >= d[1]))
                   3741:       /* for (i=1; i<n; i++) */
                   3742:       for (i=2; i<=n; i++)
                   3743:           d[i] = 0.0;
                   3744:    /* for (k=1; k<n; k++) { */
                   3745:    for (k=2; k<=n; k++) {
                   3746:     /*
                   3747:       The inner loop starts here.
                   3748:     */
                   3749: #ifdef DEBUGPRAX
                   3750:       printf("      The inner loop  here from k=%d to n=%d.\n",k,n);
                   3751:       /* fprintf(ficlog,"      The inner loop  here from k=%d to n=%d.\n",k,n); */
                   3752: #endif
                   3753:        /* for (i=0; i<n; i++) */
                   3754:        for (i=1; i<=n; i++)
                   3755:            y[i] = x[i];
                   3756:        sf = fx;
                   3757: #ifdef DEBUGPRAX
                   3758:        printf(" illc=%d and kt=%d and ktm=%d\n", illc, kt, ktm);
                   3759: #endif
                   3760:        illc = illc || (kt > 0);
                   3761: next:
                   3762:        kl = k;
                   3763:        df = 0.0;
                   3764:        if (illc) {        /* random step to get off resolution valley */
                   3765: #ifdef DEBUGPRAX
                   3766:          printf("  A random step follows, to avoid resolution valleys.\n");
                   3767:          matprint("  before rand, vectors:",v,n,n);
                   3768: #endif
                   3769:           for (i=1; i<=n; i++) {
                   3770: #ifdef NOBRENTRAND
                   3771:            r = drandom();
                   3772: #else
                   3773:            seed=i;
                   3774:            /* seed=i+1; */
                   3775: #ifdef DEBUGRAND
                   3776:            printf(" Random seed=%d, brent i=%d",seed,i); /* YYYY i=5 j=1 vji= -0.0001170073 */
                   3777: #endif
                   3778:            r = randbrent ( &seed );
                   3779: #endif
                   3780: #ifdef DEBUGRAND
                   3781:            printf(" Random r=%.7g \n",r);
                   3782: #endif     
                   3783:             z[i] = (0.1 * ldt + t2 * pow(10.0,(double)kt)) * (r - 0.5);
                   3784:            /* z[i] = (0.1 * ldt + t2 * pow(10.0,(double)kt)) * (drandom() - 0.5); */
                   3785: 
                   3786:            s = z[i];
                   3787:               for (j=1; j <= n; j++)
                   3788:                   x[j] += s * v[j][i];
                   3789:          }
                   3790: #ifdef DEBUGRAND
                   3791:          matprint("  after rand, vectors:",v,n,n);
                   3792: #endif
                   3793: #ifdef NR_SHIFT
                   3794:           fx = (*fun)((x-1), n);
                   3795: #else
                   3796:           fx = (*fun)(x, n);
                   3797: #endif
                   3798:           /* fx = (*func) ( (x-1) ); *//* This for func which is computed from x[1] and not from x[0] xm1=(x-1)*/
                   3799:           nf++;
                   3800:        }
                   3801:        /* minimize along non-conjugate directions */
                   3802: #ifdef DEBUGPRAX
                   3803:        printf(" Minimize along the 'non-conjugate' directions (dots printed) V(*,%d),...,V(*,%d).\n",k,n);
                   3804:        /* fprintf(ficlog," Minimize along the 'non-conjugate' directions  (dots printed) V(*,%d),...,V(*,%d).\n",k,n); */
                   3805: #endif
                   3806:        /* for (k2=k; k2<n; k2++) {  /\* Be careful here k2 <=n ? *\/ */
                   3807:        for (k2=k; k2<=n; k2++) {  /* Be careful here k2 <=n ? */
                   3808:            sl = fx;
                   3809:            s = 0.0;
                   3810: #ifdef DEBUGPRAX
                   3811:           printf(" Minimize along the 'NON-CONJUGATE' true direction k2=%14d fx=%14.7f\n",k2, fx);
                   3812:    matprint("  before min vectors:",v,n,n);
                   3813: #endif
                   3814:            /* min(k2, 2, &d[k2], &s, fx, 0); */
                   3815:    /*    jsearch=k2-1; */
                   3816:    /* min(jsearch, 2, &d[jsearch], &s, fx, 0); */
                   3817:    minny(k2, 2, &d[k2], &s, fx, 0);
                   3818: #ifdef DEBUGPRAX
                   3819:           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);
                   3820: #endif
                   3821:           if (illc) {
                   3822:              /* double szk = s + z[k2]; */
                   3823:               /* s = d[k2] * szk*szk; */
                   3824:              double szk = s + z[k2];
                   3825:               s = d[k2] * szk*szk;
                   3826:           }
                   3827:            else 
                   3828:              s = sl - fx;
                   3829:            /* if (df < s) { */
                   3830:            if (df <= s) {
                   3831:               df = s;
                   3832:               kl = k2;
                   3833: #ifdef DEBUGPRAX
                   3834:            printf(" df=%.7g and choose kl=%d \n",df,kl); /* UUUU */
                   3835: #endif
                   3836:            }
                   3837:        } /* end loop k2 */
                   3838:         /*
                   3839:          If there was not much improvement on the first try, set
                   3840:          ILLC = true and start the inner loop again.
                   3841:        */
                   3842: #ifdef DEBUGPRAX
                   3843:        printf(" If there was not much improvement on the first try, set ILLC = true and start the inner loop again. illc=%d\n",illc);
                   3844:        /* fprintf(ficlog,"  If there was not much improvement on the first try, set ILLC = true and start the inner loop again.\n"); */
                   3845: #endif
                   3846:         if (!illc && (df < fabs(100.0 * (macheps) * fx))) {
                   3847: #ifdef DEBUGPRAX
                   3848:          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);         
                   3849: #endif
                   3850:           illc = 1;
                   3851:           goto next;
                   3852:        }
                   3853: #ifdef DEBUGPRAX
                   3854:        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);
                   3855: #endif
                   3856:        
                   3857:        /* if ((k == 1) && (prin > 1)){ /\* be careful k=2 *\/ */
                   3858:        if ((k == 2) && (prin > 1)){ /* be careful k=2 */
                   3859: #ifdef DEBUGPRAX
                   3860:         printf("  NEW D The second difference array d:\n" );
                   3861:         /* fprintf(ficlog, " NEW D The second difference array d:\n" ); */
                   3862: #endif
                   3863:         vecprint(" NEW D The second difference array d:",d,n);
                   3864:        }
                   3865:        /* minimize along conjugate directions */ 
                   3866:        /*
                   3867:         Minimize along the "conjugate" directions V(*,1),...,V(*,K-1).
                   3868:        */
                   3869: #ifdef DEBUGPRAX
                   3870:       printf("Minimize along the 'conjugate' directions V(*,1),...,V(*,K-1=%d).\n",k-1);
                   3871:       /* fprintf(ficlog,"Minimize along the 'conjugate' directions V(*,1),...,V(*,K-1=%d).\n",k-1); */
                   3872: #endif
                   3873:       /* for (k2=0; k2<=k-1; k2++) { */
                   3874:       for (k2=1; k2<=k-1; k2++) {
                   3875:            s = 0.0;
                   3876:            /* min(k2-1, 2, &d[k2-1], &s, fx, 0); */
                   3877:            minny(k2, 2, &d[k2], &s, fx, 0);
                   3878:        }
                   3879:        f1 = fx;
                   3880:        fx = sf;
                   3881:        lds = 0.0;
                   3882:        /* for (i=0; i<n; i++) { */
                   3883:        for (i=1; i<=n; i++) {
                   3884:            sl = x[i];
                   3885:            x[i] = y[i];
                   3886:            y[i] = sl - y[i];
                   3887:            sl = y[i];
                   3888:            lds = lds + sl*sl;
                   3889:        }
                   3890:        lds = sqrt(lds);
                   3891: #ifdef DEBUGPRAX
                   3892:        printf("Minimization done 'conjugate', shifted all points, computed lds=%.8f\n",lds);
                   3893: #endif      
                   3894:       /*
                   3895:        Discard direction V(*,kl).
                   3896:        
                   3897:        If no random step was taken, V(*,KL) is the "non-conjugate"
                   3898:        direction along which the greatest improvement was made.
                   3899:       */
                   3900:        if (lds > small_windows) {
                   3901: #ifdef DEBUGPRAX
                   3902:        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);
                   3903:         matprint("  before shift new conjugate vectors:",v,n,n);
                   3904: #endif
                   3905:         for (i=kl-1; i>=k; i--) {
                   3906:           /* for (j=0; j < n; j++) */
                   3907:           for (j=1; j <= n; j++)
                   3908:             /* v[j][i+1] = v[j][i]; */ /* This is v[j][i+1]=v[j][i] i=kl-1 to k */
                   3909:             v[j][i+1] = v[j][i]; /* This is v[j][i+1]=v[j][i] i=kl-1 to k */
                   3910:           /* v[j][i+1] = v[j][i]; */
                   3911:           /* d[i+1] = d[i];*/  /* last  is d[k+1]= d[k] */
                   3912:           d[i+1] = d[i];  /* last  is d[k]= d[k-1] */
                   3913:         }
                   3914: #ifdef DEBUGPRAX
                   3915:         matprint("  after shift new conjugate vectors:",v,n,n);         
                   3916: #endif  /* d[k] = 0.0; */
                   3917:         d[k] = 0.0;
                   3918:         for (i=1; i <= n; i++)
                   3919:           v[i][k] = y[i] / lds;
                   3920:         /* v[i][k] = y[i] / lds; */
                   3921: #ifdef DEBUGPRAX
                   3922:         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);
                   3923:         /* fprintf(ficlog,"Minimize along the new 'conjugate' direction V(*,k=%d), which is the normalized vector:  (new x) - (old x).\n",k); */
                   3924:     matprint("  before min new conjugate vectors:",v,n,n);      
                   3925: #endif
                   3926:         /* min(k-1, 4, &d[k-1], &lds, f1, 1); */
                   3927:         minny(k, 4, &d[k], &lds, f1, 1);
                   3928: #ifdef DEBUGPRAX
                   3929:         printf(" after min d(k)=%d %.7g lds=%14f\n",k,d[k],lds);
                   3930:    matprint("  after min vectors:",v,n,n);
                   3931: #endif
                   3932:         if (lds <= 0.0) {
                   3933:           lds = -lds;
                   3934: #ifdef DEBUGPRAX
                   3935:          printf(" lds changed sign lds=%.14f k=%d\n",lds,k);
                   3936: #endif    
                   3937:           /* for (i=0; i<n; i++) */
                   3938:           /*   v[i][k] = -v[i][k]; */
                   3939:           for (i=1; i<=n; i++)
                   3940:             v[i][k] = -v[i][k];
                   3941:         }
                   3942:        }
                   3943:        ldt = ldfac * ldt;
                   3944:        if (ldt < lds)
                   3945:           ldt = lds;
                   3946:        if (prin > 0){
                   3947: #ifdef DEBUGPRAX
                   3948:        printf(" k=%d",k);
                   3949:        /* fprintf(ficlog," k=%d",k); */
                   3950: #endif
                   3951:        print2();/* n, x, prin, fx, nf, nl ); */
                   3952:        }
                   3953:        t2 = 0.0;
                   3954:        /* for (i=0; i<n; i++) */
                   3955:        for (i=1; i<=n; i++)
                   3956:            t2 += x[i]*x[i];
                   3957:        t2 = m2 * sqrt(t2) + t;
                   3958:        /*
                   3959:        See whether the length of the step taken since starting the
                   3960:        inner loop exceeds half the tolerance.
                   3961:       */
                   3962: #ifdef DEBUGPRAX
                   3963:        printf("See if step length exceeds half the tolerance.\n"); /* ZZZZZ */
                   3964:       /* fprintf(ficlog,"See if step length exceeds half the tolerance.\n"); */
                   3965: #endif
                   3966:        if (ldt > (0.5 * t2))
                   3967:           kt = 0;
                   3968:        else 
                   3969:          kt++;
                   3970: #ifdef DEBUGPRAX
                   3971:        printf("if kt=%d >? ktm=%d gotoL2 loop\n",kt,ktm);
                   3972: #endif
                   3973:        if (kt > ktm){
                   3974:          if ( 0 < prin ){
                   3975:           /* printf("\nr8vec_print\n X:\n"); */
                   3976:           /* fprintf(ficlog,"\nr8vec_print\n X:\n"); */
                   3977:           vecprint ("END  X:", x, n );
                   3978:         }
                   3979:            goto fret;
                   3980:        }
                   3981: #ifdef DEBUGPRAX
                   3982:    matprint("  end of L2 loop vectors:",v,n,n);
                   3983: #endif
                   3984:        
                   3985:    }
                   3986:    /* printf("The inner loop ends here.\n"); */
                   3987:    /* fprintf(ficlog,"The inner loop ends here.\n"); */
                   3988:    /*
                   3989:      The inner loop ends here.
                   3990:      
                   3991:      Try quadratic extrapolation in case we are in a curved valley.
                   3992:    */
                   3993: #ifdef DEBUGPRAX
                   3994:    printf("Try QUAD ratic extrapolation in case we are in a curved valley.\n");
                   3995: #endif
                   3996:    /*  try quadratic extrapolation in case    */
                   3997:    /*  we are stuck in a curved valley        */
                   3998:    quad();
                   3999:    dn = 0.0;
                   4000:    /* for (i=0; i<n; i++) { */
                   4001:    for (i=1; i<=n; i++) {
                   4002:        d[i] = 1.0 / sqrt(d[i]);
                   4003:        if (dn < d[i])
                   4004:           dn = d[i];
                   4005:    }
                   4006:    if (prin > 2)
                   4007:      matprint("  NEW DIRECTIONS vectors:",v,n,n);
                   4008:    /* for (j=0; j<n; j++) { */
                   4009:    for (j=1; j<=n; j++) {
                   4010:        s = d[j] / dn;
                   4011:        /* for (i=0; i < n; i++) */
                   4012:        for (i=1; i <= n; i++)
                   4013:            v[i][j] *= s;
                   4014:    }
                   4015:    
                   4016:    if (scbd > 1.0) {       /* scale axis to reduce condition number */
                   4017: #ifdef DEBUGPRAX
                   4018:      printf("Scale the axes to try to reduce the condition number.\n");
                   4019: #endif
                   4020:      /* fprintf(ficlog,"Scale the axes to try to reduce the condition number.\n"); */
                   4021:       s = vlarge;
                   4022:       /* for (i=0; i<n; i++) { */
                   4023:       for (i=1; i<=n; i++) {
                   4024:           sl = 0.0;
                   4025:           /* for (j=0; j < n; j++) */
                   4026:           for (j=1; j <= n; j++)
                   4027:               sl += v[i][j]*v[i][j];
                   4028:           z[i] = sqrt(sl);
                   4029:           if (z[i] < m4)
                   4030:              z[i] = m4;
                   4031:           if (s > z[i])
                   4032:              s = z[i];
                   4033:       }
                   4034:       /* for (i=0; i<n; i++) { */
                   4035:       for (i=1; i<=n; i++) {
                   4036:           sl = s / z[i];
                   4037:           z[i] = 1.0 / sl;
                   4038:           if (z[i] > scbd) {
                   4039:              sl = 1.0 / scbd;
                   4040:              z[i] = scbd;
                   4041:           }
                   4042:       }
                   4043:    }
                   4044:    for (i=1; i<=n; i++)
                   4045:        /* for (j=0; j<=i-1; j++) { */
                   4046:        /* for (j=1; j<=i; j++) { */
                   4047:        for (j=1; j<=i-1; j++) {
                   4048:            s = v[i][j];
                   4049:            v[i][j] = v[j][i];
                   4050:            v[j][i] = s;
                   4051:        }
                   4052: #ifdef DEBUGPRAX
                   4053:     printf(" Calculate a new set of orthogonal directions before repeating  the main loop.\n  Transpose V for MINFIT:...\n");
                   4054: #endif
                   4055:       /*
                   4056:       MINFIT finds the singular value decomposition of V.
                   4057: 
                   4058:       This gives the principal values and principal directions of the
                   4059:       approximating quadratic form without squaring the condition number.
                   4060:     */
                   4061:  #ifdef DEBUGPRAX
                   4062:     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");
                   4063: #endif
                   4064: 
                   4065:    minfit(n, macheps, vsmall, v, d);
                   4066:     /* for(i=0; i<n;i++)printf(" %14.7g",d[i]); */
                   4067:     /* v is overwritten with R. */
                   4068:     /*
                   4069:       Unscale the axes.
                   4070:     */
                   4071:    if (scbd > 1.0) {
                   4072: #ifdef DEBUGPRAX
                   4073:       printf(" Unscale the axes.\n");
                   4074: #endif
                   4075:       /* for (i=0; i<n; i++) { */
                   4076:       for (i=1; i<=n; i++) {
                   4077:           s = z[i];
                   4078:           /* for (j=0; j<n; j++) */
                   4079:           for (j=1; j<=n; j++)
                   4080:               v[i][j] *= s;
                   4081:       }
                   4082:       /* for (i=0; i<n; i++) { */
                   4083:       for (i=1; i<=n; i++) {
                   4084:           s = 0.0;
                   4085:           /* for (j=0; j<n; j++) */
                   4086:           for (j=1; j<=n; j++)
                   4087:               s += v[j][i]*v[j][i];
                   4088:           s = sqrt(s);
                   4089:           d[i] *= s;
                   4090:           s = 1.0 / s;
                   4091:           /* for (j=0; j<n; j++) */
                   4092:           for (j=1; j<=n; j++)
                   4093:               v[j][i] *= s;
                   4094:       }
                   4095:    }
                   4096:    /* for (i=0; i<n; i++) { */
                   4097:    double dni; /* added for compatibility with buckhardt but not brent */
                   4098:    for (i=1; i<=n; i++) {
                   4099:      dni=dn*d[i]; /* added for compatibility with buckhardt but not brent */
                   4100:        if ((dn * d[i]) > large)
                   4101:           d[i] = vsmall;
                   4102:        else if ((dn * d[i]) < small_windows)
                   4103:           d[i] = vlarge;
                   4104:        else 
                   4105:         d[i] = 1.0 / dni / dni; /* added for compatibility with buckhardt but not brent */
                   4106:           /* d[i] = pow(dn * d[i],-2.0); */
                   4107:    }
                   4108: #ifdef DEBUGPRAX
                   4109:    vecprint ("\n Before sort Eigenvalues of a:",d,n );
                   4110: #endif
                   4111:    
                   4112:    sort();               /* the new eigenvalues and eigenvectors */
                   4113: #ifdef DEBUGPRAX
                   4114:    vecprint( " After sort the eigenvalues ....\n", d, n);
                   4115:    matprint( " After sort the eigenvectors....\n", v, n,n);
                   4116: #endif
                   4117: #ifdef DEBUGPRAX
                   4118:     printf("  Determine the smallest eigenvalue.\n");
                   4119: #endif
                   4120:    /* dmin = d[n-1]; */
                   4121:    dmin = d[n];
                   4122:    if (dmin < small_windows)
                   4123:       dmin = small_windows;
                   4124:     /*
                   4125:      The ratio of the smallest to largest eigenvalue determines whether
                   4126:      the system is ill conditioned.
                   4127:    */
                   4128:   
                   4129:    /* illc = (m2 * d[0]) > dmin; */
                   4130:    illc = (m2 * d[1]) > dmin;
                   4131: #ifdef DEBUGPRAX
                   4132:     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]);
                   4133: #endif
                   4134:    
                   4135:    if ((prin > 2) && (scbd > 1.0))
                   4136:       vecprint("\n The scale factors:",z,n);
                   4137:    if (prin > 2)
                   4138:       vecprint("  Principal values (EIGEN VALUES OF A) of the quadratic form:",d,n);
                   4139:    if (prin > 2)
                   4140:      matprint("  The principal axes (EIGEN VECTORS OF A:",v,n, n);
                   4141: 
                   4142:    if ((maxfun > 0) && (nf > maxfun)) {
                   4143:       if (prin)
                   4144:         printf("\n... maximum number of function calls reached ...\n");
                   4145:       goto fret;
                   4146:    }
                   4147: #ifdef DEBUGPRAX
                   4148:    printf("Goto main loop\n");
                   4149: #endif
                   4150:    goto mloop;          /* back to main loop */
                   4151: 
                   4152: fret:
                   4153:    if (prin > 0) {
                   4154:          vecprint("\n  X:", x, n);
                   4155:          /* printf("\n... ChiSq reduced to %20.10e ...\n", fx); */
                   4156:         /* printf("... after %20u function calls.\n", nf); */
                   4157:    }
                   4158:    free_vector(d, 1, n);
                   4159:    free_vector(y, 1, n);
                   4160:    free_vector(z, 1, n);
                   4161:    free_vector(q0, 1, n);
                   4162:    free_vector(q1, 1, n);
                   4163:    free_matrix(v, 1, n, 1, n);
                   4164:    /*   double *d, *y, *z, */
                   4165:    /* *q0, *q1, **v; */
                   4166:    free_vector(tflin, 1, n);
                   4167:    /* double *tflin; /\* used in flin: return (*fun)(tflin, n); *\/ */
                   4168:    free_vector(e, 1, n);
                   4169:    /* double *e; /\* used in minfit, don't konw how to free memory and thus made global *\/ */
                   4170:    
                   4171:    return(fx);
                   4172: }
                   4173: 
                   4174: /* end praxis gegen */
1.126     brouard  4175: 
                   4176: /*************** powell ************************/
1.162     brouard  4177: /*
1.317     brouard  4178: Minimization of a function func of n variables. Input consists in an initial starting point
                   4179: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   4180: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   4181: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  4182: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   4183: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   4184:  */
1.224     brouard  4185: #ifdef LINMINORIGINAL
                   4186: #else
                   4187:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  4188:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  4189: #endif
1.126     brouard  4190: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   4191:            double (*func)(double [])) 
                   4192: { 
1.224     brouard  4193: #ifdef LINMINORIGINAL
                   4194:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  4195:              double (*func)(double [])); 
1.224     brouard  4196: #else 
1.241     brouard  4197:  void linmin(double p[], double xi[], int n, double *fret,
                   4198:             double (*func)(double []),int *flat); 
1.224     brouard  4199: #endif
1.239     brouard  4200:  int i,ibig,j,jk,k; 
1.126     brouard  4201:   double del,t,*pt,*ptt,*xit;
1.181     brouard  4202:   double directest;
1.126     brouard  4203:   double fp,fptt;
                   4204:   double *xits;
                   4205:   int niterf, itmp;
1.349     brouard  4206:   int Bigter=0, nBigterf=1;
                   4207:   
1.126     brouard  4208:   pt=vector(1,n); 
                   4209:   ptt=vector(1,n); 
                   4210:   xit=vector(1,n); 
                   4211:   xits=vector(1,n); 
                   4212:   *fret=(*func)(p); 
                   4213:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.338     brouard  4214:   rcurr_time = time(NULL);
                   4215:   fp=(*fret); /* Initialisation */
1.126     brouard  4216:   for (*iter=1;;++(*iter)) { 
                   4217:     ibig=0; 
                   4218:     del=0.0; 
1.157     brouard  4219:     rlast_time=rcurr_time;
1.349     brouard  4220:     rlast_btime=rcurr_time;
1.157     brouard  4221:     /* (void) gettimeofday(&curr_time,&tzp); */
                   4222:     rcurr_time = time(NULL);  
                   4223:     curr_time = *localtime(&rcurr_time);
1.337     brouard  4224:     /* 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); */
                   4225:     /* 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  4226:     /* Bigter=(*iter - *iter % ncovmodel)/ncovmodel +1; /\* Big iteration, i.e on ncovmodel cycle *\/ */
                   4227:     Bigter=(*iter - (*iter-1) % n)/n +1; /* Big iteration, i.e on ncovmodel cycle */
1.349     brouard  4228:     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);
                   4229:     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);
                   4230:     fprintf(ficrespow,"%d %d %.12f %d",*iter,Bigter, *fret,curr_time.tm_sec-start_time.tm_sec);
1.324     brouard  4231:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  4232:     for (i=1;i<=n;i++) {
1.126     brouard  4233:       fprintf(ficrespow," %.12lf", p[i]);
                   4234:     }
1.239     brouard  4235:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   4236:     printf("\n#model=  1      +     age ");
                   4237:     fprintf(ficlog,"\n#model=  1      +     age ");
                   4238:     if(nagesqr==1){
1.241     brouard  4239:        printf("  + age*age  ");
                   4240:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  4241:     }
1.362     brouard  4242:     for(j=1;j <=ncovmodel-2-nagesqr;j++){
1.239     brouard  4243:       if(Typevar[j]==0) {
                   4244:        printf("  +      V%d  ",Tvar[j]);
                   4245:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   4246:       }else if(Typevar[j]==1) {
                   4247:        printf("  +    V%d*age ",Tvar[j]);
                   4248:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   4249:       }else if(Typevar[j]==2) {
                   4250:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   4251:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  4252:       }else if(Typevar[j]==3) {
                   4253:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   4254:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.239     brouard  4255:       }
                   4256:     }
1.126     brouard  4257:     printf("\n");
1.239     brouard  4258: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   4259: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  4260:     fprintf(ficlog,"\n");
1.239     brouard  4261:     for(i=1,jk=1; i <=nlstate; i++){
                   4262:       for(k=1; k <=(nlstate+ndeath); k++){
                   4263:        if (k != i) {
                   4264:          printf("%d%d ",i,k);
                   4265:          fprintf(ficlog,"%d%d ",i,k);
                   4266:          for(j=1; j <=ncovmodel; j++){
                   4267:            printf("%12.7f ",p[jk]);
                   4268:            fprintf(ficlog,"%12.7f ",p[jk]);
                   4269:            jk++; 
                   4270:          }
                   4271:          printf("\n");
                   4272:          fprintf(ficlog,"\n");
                   4273:        }
                   4274:       }
                   4275:     }
1.241     brouard  4276:     if(*iter <=3 && *iter >1){
1.157     brouard  4277:       tml = *localtime(&rcurr_time);
                   4278:       strcpy(strcurr,asctime(&tml));
                   4279:       rforecast_time=rcurr_time; 
1.126     brouard  4280:       itmp = strlen(strcurr);
                   4281:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  4282:        strcurr[itmp-1]='\0';
1.162     brouard  4283:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  4284:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.349     brouard  4285:       for(nBigterf=1;nBigterf<=31;nBigterf+=10){
                   4286:        niterf=nBigterf*ncovmodel;
                   4287:        /* rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time); */
1.241     brouard  4288:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   4289:        forecast_time = *localtime(&rforecast_time);
                   4290:        strcpy(strfor,asctime(&forecast_time));
                   4291:        itmp = strlen(strfor);
                   4292:        if(strfor[itmp-1]=='\n')
                   4293:          strfor[itmp-1]='\0';
1.349     brouard  4294:        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);
                   4295:        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  4296:       }
                   4297:     }
1.359     brouard  4298:     for (i=1;i<=n;i++) { /* For each direction i, maximisation after loading directions */
                   4299:       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  */
                   4300: 
                   4301:       fptt=(*fret); /* Computes likelihood for parameters xit */
1.126     brouard  4302: #ifdef DEBUG
1.203     brouard  4303:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   4304:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  4305: #endif
1.203     brouard  4306:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  4307:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  4308: #ifdef LINMINORIGINAL
1.359     brouard  4309:       linmin(p,xit,n,fret,func); /* New point i minimizing in direction xit, i has coordinates p[j].*/
1.357     brouard  4310:       /* xit[j] gives the n coordinates of direction i as input.*/
                   4311:       /* *fret gives the maximum value on direction xit */
1.224     brouard  4312: #else
                   4313:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.359     brouard  4314:       flatdir[i]=flat; /* Function is vanishing in that direction i */
1.224     brouard  4315: #endif
1.359     brouard  4316:       /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  4317:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.359     brouard  4318:        /* because that direction will be replaced unless the gain del is small */
                   4319:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   4320:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   4321:        /* with the new direction. */
                   4322:        del=fabs(fptt-(*fret)); 
                   4323:        ibig=i; 
1.126     brouard  4324:       } 
                   4325: #ifdef DEBUG
                   4326:       printf("%d %.12e",i,(*fret));
                   4327:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   4328:       for (j=1;j<=n;j++) {
1.359     brouard  4329:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   4330:        printf(" x(%d)=%.12e",j,xit[j]);
                   4331:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  4332:       }
                   4333:       for(j=1;j<=n;j++) {
1.359     brouard  4334:        printf(" p(%d)=%.12e",j,p[j]);
                   4335:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  4336:       }
                   4337:       printf("\n");
                   4338:       fprintf(ficlog,"\n");
                   4339: #endif
1.187     brouard  4340:     } /* end loop on each direction i */
1.357     brouard  4341:     /* Convergence test will use last linmin estimation (fret) and compare to former iteration (fp) */ 
1.188     brouard  4342:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.359     brouard  4343:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  4344:     for(j=1;j<=n;j++) {
                   4345:       if(flatdir[j] >0){
                   4346:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   4347:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  4348:       }
1.319     brouard  4349:       /* printf("\n"); */
                   4350:       /* fprintf(ficlog,"\n"); */
                   4351:     }
1.243     brouard  4352:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   4353:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  4354:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   4355:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   4356:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   4357:       /* decreased of more than 3.84  */
                   4358:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   4359:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   4360:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  4361:                        
1.188     brouard  4362:       /* Starting the program with initial values given by a former maximization will simply change */
                   4363:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   4364:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   4365:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  4366: #ifdef DEBUG
                   4367:       int k[2],l;
                   4368:       k[0]=1;
                   4369:       k[1]=-1;
                   4370:       printf("Max: %.12e",(*func)(p));
                   4371:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   4372:       for (j=1;j<=n;j++) {
                   4373:        printf(" %.12e",p[j]);
                   4374:        fprintf(ficlog," %.12e",p[j]);
                   4375:       }
                   4376:       printf("\n");
                   4377:       fprintf(ficlog,"\n");
                   4378:       for(l=0;l<=1;l++) {
                   4379:        for (j=1;j<=n;j++) {
                   4380:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   4381:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   4382:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   4383:        }
                   4384:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   4385:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   4386:       }
                   4387: #endif
                   4388: 
                   4389:       free_vector(xit,1,n); 
                   4390:       free_vector(xits,1,n); 
                   4391:       free_vector(ptt,1,n); 
                   4392:       free_vector(pt,1,n); 
                   4393:       return; 
1.192     brouard  4394:     } /* enough precision */ 
1.240     brouard  4395:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.359     brouard  4396:     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  4397:       ptt[j]=2.0*p[j]-pt[j]; 
1.359     brouard  4398:       xit[j]=p[j]-pt[j]; /* Coordinate j of last direction xi_n=P_n-P_0 */
                   4399: #ifdef DEBUG
                   4400:       printf("\n %d xit=%12.7g p=%12.7g pt=%12.7g ",j,xit[j],p[j],pt[j]);
                   4401: #endif
                   4402:       pt[j]=p[j]; /* New P0 is Pn */
                   4403:     }
                   4404: #ifdef DEBUG
                   4405:     printf("\n");
                   4406: #endif
1.181     brouard  4407:     fptt=(*func)(ptt); /* f_3 */
1.359     brouard  4408: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in directions until some iterations are done */
1.224     brouard  4409:                if (*iter <=4) {
1.225     brouard  4410: #else
                   4411: #endif
1.224     brouard  4412: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  4413: #else
1.161     brouard  4414:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  4415: #endif
1.162     brouard  4416:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  4417:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  4418:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   4419:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   4420:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  4421:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   4422:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   4423:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  4424:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  4425:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   4426:       /* mu² and del² are equal when f3=f1 */
1.359     brouard  4427:       /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   4428:       /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   4429:       /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   4430:       /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  4431: #ifdef NRCORIGINAL
                   4432:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   4433: #else
                   4434:       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  4435:       t= t- del*SQR(fp-fptt);
1.183     brouard  4436: #endif
1.202     brouard  4437:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  4438: #ifdef DEBUG
1.181     brouard  4439:       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);
                   4440:       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  4441:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   4442:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   4443:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   4444:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   4445:       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);
                   4446:       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);
                   4447: #endif
1.183     brouard  4448: #ifdef POWELLORIGINAL
                   4449:       if (t < 0.0) { /* Then we use it for new direction */
1.361     brouard  4450: #else  /* Not POWELLOriginal but Brouard's */
1.182     brouard  4451:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.359     brouard  4452:        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  4453:         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  4454:         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  4455:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   4456:       } 
1.361     brouard  4457:       if (directest < 0.0) { /* Then we use (P0, Pn) for new direction Xi_n or Xi_iBig */
1.181     brouard  4458: #endif
1.191     brouard  4459: #ifdef DEBUGLINMIN
1.234     brouard  4460:        printf("Before linmin in direction P%d-P0\n",n);
                   4461:        for (j=1;j<=n;j++) {
                   4462:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   4463:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   4464:          if(j % ncovmodel == 0){
                   4465:            printf("\n");
                   4466:            fprintf(ficlog,"\n");
                   4467:          }
                   4468:        }
1.224     brouard  4469: #endif
                   4470: #ifdef LINMINORIGINAL
1.234     brouard  4471:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  4472: #else
1.234     brouard  4473:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   4474:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  4475: #endif
1.234     brouard  4476:        
1.191     brouard  4477: #ifdef DEBUGLINMIN
1.234     brouard  4478:        for (j=1;j<=n;j++) { 
                   4479:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   4480:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   4481:          if(j % ncovmodel == 0){
                   4482:            printf("\n");
                   4483:            fprintf(ficlog,"\n");
                   4484:          }
                   4485:        }
1.224     brouard  4486: #endif
1.234     brouard  4487:        for (j=1;j<=n;j++) { 
                   4488:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   4489:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   4490:        }
1.361     brouard  4491: 
                   4492: /* #else */
                   4493: /*     for (i=1;i<=n-1;i++) {  */
                   4494: /*       for (j=1;j<=n;j++) {  */
                   4495: /*         xi[j][i]=xi[j][i+1]; /\* Standard method of conjugate directions, not Powell who changes the nth direction by p0 pn . *\/ */
                   4496: /*       } */
                   4497: /*     } */
                   4498: /*     for (j=1;j<=n;j++) {  */
                   4499: /*       xi[j][n]=xit[j];      /\* and this nth direction by the by the average p_0 p_n *\/ */
                   4500: /*     } */
                   4501: /*     /\* for (j=1;j<=n-1;j++) {  *\/ */
                   4502: /*     /\*   xi[j][1]=xi[j][j+1]; /\\* Standard method of conjugate directions *\\/ *\/ */
                   4503: /*     /\*   xi[j][n]=xit[j];      /\\* and this nth direction by the by the average p_0 p_n *\\/ *\/ */
                   4504: /*     /\* } *\/ */
                   4505: /* #endif */
1.224     brouard  4506: #ifdef LINMINORIGINAL
                   4507: #else
1.234     brouard  4508:        for (j=1, flatd=0;j<=n;j++) {
                   4509:          if(flatdir[j]>0)
                   4510:            flatd++;
                   4511:        }
                   4512:        if(flatd >0){
1.255     brouard  4513:          printf("%d flat directions: ",flatd);
                   4514:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  4515:          for (j=1;j<=n;j++) { 
                   4516:            if(flatdir[j]>0){
                   4517:              printf("%d ",j);
                   4518:              fprintf(ficlog,"%d ",j);
                   4519:            }
                   4520:          }
                   4521:          printf("\n");
                   4522:          fprintf(ficlog,"\n");
1.319     brouard  4523: #ifdef FLATSUP
                   4524:           free_vector(xit,1,n); 
                   4525:           free_vector(xits,1,n); 
                   4526:           free_vector(ptt,1,n); 
                   4527:           free_vector(pt,1,n); 
                   4528:           return;
                   4529: #endif
1.361     brouard  4530:        }  /* endif(flatd >0) */
                   4531: #endif /* LINMINORIGINAL */
1.234     brouard  4532:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   4533:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   4534:        
1.126     brouard  4535: #ifdef DEBUG
1.234     brouard  4536:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   4537:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   4538:        for(j=1;j<=n;j++){
                   4539:          printf(" %lf",xit[j]);
                   4540:          fprintf(ficlog," %lf",xit[j]);
                   4541:        }
                   4542:        printf("\n");
                   4543:        fprintf(ficlog,"\n");
1.126     brouard  4544: #endif
1.192     brouard  4545:       } /* end of t or directest negative */
1.359     brouard  4546:       printf(" Directest is positive, P_n-P_0 does not increase the conjugacy. n=%d\n",n);
                   4547:       fprintf(ficlog," Directest is positive, P_n-P_0 does not increase the conjugacy. n=%d\n",n);
1.224     brouard  4548: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  4549: #else
1.234     brouard  4550:       } /* end if (fptt < fp)  */
1.192     brouard  4551: #endif
1.225     brouard  4552: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  4553:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  4554: #else
1.224     brouard  4555: #endif
1.234     brouard  4556:                } /* loop iteration */ 
1.126     brouard  4557: } 
1.234     brouard  4558:   
1.126     brouard  4559: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  4560:   
1.235     brouard  4561:   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  4562:   {
1.338     brouard  4563:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
1.279     brouard  4564:      *   (and selected quantitative values in nres)
                   4565:      *  by left multiplying the unit
                   4566:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   4567:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   4568:      * Wx is row vector: population in state 1, population in state 2, population dead
                   4569:      * or prevalence in state 1, prevalence in state 2, 0
                   4570:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   4571:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   4572:      * Output is prlim.
                   4573:      * Initial matrix pimij 
                   4574:      */
1.206     brouard  4575:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   4576:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   4577:   /*  0,                   0                  , 1} */
                   4578:   /*
                   4579:    * and after some iteration: */
                   4580:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   4581:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   4582:   /*  0,                   0                  , 1} */
                   4583:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   4584:   /* {0.51571254859325999, 0.4842874514067399, */
                   4585:   /*  0.51326036147820708, 0.48673963852179264} */
                   4586:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  4587:     
1.332     brouard  4588:     int i, ii,j,k, k1;
1.209     brouard  4589:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  4590:   /* double **matprod2(); */ /* test */
1.218     brouard  4591:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  4592:   double **newm;
1.209     brouard  4593:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  4594:   int ncvloop=0;
1.288     brouard  4595:   int first=0;
1.169     brouard  4596:   
1.209     brouard  4597:   min=vector(1,nlstate);
                   4598:   max=vector(1,nlstate);
                   4599:   meandiff=vector(1,nlstate);
                   4600: 
1.218     brouard  4601:        /* Starting with matrix unity */
1.126     brouard  4602:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   4603:     for (j=1;j<=nlstate+ndeath;j++){
                   4604:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4605:     }
1.169     brouard  4606:   
                   4607:   cov[1]=1.;
                   4608:   
                   4609:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  4610:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  4611:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  4612:     ncvloop++;
1.126     brouard  4613:     newm=savm;
                   4614:     /* Covariates have to be included here again */
1.138     brouard  4615:     cov[2]=agefin;
1.319     brouard  4616:      if(nagesqr==1){
                   4617:       cov[3]= agefin*agefin;
                   4618:      }
1.332     brouard  4619:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   4620:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   4621:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  4622:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  4623:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   4624:        }else{
                   4625:         cov[2+nagesqr+k1]=precov[nres][k1];
                   4626:        }
                   4627:      }/* End of loop on model equation */
                   4628:      
                   4629: /* Start of old code (replaced by a loop on position in the model equation */
                   4630:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   4631:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   4632:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   4633:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   4634:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   4635:     /*    * k                  1        2      3    4      5      6     7        8 */
                   4636:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   4637:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   4638:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   4639:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   4640:     /*    *nsd=3                              (1)  (2)           (3) */
                   4641:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   4642:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   4643:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   4644:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   4645:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   4646:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   4647:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   4648:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   4649:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   4650:     /*    *TvarsDpType */
                   4651:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   4652:     /*    * nsd=1              (1)           (2) */
                   4653:     /*    *TvarsD[nsd]          3             2 */
                   4654:     /*    *TnsdVar           (3)=1          (2)=2 */
                   4655:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   4656:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   4657:     /*    *\/ */
                   4658:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   4659:     /*   /\* 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)); *\/ */
                   4660:     /* } */
                   4661:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   4662:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   4663:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   4664:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   4665:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   4666:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   4667:     /*   /\* 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]); *\/ */
                   4668:     /* } */
                   4669:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   4670:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   4671:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   4672:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   4673:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   4674:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   4675:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   4676:     /*   } */
                   4677:     /*   /\* 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]); *\/ */
                   4678:     /* } */
                   4679:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   4680:     /*   /\* 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]); *\/ */
                   4681:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   4682:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   4683:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   4684:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   4685:     /*         }else{ */
                   4686:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   4687:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   4688:     /*         } */
                   4689:     /*   }else{ */
                   4690:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   4691:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   4692:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   4693:     /*         }else{ */
                   4694:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   4695:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   4696:     /*         } */
                   4697:     /*   } */
                   4698:     /* } /\* End product without age *\/ */
                   4699: /* ENd of old code */
1.138     brouard  4700:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   4701:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   4702:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  4703:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4704:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  4705:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  4706:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  4707:     
1.126     brouard  4708:     savm=oldm;
                   4709:     oldm=newm;
1.209     brouard  4710: 
                   4711:     for(j=1; j<=nlstate; j++){
                   4712:       max[j]=0.;
                   4713:       min[j]=1.;
                   4714:     }
                   4715:     for(i=1;i<=nlstate;i++){
                   4716:       sumnew=0;
                   4717:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   4718:       for(j=1; j<=nlstate; j++){ 
                   4719:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   4720:        max[j]=FMAX(max[j],prlim[i][j]);
                   4721:        min[j]=FMIN(min[j],prlim[i][j]);
                   4722:       }
                   4723:     }
                   4724: 
1.126     brouard  4725:     maxmax=0.;
1.209     brouard  4726:     for(j=1; j<=nlstate; j++){
                   4727:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   4728:       maxmax=FMAX(maxmax,meandiff[j]);
                   4729:       /* 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  4730:     } /* j loop */
1.203     brouard  4731:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  4732:     /* 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  4733:     if(maxmax < ftolpl){
1.209     brouard  4734:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   4735:       free_vector(min,1,nlstate);
                   4736:       free_vector(max,1,nlstate);
                   4737:       free_vector(meandiff,1,nlstate);
1.126     brouard  4738:       return prlim;
                   4739:     }
1.288     brouard  4740:   } /* agefin loop */
1.208     brouard  4741:     /* After some age loop it doesn't converge */
1.288     brouard  4742:   if(!first){
                   4743:     first=1;
                   4744:     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  4745:     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);
                   4746:   }else if (first >=1 && first <10){
                   4747:     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);
                   4748:     first++;
                   4749:   }else if (first ==10){
                   4750:     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);
                   4751:     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");
                   4752:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   4753:     first++;
1.288     brouard  4754:   }
                   4755: 
1.359     brouard  4756:   /* Try to lower 'ftol', for example from 1.e-8 to 6.e-9.\n", ftolpl,
                   4757:    * (int)age, (int)delaymax, (int)agefin, ncvloop,
                   4758:    * (int)age-(int)agefin); */
1.209     brouard  4759:   free_vector(min,1,nlstate);
                   4760:   free_vector(max,1,nlstate);
                   4761:   free_vector(meandiff,1,nlstate);
1.208     brouard  4762:   
1.169     brouard  4763:   return prlim; /* should not reach here */
1.126     brouard  4764: }
                   4765: 
1.217     brouard  4766: 
                   4767:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   4768: 
1.218     brouard  4769:  /* 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) */
                   4770:  /* 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  4771:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  4772: {
1.264     brouard  4773:   /* 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  4774:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   4775:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   4776:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   4777:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   4778:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   4779:   /* Initial matrix pimij */
                   4780:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   4781:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   4782:   /*  0,                   0                  , 1} */
                   4783:   /*
                   4784:    * and after some iteration: */
                   4785:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   4786:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   4787:   /*  0,                   0                  , 1} */
                   4788:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   4789:   /* {0.51571254859325999, 0.4842874514067399, */
                   4790:   /*  0.51326036147820708, 0.48673963852179264} */
                   4791:   /* If we start from prlim again, prlim tends to a constant matrix */
                   4792: 
1.359     brouard  4793:   int i, ii,j, k1;
1.247     brouard  4794:   int first=0;
1.217     brouard  4795:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   4796:   /* double **matprod2(); */ /* test */
                   4797:   double **out, cov[NCOVMAX+1], **bmij();
                   4798:   double **newm;
1.218     brouard  4799:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   4800:   double        **oldm, **savm;  /* for use */
                   4801: 
1.217     brouard  4802:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   4803:   int ncvloop=0;
                   4804:   
                   4805:   min=vector(1,nlstate);
                   4806:   max=vector(1,nlstate);
                   4807:   meandiff=vector(1,nlstate);
                   4808: 
1.266     brouard  4809:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   4810:   oldm=oldms; savm=savms;
                   4811:   
                   4812:   /* Starting with matrix unity */
                   4813:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   4814:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  4815:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4816:     }
                   4817:   
                   4818:   cov[1]=1.;
                   4819:   
                   4820:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   4821:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  4822:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  4823:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   4824:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  4825:     ncvloop++;
1.218     brouard  4826:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   4827:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  4828:     /* Covariates have to be included here again */
                   4829:     cov[2]=agefin;
1.319     brouard  4830:     if(nagesqr==1){
1.217     brouard  4831:       cov[3]= agefin*agefin;;
1.319     brouard  4832:     }
1.332     brouard  4833:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  4834:       if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  4835:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  4836:       }else{
1.332     brouard  4837:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  4838:       }
1.332     brouard  4839:     }/* End of loop on model equation */
                   4840: 
                   4841: /* Old code */ 
                   4842: 
                   4843:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   4844:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   4845:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   4846:     /*   /\* 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)); *\/ */
                   4847:     /* } */
                   4848:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   4849:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   4850:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   4851:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   4852:     /* /\* } *\/ */
                   4853:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   4854:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   4855:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   4856:     /*   /\* 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]); *\/ */
                   4857:     /* } */
                   4858:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   4859:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   4860:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   4861:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   4862:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   4863:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   4864:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   4865:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   4866:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   4867:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   4868:     /*   } */
                   4869:     /*   /\* 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]); *\/ */
                   4870:     /* } */
                   4871:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   4872:     /*   /\* 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]); *\/ */
                   4873:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   4874:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   4875:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   4876:     /*         }else{ */
                   4877:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   4878:     /*         } */
                   4879:     /*   }else{ */
                   4880:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   4881:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   4882:     /*         }else{ */
                   4883:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   4884:     /*         } */
                   4885:     /*   } */
                   4886:     /* } */
1.217     brouard  4887:     
                   4888:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   4889:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   4890:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   4891:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4892:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  4893:                /* ij should be linked to the correct index of cov */
                   4894:                /* age and covariate values ij are in 'cov', but we need to pass
                   4895:                 * ij for the observed prevalence at age and status and covariate
                   4896:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   4897:                 */
                   4898:     /* 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 *\/ */
                   4899:     /* 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 *\/ */
                   4900:     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  4901:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  4902:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   4903:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   4904:     /*         printf("%d newm= ",i); */
                   4905:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   4906:     /*           printf("%f ",newm[i][j]); */
                   4907:     /*         } */
                   4908:     /*         printf("oldm * "); */
                   4909:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   4910:     /*           printf("%f ",oldm[i][j]); */
                   4911:     /*         } */
1.268     brouard  4912:     /*         printf(" bmmij "); */
1.266     brouard  4913:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   4914:     /*           printf("%f ",pmmij[i][j]); */
                   4915:     /*         } */
                   4916:     /*         printf("\n"); */
                   4917:     /*   } */
                   4918:     /* } */
1.217     brouard  4919:     savm=oldm;
                   4920:     oldm=newm;
1.266     brouard  4921: 
1.217     brouard  4922:     for(j=1; j<=nlstate; j++){
                   4923:       max[j]=0.;
                   4924:       min[j]=1.;
                   4925:     }
                   4926:     for(j=1; j<=nlstate; j++){ 
                   4927:       for(i=1;i<=nlstate;i++){
1.234     brouard  4928:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   4929:        bprlim[i][j]= newm[i][j];
                   4930:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   4931:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  4932:       }
                   4933:     }
1.218     brouard  4934:                
1.217     brouard  4935:     maxmax=0.;
                   4936:     for(i=1; i<=nlstate; i++){
1.318     brouard  4937:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  4938:       maxmax=FMAX(maxmax,meandiff[i]);
                   4939:       /* 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  4940:     } /* i loop */
1.217     brouard  4941:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  4942:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  4943:     if(maxmax < ftolpl){
1.220     brouard  4944:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  4945:       free_vector(min,1,nlstate);
                   4946:       free_vector(max,1,nlstate);
                   4947:       free_vector(meandiff,1,nlstate);
                   4948:       return bprlim;
                   4949:     }
1.288     brouard  4950:   } /* agefin loop */
1.217     brouard  4951:     /* After some age loop it doesn't converge */
1.288     brouard  4952:   if(!first){
1.247     brouard  4953:     first=1;
                   4954:     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\
                   4955: 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);
                   4956:   }
                   4957:   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  4958: 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);
                   4959:   /* 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); */
                   4960:   free_vector(min,1,nlstate);
                   4961:   free_vector(max,1,nlstate);
                   4962:   free_vector(meandiff,1,nlstate);
                   4963:   
                   4964:   return bprlim; /* should not reach here */
                   4965: }
                   4966: 
1.126     brouard  4967: /*************** transition probabilities ***************/ 
                   4968: 
                   4969: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   4970: {
1.138     brouard  4971:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  4972:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  4973:      model to the ncovmodel covariates (including constant and age).
                   4974:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   4975:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   4976:      ncth covariate in the global vector x is given by the formula:
                   4977:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   4978:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   4979:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   4980:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  4981:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  4982:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  4983:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  4984:   */
                   4985:   double s1, lnpijopii;
1.126     brouard  4986:   /*double t34;*/
1.164     brouard  4987:   int i,j, nc, ii, jj;
1.126     brouard  4988: 
1.223     brouard  4989:   for(i=1; i<= nlstate; i++){
                   4990:     for(j=1; j<i;j++){
                   4991:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   4992:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   4993:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   4994:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   4995:       }
                   4996:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  4997:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  4998:     }
                   4999:     for(j=i+1; j<=nlstate+ndeath;j++){
                   5000:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   5001:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   5002:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   5003:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   5004:       }
                   5005:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  5006:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  5007:     }
                   5008:   }
1.218     brouard  5009:   
1.223     brouard  5010:   for(i=1; i<= nlstate; i++){
                   5011:     s1=0;
                   5012:     for(j=1; j<i; j++){
1.339     brouard  5013:       /* printf("debug1 %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:     for(j=i+1; j<=nlstate+ndeath; j++){
1.339     brouard  5017:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  5018:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   5019:     }
                   5020:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   5021:     ps[i][i]=1./(s1+1.);
                   5022:     /* Computing other pijs */
                   5023:     for(j=1; j<i; j++)
1.325     brouard  5024:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  5025:     for(j=i+1; j<=nlstate+ndeath; j++)
                   5026:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   5027:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   5028:   } /* end i */
1.218     brouard  5029:   
1.223     brouard  5030:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   5031:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   5032:       ps[ii][jj]=0;
                   5033:       ps[ii][ii]=1;
                   5034:     }
                   5035:   }
1.294     brouard  5036: 
                   5037: 
1.223     brouard  5038:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   5039:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   5040:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   5041:   /*   } */
                   5042:   /*   printf("\n "); */
                   5043:   /* } */
                   5044:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   5045:   /*
                   5046:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  5047:                goto end;*/
1.266     brouard  5048:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  5049: }
                   5050: 
1.218     brouard  5051: /*************** backward transition probabilities ***************/ 
                   5052: 
                   5053:  /* 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 ) */
                   5054: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   5055:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   5056: {
1.302     brouard  5057:   /* 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  5058:    * 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  5059:    */
1.359     brouard  5060:   int ii, j;
1.222     brouard  5061:   
1.359     brouard  5062:   double  **pmij();
1.222     brouard  5063:   double sumnew=0.;
1.218     brouard  5064:   double agefin;
1.292     brouard  5065:   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  5066:   double **dnewm, **dsavm, **doldm;
                   5067:   double **bbmij;
                   5068:   
1.218     brouard  5069:   doldm=ddoldms; /* global pointers */
1.222     brouard  5070:   dnewm=ddnewms;
                   5071:   dsavm=ddsavms;
1.318     brouard  5072: 
                   5073:   /* Debug */
                   5074:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  5075:   agefin=cov[2];
1.268     brouard  5076:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  5077:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  5078:      the observed prevalence (with this covariate ij) at beginning of transition */
                   5079:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  5080: 
                   5081:   /* P_x */
1.325     brouard  5082:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  5083:   /* outputs pmmij which is a stochastic matrix in row */
                   5084: 
                   5085:   /* Diag(w_x) */
1.292     brouard  5086:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  5087:   sumnew=0.;
1.269     brouard  5088:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  5089:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  5090:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  5091:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   5092:   }
                   5093:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   5094:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   5095:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  5096:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  5097:     }
                   5098:   }else{
                   5099:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   5100:       for (j=1;j<=nlstate+ndeath;j++)
                   5101:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   5102:     }
                   5103:     /* if(sumnew <0.9){ */
                   5104:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   5105:     /* } */
                   5106:   }
                   5107:   k3=0.0;  /* We put the last diagonal to 0 */
                   5108:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   5109:       doldm[ii][ii]= k3;
                   5110:   }
                   5111:   /* End doldm, At the end doldm is diag[(w_i)] */
                   5112:   
1.292     brouard  5113:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   5114:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  5115: 
1.292     brouard  5116:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  5117:   /* 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  5118:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  5119:     sumnew=0.;
1.222     brouard  5120:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  5121:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  5122:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  5123:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  5124:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  5125:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  5126:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  5127:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  5128:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  5129:        /* }else */
1.268     brouard  5130:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   5131:     } /*End ii */
                   5132:   } /* 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 */
                   5133: 
1.292     brouard  5134:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  5135:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  5136:   /* end bmij */
1.266     brouard  5137:   return ps; /*pointer is unchanged */
1.218     brouard  5138: }
1.217     brouard  5139: /*************** transition probabilities ***************/ 
                   5140: 
1.218     brouard  5141: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  5142: {
                   5143:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   5144:      computes the probability to be observed in state j being in state i by appying the
                   5145:      model to the ncovmodel covariates (including constant and age).
                   5146:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   5147:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   5148:      ncth covariate in the global vector x is given by the formula:
                   5149:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   5150:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   5151:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   5152:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   5153:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   5154:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   5155:   */
                   5156:   double s1, lnpijopii;
                   5157:   /*double t34;*/
                   5158:   int i,j, nc, ii, jj;
                   5159: 
1.234     brouard  5160:   for(i=1; i<= nlstate; i++){
                   5161:     for(j=1; j<i;j++){
                   5162:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   5163:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   5164:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   5165:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   5166:       }
                   5167:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   5168:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   5169:     }
                   5170:     for(j=i+1; j<=nlstate+ndeath;j++){
                   5171:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   5172:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   5173:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   5174:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   5175:       }
                   5176:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   5177:     }
                   5178:   }
                   5179:   
                   5180:   for(i=1; i<= nlstate; i++){
                   5181:     s1=0;
                   5182:     for(j=1; j<i; j++){
                   5183:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   5184:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   5185:     }
                   5186:     for(j=i+1; j<=nlstate+ndeath; j++){
                   5187:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   5188:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   5189:     }
                   5190:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   5191:     ps[i][i]=1./(s1+1.);
                   5192:     /* Computing other pijs */
                   5193:     for(j=1; j<i; j++)
                   5194:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   5195:     for(j=i+1; j<=nlstate+ndeath; j++)
                   5196:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   5197:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   5198:   } /* end i */
                   5199:   
                   5200:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   5201:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   5202:       ps[ii][jj]=0;
                   5203:       ps[ii][ii]=1;
                   5204:     }
                   5205:   }
1.296     brouard  5206:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  5207:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   5208:     s1=0.;
                   5209:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   5210:       s1+=ps[ii][jj];
                   5211:     }
                   5212:     for(ii=1; ii<= nlstate; ii++){
                   5213:       ps[ii][jj]=ps[ii][jj]/s1;
                   5214:     }
                   5215:   }
                   5216:   /* Transposition */
                   5217:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   5218:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   5219:       s1=ps[ii][jj];
                   5220:       ps[ii][jj]=ps[jj][ii];
                   5221:       ps[jj][ii]=s1;
                   5222:     }
                   5223:   }
                   5224:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   5225:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   5226:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   5227:   /*   } */
                   5228:   /*   printf("\n "); */
                   5229:   /* } */
                   5230:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   5231:   /*
                   5232:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   5233:     goto end;*/
                   5234:   return ps;
1.217     brouard  5235: }
                   5236: 
                   5237: 
1.126     brouard  5238: /**************** Product of 2 matrices ******************/
                   5239: 
1.145     brouard  5240: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  5241: {
                   5242:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   5243:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   5244:   /* in, b, out are matrice of pointers which should have been initialized 
                   5245:      before: only the contents of out is modified. The function returns
                   5246:      a pointer to pointers identical to out */
1.145     brouard  5247:   int i, j, k;
1.126     brouard  5248:   for(i=nrl; i<= nrh; i++)
1.145     brouard  5249:     for(k=ncolol; k<=ncoloh; k++){
                   5250:       out[i][k]=0.;
                   5251:       for(j=ncl; j<=nch; j++)
                   5252:        out[i][k] +=in[i][j]*b[j][k];
                   5253:     }
1.126     brouard  5254:   return out;
                   5255: }
                   5256: 
                   5257: 
                   5258: /************* Higher Matrix Product ***************/
                   5259: 
1.235     brouard  5260: 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  5261: {
1.336     brouard  5262:   /* Already optimized with precov.
                   5263:      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  5264:      'nhstepm*hstepm*stepm' months (i.e. until
                   5265:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   5266:      nhstepm*hstepm matrices. 
                   5267:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   5268:      (typically every 2 years instead of every month which is too big 
                   5269:      for the memory).
                   5270:      Model is determined by parameters x and covariates have to be 
                   5271:      included manually here. 
                   5272: 
                   5273:      */
                   5274: 
1.359     brouard  5275:   int i, j, d, h, k1;
1.131     brouard  5276:   double **out, cov[NCOVMAX+1];
1.126     brouard  5277:   double **newm;
1.187     brouard  5278:   double agexact;
1.359     brouard  5279:   /*double agebegin, ageend;*/
1.126     brouard  5280: 
                   5281:   /* Hstepm could be zero and should return the unit matrix */
                   5282:   for (i=1;i<=nlstate+ndeath;i++)
                   5283:     for (j=1;j<=nlstate+ndeath;j++){
                   5284:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   5285:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   5286:     }
                   5287:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   5288:   for(h=1; h <=nhstepm; h++){
                   5289:     for(d=1; d <=hstepm; d++){
                   5290:       newm=savm;
                   5291:       /* Covariates have to be included here again */
                   5292:       cov[1]=1.;
1.214     brouard  5293:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  5294:       cov[2]=agexact;
1.319     brouard  5295:       if(nagesqr==1){
1.227     brouard  5296:        cov[3]= agexact*agexact;
1.319     brouard  5297:       }
1.330     brouard  5298:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   5299:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   5300:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  5301:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  5302:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   5303:        }else{
                   5304:          cov[2+nagesqr+k1]=precov[nres][k1];
                   5305:        }
                   5306:       }/* End of loop on model equation */
                   5307:        /* Old code */ 
                   5308: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   5309: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   5310: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   5311: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   5312: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   5313: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   5314: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   5315: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   5316: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   5317: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   5318: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   5319: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   5320: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   5321: /*       /\* 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]])); *\/ */
                   5322: /*       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); */
                   5323: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   5324: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   5325: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   5326: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   5327: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   5328: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   5329: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   5330: /*       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]]); */
                   5331: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   5332: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   5333: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   5334: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   5335: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   5336: /*       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]); */
                   5337: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   5338: 
                   5339: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   5340: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   5341: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   5342: /*       /\* *\/ */
1.330     brouard  5343: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   5344: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   5345: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  5346: /* /\*cptcovage=2                   1               2      *\/ */
                   5347: /* /\*Tage[k]=                      5               8      *\/  */
                   5348: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   5349: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   5350: /*       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]]); */
                   5351: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   5352: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   5353: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   5354: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   5355: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   5356: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   5357: /*       /\*   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); *\/ */
                   5358: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   5359: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   5360: /*       /\* } *\/ */
                   5361: /*       /\* 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]); *\/ */
                   5362: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   5363: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   5364: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   5365: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   5366: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   5367: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   5368: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   5369: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   5370: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  5371:          
1.332     brouard  5372: /*       /\* 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])]); *\/ */
                   5373: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   5374: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   5375: /*       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]]); */
                   5376: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   5377: 
                   5378: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   5379: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   5380: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   5381: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   5382: /*           /\* 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]])]; *\/ */
                   5383: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   5384: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   5385: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   5386: /*       /\*   } *\/ */
                   5387: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   5388: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   5389: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   5390: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   5391: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   5392: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   5393: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   5394: /*       /\*   } *\/ */
                   5395: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   5396: /*     }/\*end of products *\/ */
                   5397:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  5398:       /* for (k=1; k<=cptcovn;k++)  */
                   5399:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   5400:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   5401:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   5402:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   5403:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  5404:       
                   5405:       
1.126     brouard  5406:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   5407:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  5408:       /* right multiplication of oldm by the current matrix */
1.126     brouard  5409:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   5410:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  5411:       /* if((int)age == 70){ */
                   5412:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   5413:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   5414:       /*         printf("%d pmmij ",i); */
                   5415:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   5416:       /*           printf("%f ",pmmij[i][j]); */
                   5417:       /*         } */
                   5418:       /*         printf(" oldm "); */
                   5419:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   5420:       /*           printf("%f ",oldm[i][j]); */
                   5421:       /*         } */
                   5422:       /*         printf("\n"); */
                   5423:       /*       } */
                   5424:       /* } */
1.126     brouard  5425:       savm=oldm;
                   5426:       oldm=newm;
                   5427:     }
                   5428:     for(i=1; i<=nlstate+ndeath; i++)
                   5429:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  5430:        po[i][j][h]=newm[i][j];
                   5431:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  5432:       }
1.128     brouard  5433:     /*printf("h=%d ",h);*/
1.126     brouard  5434:   } /* end h */
1.267     brouard  5435:   /*     printf("\n H=%d \n",h); */
1.126     brouard  5436:   return po;
                   5437: }
                   5438: 
1.217     brouard  5439: /************* Higher Back Matrix Product ***************/
1.218     brouard  5440: /* 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  5441: 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  5442: {
1.332     brouard  5443:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   5444:      computes the transition matrix starting at age 'age' over
1.217     brouard  5445:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  5446:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   5447:      nhstepm*hstepm matrices.
                   5448:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   5449:      (typically every 2 years instead of every month which is too big
1.217     brouard  5450:      for the memory).
1.218     brouard  5451:      Model is determined by parameters x and covariates have to be
1.266     brouard  5452:      included manually here. Then we use a call to bmij(x and cov)
                   5453:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  5454:   */
1.217     brouard  5455: 
1.359     brouard  5456:   int i, j, d, h, k1;
1.266     brouard  5457:   double **out, cov[NCOVMAX+1], **bmij();
                   5458:   double **newm, ***newmm;
1.217     brouard  5459:   double agexact;
1.359     brouard  5460:   /*double agebegin, ageend;*/
1.222     brouard  5461:   double **oldm, **savm;
1.217     brouard  5462: 
1.266     brouard  5463:   newmm=po; /* To be saved */
                   5464:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  5465:   /* Hstepm could be zero and should return the unit matrix */
                   5466:   for (i=1;i<=nlstate+ndeath;i++)
                   5467:     for (j=1;j<=nlstate+ndeath;j++){
                   5468:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   5469:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   5470:     }
                   5471:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   5472:   for(h=1; h <=nhstepm; h++){
                   5473:     for(d=1; d <=hstepm; d++){
                   5474:       newm=savm;
                   5475:       /* Covariates have to be included here again */
                   5476:       cov[1]=1.;
1.271     brouard  5477:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  5478:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  5479:         /* Debug */
                   5480:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  5481:       cov[2]=agexact;
1.332     brouard  5482:       if(nagesqr==1){
1.222     brouard  5483:        cov[3]= agexact*agexact;
1.332     brouard  5484:       }
                   5485:       /** New code */
                   5486:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  5487:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  5488:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  5489:        }else{
1.332     brouard  5490:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  5491:        }
1.332     brouard  5492:       }/* End of loop on model equation */
                   5493:       /** End of new code */
                   5494:   /** This was old code */
                   5495:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   5496:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   5497:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   5498:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   5499:       /*   /\* 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)); *\/ */
                   5500:       /* } */
                   5501:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   5502:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   5503:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   5504:       /*       /\* 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]); *\/ */
                   5505:       /* } */
                   5506:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   5507:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   5508:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   5509:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   5510:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   5511:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   5512:       /*       } */
                   5513:       /*       /\* 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]); *\/ */
                   5514:       /* } */
                   5515:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   5516:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   5517:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   5518:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   5519:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   5520:       /*         }else{ */
                   5521:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   5522:       /*         } */
                   5523:       /*       }else{ */
                   5524:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   5525:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   5526:       /*         }else{ */
                   5527:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   5528:       /*         } */
                   5529:       /*       } */
                   5530:       /* }                      */
                   5531:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   5532:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   5533: /** End of old code */
                   5534:       
1.218     brouard  5535:       /* Careful transposed matrix */
1.266     brouard  5536:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  5537:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  5538:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  5539:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  5540:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  5541:       /* if((int)age == 70){ */
                   5542:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   5543:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   5544:       /*         printf("%d pmmij ",i); */
                   5545:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   5546:       /*           printf("%f ",pmmij[i][j]); */
                   5547:       /*         } */
                   5548:       /*         printf(" oldm "); */
                   5549:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   5550:       /*           printf("%f ",oldm[i][j]); */
                   5551:       /*         } */
                   5552:       /*         printf("\n"); */
                   5553:       /*       } */
                   5554:       /* } */
                   5555:       savm=oldm;
                   5556:       oldm=newm;
                   5557:     }
                   5558:     for(i=1; i<=nlstate+ndeath; i++)
                   5559:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  5560:        po[i][j][h]=newm[i][j];
1.268     brouard  5561:        /* if(h==nhstepm) */
                   5562:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  5563:       }
1.268     brouard  5564:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  5565:   } /* end h */
1.268     brouard  5566:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  5567:   return po;
                   5568: }
                   5569: 
                   5570: 
1.162     brouard  5571: #ifdef NLOPT
                   5572:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   5573:   double fret;
                   5574:   double *xt;
                   5575:   int j;
                   5576:   myfunc_data *d2 = (myfunc_data *) pd;
                   5577: /* xt = (p1-1); */
                   5578:   xt=vector(1,n); 
                   5579:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   5580: 
                   5581:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   5582:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   5583:   printf("Function = %.12lf ",fret);
                   5584:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   5585:   printf("\n");
                   5586:  free_vector(xt,1,n);
                   5587:   return fret;
                   5588: }
                   5589: #endif
1.126     brouard  5590: 
                   5591: /*************** log-likelihood *************/
                   5592: double func( double *x)
                   5593: {
1.336     brouard  5594:   int i, ii, j, k, mi, d, kk, kf=0;
1.226     brouard  5595:   int ioffset=0;
1.339     brouard  5596:   int ipos=0,iposold=0,ncovv=0;
                   5597: 
1.340     brouard  5598:   double cotvarv, cotvarvold;
1.226     brouard  5599:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   5600:   double **out;
                   5601:   double lli; /* Individual log likelihood */
                   5602:   int s1, s2;
1.228     brouard  5603:   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  5604: 
1.226     brouard  5605:   double bbh, survp;
                   5606:   double agexact;
1.336     brouard  5607:   double agebegin, ageend;
1.226     brouard  5608:   /*extern weight */
                   5609:   /* We are differentiating ll according to initial status */
                   5610:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   5611:   /*for(i=1;i<imx;i++) 
                   5612:     printf(" %d\n",s[4][i]);
                   5613:   */
1.162     brouard  5614: 
1.226     brouard  5615:   ++countcallfunc;
1.162     brouard  5616: 
1.226     brouard  5617:   cov[1]=1.;
1.126     brouard  5618: 
1.226     brouard  5619:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  5620:   ioffset=0;
1.226     brouard  5621:   if(mle==1){
                   5622:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   5623:       /* Computes the values of the ncovmodel covariates of the model
                   5624:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   5625:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   5626:         to be observed in j being in i according to the model.
                   5627:       */
1.243     brouard  5628:       ioffset=2+nagesqr ;
1.233     brouard  5629:    /* Fixed */
1.345     brouard  5630:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummy or quant or prod */
1.319     brouard  5631:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   5632:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   5633:        /*  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  5634:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.336     brouard  5635:        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  5636:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  5637:       }
1.226     brouard  5638:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  5639:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  5640:         has been calculated etc */
                   5641:       /* For an individual i, wav[i] gives the number of effective waves */
                   5642:       /* We compute the contribution to Likelihood of each effective transition
                   5643:         mw[mi][i] is real wave of the mi th effectve wave */
                   5644:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   5645:         s2=s[mw[mi+1][i]][i];
1.341     brouard  5646:         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  5647:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   5648:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   5649:       */
1.336     brouard  5650:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   5651:       /* Wave varying (but not age varying) */
1.339     brouard  5652:        /* 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*\/ */
                   5653:        /*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
                   5654:        /*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   5655:        /* } */
1.340     brouard  5656:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
                   5657:          itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   5658:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  5659:          if(FixedV[itv]!=0){ /* Not a fixed covariate */
1.341     brouard  5660:            cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* cotvar[wav][ncovcol+nqv+iv][i] */
1.340     brouard  5661:          }else{ /* fixed covariate */
1.345     brouard  5662:            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  5663:          }
1.339     brouard  5664:          if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  5665:            cotvarvold=cotvarv;
                   5666:          }else{ /* A second product */
                   5667:            cotvarv=cotvarv*cotvarvold;
1.339     brouard  5668:          }
                   5669:          iposold=ipos;
1.340     brouard  5670:          cov[ioffset+ipos]=cotvarv;
1.234     brouard  5671:        }
1.339     brouard  5672:        /* for products of time varying to be done */
1.234     brouard  5673:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5674:          for (j=1;j<=nlstate+ndeath;j++){
                   5675:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5676:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5677:          }
1.336     brouard  5678: 
                   5679:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   5680:        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  5681:        for(d=0; d<dh[mi][i]; d++){
                   5682:          newm=savm;
                   5683:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5684:          cov[2]=agexact;
                   5685:          if(nagesqr==1)
                   5686:            cov[3]= agexact*agexact;  /* Should be changed here */
1.349     brouard  5687:          /* for (kk=1; kk<=cptcovage;kk++) { */
                   5688:          /*   if(!FixedV[Tvar[Tage[kk]]]) */
                   5689:          /*     cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /\* Tage[kk] gives the data-covariate associated with age *\/ */
                   5690:          /*   else */
                   5691:          /*     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) *\/  */
                   5692:          /* } */
                   5693:          for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   5694:            itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   5695:            ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   5696:            if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   5697:              cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   5698:            }else{ /* fixed covariate */
                   5699:              cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   5700:            }
                   5701:            if(ipos!=iposold){ /* Not a product or first of a product */
                   5702:              cotvarvold=cotvarv;
                   5703:            }else{ /* A second product */
                   5704:              cotvarv=cotvarv*cotvarvold;
                   5705:            }
                   5706:            iposold=ipos;
                   5707:            cov[ioffset+ipos]=cotvarv*agexact;
                   5708:            /* For products */
1.234     brouard  5709:          }
1.349     brouard  5710:          
1.234     brouard  5711:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5712:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5713:          savm=oldm;
                   5714:          oldm=newm;
                   5715:        } /* end mult */
                   5716:        
                   5717:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   5718:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   5719:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   5720:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   5721:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   5722:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   5723:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   5724:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  5725:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   5726:                                 * -stepm/2 to stepm/2 .
                   5727:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   5728:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   5729:                                 */
1.234     brouard  5730:        s1=s[mw[mi][i]][i];
                   5731:        s2=s[mw[mi+1][i]][i];
                   5732:        bbh=(double)bh[mi][i]/(double)stepm; 
                   5733:        /* bias bh is positive if real duration
                   5734:         * is higher than the multiple of stepm and negative otherwise.
                   5735:         */
                   5736:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   5737:        if( s2 > nlstate){ 
                   5738:          /* i.e. if s2 is a death state and if the date of death is known 
                   5739:             then the contribution to the likelihood is the probability to 
                   5740:             die between last step unit time and current  step unit time, 
                   5741:             which is also equal to probability to die before dh 
                   5742:             minus probability to die before dh-stepm . 
                   5743:             In version up to 0.92 likelihood was computed
                   5744:             as if date of death was unknown. Death was treated as any other
                   5745:             health state: the date of the interview describes the actual state
                   5746:             and not the date of a change in health state. The former idea was
                   5747:             to consider that at each interview the state was recorded
                   5748:             (healthy, disable or death) and IMaCh was corrected; but when we
                   5749:             introduced the exact date of death then we should have modified
                   5750:             the contribution of an exact death to the likelihood. This new
                   5751:             contribution is smaller and very dependent of the step unit
                   5752:             stepm. It is no more the probability to die between last interview
                   5753:             and month of death but the probability to survive from last
                   5754:             interview up to one month before death multiplied by the
                   5755:             probability to die within a month. Thanks to Chris
                   5756:             Jackson for correcting this bug.  Former versions increased
                   5757:             mortality artificially. The bad side is that we add another loop
                   5758:             which slows down the processing. The difference can be up to 10%
                   5759:             lower mortality.
                   5760:          */
                   5761:          /* If, at the beginning of the maximization mostly, the
                   5762:             cumulative probability or probability to be dead is
                   5763:             constant (ie = 1) over time d, the difference is equal to
                   5764:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   5765:             s1 at precedent wave, to be dead a month before current
                   5766:             wave is equal to probability, being at state s1 at
                   5767:             precedent wave, to be dead at mont of the current
                   5768:             wave. Then the observed probability (that this person died)
                   5769:             is null according to current estimated parameter. In fact,
                   5770:             it should be very low but not zero otherwise the log go to
                   5771:             infinity.
                   5772:          */
1.183     brouard  5773: /* #ifdef INFINITYORIGINAL */
                   5774: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   5775: /* #else */
                   5776: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   5777: /*         lli=log(mytinydouble); */
                   5778: /*       else */
                   5779: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   5780: /* #endif */
1.226     brouard  5781:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  5782:          
1.226     brouard  5783:        } else if  ( s2==-1 ) { /* alive */
                   5784:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   5785:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   5786:          /*survp += out[s1][j]; */
                   5787:          lli= log(survp);
                   5788:        }
1.336     brouard  5789:        /* else if  (s2==-4) {  */
                   5790:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
                   5791:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   5792:        /*   lli= log(survp);  */
                   5793:        /* }  */
                   5794:        /* else if  (s2==-5) {  */
                   5795:        /*   for (j=1,survp=0. ; j<=2; j++)   */
                   5796:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   5797:        /*   lli= log(survp);  */
                   5798:        /* }  */
1.226     brouard  5799:        else{
                   5800:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   5801:          /*  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 */
                   5802:        } 
                   5803:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   5804:        /*if(lli ==000.0)*/
1.340     brouard  5805:        /* 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  5806:        ipmx +=1;
                   5807:        sw += weight[i];
                   5808:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   5809:        /* if (lli < log(mytinydouble)){ */
                   5810:        /*   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); */
                   5811:        /*   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]); */
                   5812:        /* } */
                   5813:       } /* end of wave */
                   5814:     } /* end of individual */
                   5815:   }  else if(mle==2){
                   5816:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  5817:       ioffset=2+nagesqr ;
                   5818:       for (k=1; k<=ncovf;k++)
                   5819:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  5820:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  5821:        for(k=1; k <= ncovv ; k++){
1.341     brouard  5822:          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  5823:        }
1.226     brouard  5824:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5825:          for (j=1;j<=nlstate+ndeath;j++){
                   5826:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5827:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5828:          }
                   5829:        for(d=0; d<=dh[mi][i]; d++){
                   5830:          newm=savm;
                   5831:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5832:          cov[2]=agexact;
                   5833:          if(nagesqr==1)
                   5834:            cov[3]= agexact*agexact;
                   5835:          for (kk=1; kk<=cptcovage;kk++) {
                   5836:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   5837:          }
                   5838:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5839:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5840:          savm=oldm;
                   5841:          oldm=newm;
                   5842:        } /* end mult */
                   5843:       
                   5844:        s1=s[mw[mi][i]][i];
                   5845:        s2=s[mw[mi+1][i]][i];
                   5846:        bbh=(double)bh[mi][i]/(double)stepm; 
                   5847:        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 */
                   5848:        ipmx +=1;
                   5849:        sw += weight[i];
                   5850:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   5851:       } /* end of wave */
                   5852:     } /* end of individual */
                   5853:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   5854:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   5855:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   5856:       for(mi=1; mi<= wav[i]-1; mi++){
                   5857:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5858:          for (j=1;j<=nlstate+ndeath;j++){
                   5859:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5860:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5861:          }
                   5862:        for(d=0; d<dh[mi][i]; d++){
                   5863:          newm=savm;
                   5864:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5865:          cov[2]=agexact;
                   5866:          if(nagesqr==1)
                   5867:            cov[3]= agexact*agexact;
                   5868:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  5869:            if(!FixedV[Tvar[Tage[kk]]])
                   5870:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   5871:            else
1.341     brouard  5872:              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  5873:          }
                   5874:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5875:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5876:          savm=oldm;
                   5877:          oldm=newm;
                   5878:        } /* end mult */
                   5879:       
                   5880:        s1=s[mw[mi][i]][i];
                   5881:        s2=s[mw[mi+1][i]][i];
                   5882:        bbh=(double)bh[mi][i]/(double)stepm; 
                   5883:        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 */
                   5884:        ipmx +=1;
                   5885:        sw += weight[i];
                   5886:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   5887:       } /* end of wave */
                   5888:     } /* end of individual */
                   5889:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   5890:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   5891:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   5892:       for(mi=1; mi<= wav[i]-1; mi++){
                   5893:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5894:          for (j=1;j<=nlstate+ndeath;j++){
                   5895:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5896:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5897:          }
                   5898:        for(d=0; d<dh[mi][i]; d++){
                   5899:          newm=savm;
                   5900:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5901:          cov[2]=agexact;
                   5902:          if(nagesqr==1)
                   5903:            cov[3]= agexact*agexact;
                   5904:          for (kk=1; kk<=cptcovage;kk++) {
                   5905:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   5906:          }
1.126     brouard  5907:        
1.226     brouard  5908:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5909:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5910:          savm=oldm;
                   5911:          oldm=newm;
                   5912:        } /* end mult */
                   5913:       
                   5914:        s1=s[mw[mi][i]][i];
                   5915:        s2=s[mw[mi+1][i]][i];
                   5916:        if( s2 > nlstate){ 
                   5917:          lli=log(out[s1][s2] - savm[s1][s2]);
                   5918:        } else if  ( s2==-1 ) { /* alive */
                   5919:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   5920:            survp += out[s1][j];
                   5921:          lli= log(survp);
                   5922:        }else{
                   5923:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   5924:        }
                   5925:        ipmx +=1;
                   5926:        sw += weight[i];
                   5927:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.343     brouard  5928:        /* 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  5929:       } /* end of wave */
                   5930:     } /* end of individual */
                   5931:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   5932:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   5933:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   5934:       for(mi=1; mi<= wav[i]-1; mi++){
                   5935:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5936:          for (j=1;j<=nlstate+ndeath;j++){
                   5937:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5938:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5939:          }
                   5940:        for(d=0; d<dh[mi][i]; d++){
                   5941:          newm=savm;
                   5942:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5943:          cov[2]=agexact;
                   5944:          if(nagesqr==1)
                   5945:            cov[3]= agexact*agexact;
                   5946:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  5947:            if(!FixedV[Tvar[Tage[kk]]])
                   5948:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   5949:            else
1.341     brouard  5950:              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  5951:          }
1.126     brouard  5952:        
1.226     brouard  5953:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5954:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5955:          savm=oldm;
                   5956:          oldm=newm;
                   5957:        } /* end mult */
                   5958:       
                   5959:        s1=s[mw[mi][i]][i];
                   5960:        s2=s[mw[mi+1][i]][i];
                   5961:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   5962:        ipmx +=1;
                   5963:        sw += weight[i];
                   5964:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   5965:        /*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]);*/
                   5966:       } /* end of wave */
                   5967:     } /* end of individual */
                   5968:   } /* End of if */
                   5969:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   5970:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   5971:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   5972:   return -l;
1.126     brouard  5973: }
                   5974: 
                   5975: /*************** log-likelihood *************/
                   5976: double funcone( double *x)
                   5977: {
1.228     brouard  5978:   /* Same as func but slower because of a lot of printf and if */
1.359     brouard  5979:   int i, ii, j, k, mi, d, kv=0, kf=0;
1.228     brouard  5980:   int ioffset=0;
1.339     brouard  5981:   int ipos=0,iposold=0,ncovv=0;
                   5982: 
1.340     brouard  5983:   double cotvarv, cotvarvold;
1.131     brouard  5984:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  5985:   double **out;
                   5986:   double lli; /* Individual log likelihood */
                   5987:   double llt;
                   5988:   int s1, s2;
1.228     brouard  5989:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   5990: 
1.126     brouard  5991:   double bbh, survp;
1.187     brouard  5992:   double agexact;
1.214     brouard  5993:   double agebegin, ageend;
1.126     brouard  5994:   /*extern weight */
                   5995:   /* We are differentiating ll according to initial status */
                   5996:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   5997:   /*for(i=1;i<imx;i++) 
                   5998:     printf(" %d\n",s[4][i]);
                   5999:   */
                   6000:   cov[1]=1.;
                   6001: 
                   6002:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  6003:   ioffset=0;
                   6004:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.336     brouard  6005:     /* Computes the values of the ncovmodel covariates of the model
                   6006:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   6007:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   6008:        to be observed in j being in i according to the model.
                   6009:     */
1.243     brouard  6010:     /* ioffset=2+nagesqr+cptcovage; */
                   6011:     ioffset=2+nagesqr;
1.232     brouard  6012:     /* Fixed */
1.224     brouard  6013:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  6014:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.349     brouard  6015:     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  6016:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
                   6017:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
                   6018:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
1.335     brouard  6019:       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  6020: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   6021: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   6022: /*    cov[2+6]=covar[2][i]; V2  */
                   6023: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   6024: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   6025: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   6026: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   6027: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   6028: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  6029:     }
1.336     brouard  6030:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   6031:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   6032:         has been calculated etc */
                   6033:       /* For an individual i, wav[i] gives the number of effective waves */
                   6034:       /* We compute the contribution to Likelihood of each effective transition
                   6035:         mw[mi][i] is real wave of the mi th effectve wave */
                   6036:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   6037:         s2=s[mw[mi+1][i]][i];
1.341     brouard  6038:         And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][ncovcol+nqv+iv][i]
1.336     brouard  6039:       */
                   6040:     /* This part may be useless now because everythin should be in covar */
1.232     brouard  6041:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   6042:     /*   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?)*\/ */
                   6043:     /* } */
1.231     brouard  6044:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   6045:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   6046:     /* } */
1.225     brouard  6047:     
1.233     brouard  6048: 
                   6049:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.339     brouard  6050:       /* 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 */
                   6051:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
                   6052:       /*       /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
                   6053:       /*       cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   6054:       /* } */
                   6055:       
                   6056:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   6057:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   6058:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   6059:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
                   6060:       /* We need the position of the time varying or product in the model */
                   6061:       /* 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 */            
                   6062:       /* TvarVV gives the variable name */
1.340     brouard  6063:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   6064:       *      k=         1   2     3     4         5        6        7       8        9
                   6065:       *  varying            1     2                                 3       4        5
                   6066:       *  ncovv              1     2                                3 4     5 6      7 8
1.343     brouard  6067:       * TvarVV[ncovv]      V3     5                                1 3     3 5      1 5
1.340     brouard  6068:       * TvarVVind           2     3                                7 7     8 8      9 9
                   6069:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
                   6070:       */
1.345     brouard  6071:       /* Other model ncovcol=5 nqv=0 ntv=3 nqtv=0 nlstate=3
1.349     brouard  6072:        * 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  6073:        * FixedV[ncovcol+qv+ntv+nqtv]       V5
1.349     brouard  6074:        * 3           V1  V2     V3    V4   V5 V6     V7  V8 V3*V2 V7*V2  V6*V3 V7*V3 V6*V4 V7*V4
                   6075:        *             0   0      0      0    0  1      1   1  0, 0, 1,1,   1, 0, 1, 0, 1, 0, 1, 0}
                   6076:        * 3           0   0      0      0    0  1      1   1  0,     1      1    1      1    1}
                   6077:        * model=          V2  +  V3  +  V4  +  V6  +  V7  +  V6*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   6078:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   6079:         *                +age*V6*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   6080:        * model2=          V2  +  V3  +  V4  +  V6  +  V7  +  V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   6081:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   6082:         *                +age*V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   6083:        * model3=          V2  +  V3  +  V4  +  V6  +  V7  + age*V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   6084:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   6085:         *                +V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   6086:        * kmodel           1     2      3      4      5        6         7         8         9        10        11    
                   6087:        *                  12       13      14      15       16
                   6088:        *                    17        18         19        20         21
                   6089:        * Tvar[kmodel]     2     3      4      6      7        9        10        11        12        13        14
                   6090:        *                   2       3        4       6        7
                   6091:        *                     9         11          12        13         14            
                   6092:        * cptcovage=5+5 total of covariates with age 
                   6093:        * Tage[cptcovage] age*V2=12      13      14      15       16
                   6094:        *1                   17            18         19        20         21 gives the position in model of covariates associated with age
                   6095:        *3 Tage[cptcovage] age*V3*V2=6  
                   6096:        *3                age*V2=12         13      14      15       16
                   6097:        *3                age*V6*V3=18      19    20   21
                   6098:        * Tvar[Tage[cptcovage]]    Tvar[12]=2      3      4       6         Tvar[16]=7(age*V7)
                   6099:        *     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
                   6100:        * 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
                   6101:        * 3 Tvar[Tage[cptcovage]]    Tvar[6]=9      Tvar[12]=2      3     4       6         Tvar[16]=7(age*V7)
                   6102:        * 3     Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
                   6103:        * 3 Tage[cptcovage] age*V3*V2=6   age*V2=12 age*V3 13    14      15       16
                   6104:        *                    age*V6*V3=18         19        20         21 gives the position in model of covariates associated with age
                   6105:        * 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
                   6106:        * Tvar=                {2, 3, 4, 6, 7,
                   6107:        *                       9, 10, 11, 12, 13, 14,
                   6108:        *              Tvar[12]=2, 3, 4, 6, 7,
                   6109:        *              Tvar[17]=9, 11, 12, 13, 14}
                   6110:        * Typevar[1]@21 = {0, 0, 0, 0, 0,
                   6111:        *                  2, 2, 2, 2, 2, 2,
                   6112:        * 3                3, 2, 2, 2, 2, 2,
                   6113:        *                  1, 1, 1, 1, 1, 
                   6114:        *                  3, 3, 3, 3, 3}
                   6115:        * 3                 2, 3, 3, 3, 3}
                   6116:        * 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
                   6117:        * p Tprod[1]@21 {6, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   6118:        * 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}
                   6119:        * 3 Tprod[1]@21 {17, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   6120:        * cptcovprod=11 (6+5)
                   6121:        * FixedV[Tvar[Tage[cptcovage]]]]  FixedV[2]=0      FixedV[3]=0      0      1          (age*V7)Tvar[16]=1 FixedV[absolute] not [kmodel]
                   6122:        *   FixedV[Tvar[17]=FixedV[age*V6*V2]=FixedV[9]=1        1         1          1         1  
                   6123:        * 3 FixedV[Tvar[17]=FixedV[age*V3*V2]=FixedV[9]=0        [11]=1         1          1         1  
                   6124:        * FixedV[]          V1=0     V2=0   V3=0  v4=0    V5=0  V6=1    V7=1 v8=1  OK then model dependent
                   6125:        *                   9=1  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   6126:        * 3                 9=0  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   6127:        * cptcovdageprod=5  for gnuplot printing
                   6128:        * cptcovprodvage=6 
                   6129:        * ncova=15           1        2       3       4       5
                   6130:        *                      6 7        8 9      10 11        12 13     14 15
                   6131:        * TvarA              2        3       4       6       7
                   6132:        *                      6 2        6 7       7 3          6 4       7 4
                   6133:        * TvaAind             12 12      13 13     14 14      15 15       16 16        
1.345     brouard  6134:        * ncovf            1     2      3
1.349     brouard  6135:        *                                    V6       V7      V6*V2     V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   6136:        * ncovvt=14                            1      2        3 4       5 6       7 8       9 10     11 12     13 14     
                   6137:        * TvarVV[1]@14 = itv               {V6=6,     7, V6*V2=6, 2,     7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   6138:        * TvarVVind[1]@14=                    {4,     5,       6, 6,     7, 7,     8, 8,      9, 9,   10, 10,   11, 11}
                   6139:        * 3 ncovvt=12                        V6       V7      V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   6140:        * 3 TvarVV[1]@12 = itv                {6,     7, V7*V2=7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   6141:        * 3                                    1      2        3  4      5  6      7  8      9 10     11 12
                   6142:        * TvarVVind[1]@12=         {V6 is in k=4,     5,  7,(4isV2)=7,   8, 8,      9, 9,   10,10,    11,11}TvarVVind[12]=k=11
                   6143:        * TvarV              6, 7, 9, 10, 11, 12, 13, 14
                   6144:        * 3 cptcovprodvage=6
                   6145:        * 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
                   6146:        * 3 TvarAVVA[1]@15= itva 3 2    2      3    4        6       7        6 3         7 3         6 4         7 4 
                   6147:        * 3 ncovta             1 2      3      4    5        6       7        8 9       10 11       12 13        14 15
1.354     brouard  6148:        *?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  6149:        * TvarAVVAind[1]@15= V3 is in k=6 6 12  13   14      15      16       18 18       19,19,     20,20        21,21}TvarVVAind[]
                   6150:        * 3 ncovvta=10     +age*V6 + age*V7 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   6151:        * 3 we want to compute =cotvar[mw[mi][i]][TvarVVA[ncovva]][i] at position TvarVVAind[ncovva]
                   6152:        * 3 TvarVVA[1]@10= itva   6       7        6 3         7 3         6 4         7 4 
                   6153:        * 3 ncovva                1       2        3 4         5 6         7 8         9 10
                   6154:        * TvarVVAind[1]@10= V6 is in k=4  5        8,8         9, 9,      10,10        11 11}TvarVVAind[]
                   6155:        * TvarVVAind[1]@10=       15       16     18,18        19,19,      20,20        21 21}TvarVVAind[]
                   6156:        * TvarVA              V3*V2=6 6 , 1, 2, 11, 12, 13, 14
1.345     brouard  6157:        * TvarFind[1]@14= {1,    2,     3,     0 <repeats 12 times>}
1.349     brouard  6158:        * Tvar[1]@21=     {2,    3,     4,    6,      7,      9,      10,        11,       12,      13,       14,
                   6159:        *                   2, 3, 4, 6, 7,
                   6160:        *                     6, 8, 9, 10, 11}
1.345     brouard  6161:        * TvarFind[itv]                        0      0       0
                   6162:        * FixedV[itv]                          1      1       1  0      1 0       1 0       1 0       0
1.354     brouard  6163:        *? FixedV[itv]                          1      1       1  0      1 0       1 0       1 0      1 0     1 0
1.345     brouard  6164:        * Tvar[TvarFind[ncovf]]=[1]=2 [2]=3 [4]=4
                   6165:        * Tvar[TvarFind[itv]]                [0]=?      ?ncovv 1 à ncovvt]
                   6166:        *   Not a fixed cotvar[mw][itv][i]     6       7      6  2      7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
1.349     brouard  6167:        *   fixed covar[itv]                  [6]     [7]    [6][2] 
1.345     brouard  6168:        */
                   6169: 
1.349     brouard  6170:       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 */
                   6171:        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  6172:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  6173:        /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   6174:        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  6175:          /* printf("DEBUG ncovv=%d, Varying TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
1.345     brouard  6176:          cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
1.354     brouard  6177:          /* printf("DEBUG Varying cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
1.340     brouard  6178:        }else{ /* fixed covariate */
1.345     brouard  6179:          /* 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  6180:          /* printf("DEBUG ncovv=%d, Fixed TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
1.349     brouard  6181:          cotvarv=covar[itv][i];  /* Good: In V6*V3, 3 is fixed at position of the data */
1.354     brouard  6182:          /* printf("DEBUG Fixed cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
1.340     brouard  6183:        }
1.339     brouard  6184:        if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  6185:          cotvarvold=cotvarv;
                   6186:        }else{ /* A second product */
                   6187:          cotvarv=cotvarv*cotvarvold;
1.339     brouard  6188:        }
                   6189:        iposold=ipos;
1.340     brouard  6190:        cov[ioffset+ipos]=cotvarv;
1.354     brouard  6191:        /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
1.339     brouard  6192:        /* For products */
                   6193:       }
                   6194:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
                   6195:       /*       iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
                   6196:       /*       /\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
                   6197:       /*       /\*           1  2   3      4      5                         *\/ */
                   6198:       /*       /\*itv           1                                           *\/ */
                   6199:       /*       /\* TvarVInd[1]= 2                                           *\/ */
                   6200:       /*       /\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
                   6201:       /*       /\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
                   6202:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
                   6203:       /*       /\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
                   6204:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
                   6205:       /*       cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
                   6206:       /*       /\* 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]); *\/ */
                   6207:       /* } */
1.232     brouard  6208:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  6209:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   6210:       /*       /\* 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]); *\/ */
                   6211:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  6212:       /* } */
1.126     brouard  6213:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  6214:        for (j=1;j<=nlstate+ndeath;j++){
                   6215:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   6216:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   6217:        }
1.214     brouard  6218:       
                   6219:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   6220:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   6221:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  6222:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  6223:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   6224:          and mw[mi+1][i]. dh depends on stepm.*/
                   6225:        newm=savm;
1.247     brouard  6226:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  6227:        cov[2]=agexact;
                   6228:        if(nagesqr==1)
                   6229:          cov[3]= agexact*agexact;
1.349     brouard  6230:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   6231:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   6232:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   6233:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   6234:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   6235:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   6236:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   6237:          }else{ /* fixed covariate */
                   6238:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   6239:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   6240:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   6241:          }
                   6242:          if(ipos!=iposold){ /* Not a product or first of a product */
                   6243:            cotvarvold=cotvarv;
                   6244:          }else{ /* A second product */
                   6245:            /* printf("DEBUG * \n"); */
                   6246:            cotvarv=cotvarv*cotvarvold;
                   6247:          }
                   6248:          iposold=ipos;
                   6249:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   6250:          cov[ioffset+ipos]=cotvarv*agexact;
                   6251:          /* For products */
1.242     brouard  6252:        }
1.349     brouard  6253: 
1.242     brouard  6254:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   6255:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   6256:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   6257:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   6258:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   6259:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   6260:        savm=oldm;
                   6261:        oldm=newm;
1.126     brouard  6262:       } /* end mult */
1.336     brouard  6263:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   6264:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   6265:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   6266:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   6267:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   6268:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   6269:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   6270:         * probability in order to take into account the bias as a fraction of the way
                   6271:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   6272:                                 * -stepm/2 to stepm/2 .
                   6273:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   6274:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   6275:                                 */
1.126     brouard  6276:       s1=s[mw[mi][i]][i];
                   6277:       s2=s[mw[mi+1][i]][i];
1.217     brouard  6278:       /* if(s2==-1){ */
1.268     brouard  6279:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  6280:       /*       /\* exit(1); *\/ */
                   6281:       /* } */
1.126     brouard  6282:       bbh=(double)bh[mi][i]/(double)stepm; 
                   6283:       /* bias is positive if real duration
                   6284:        * is higher than the multiple of stepm and negative otherwise.
                   6285:        */
                   6286:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  6287:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  6288:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  6289:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   6290:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   6291:        lli= log(survp);
1.126     brouard  6292:       }else if (mle==1){
1.242     brouard  6293:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  6294:       } else if(mle==2){
1.242     brouard  6295:        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  6296:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  6297:        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  6298:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  6299:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  6300:       } else{  /* mle=0 back to 1 */
1.242     brouard  6301:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   6302:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  6303:       } /* End of if */
                   6304:       ipmx +=1;
                   6305:       sw += weight[i];
                   6306:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.342     brouard  6307:       /* Printing covariates values for each contribution for checking */
1.343     brouard  6308:       /* 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  6309:       if(globpr){
1.246     brouard  6310:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  6311:  %11.6f %11.6f %11.6f ", \
1.242     brouard  6312:                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  6313:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.343     brouard  6314:        /*      printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
                   6315:        /* %11.6f %11.6f %11.6f ", \ */
                   6316:        /*              num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   6317:        /*              2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  6318:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   6319:          llt +=ll[k]*gipmx/gsw;
                   6320:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335     brouard  6321:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  6322:        }
1.343     brouard  6323:        fprintf(ficresilk," %10.6f ", -llt);
1.335     brouard  6324:        /* printf(" %10.6f\n", -llt); */
1.342     brouard  6325:        /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
1.343     brouard  6326:        /* fprintf(ficresilk,"%09ld ", num[i]); */ /* not necessary */
                   6327:        for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
                   6328:          fprintf(ficresilk," %g",covar[Tvar[TvarFind[kf]]][i]);
                   6329:        }
                   6330:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
                   6331:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   6332:          if(ipos!=iposold){ /* Not a product or first of a product */
                   6333:            fprintf(ficresilk," %g",cov[ioffset+ipos]);
                   6334:            /* printf(" %g",cov[ioffset+ipos]); */
                   6335:          }else{
                   6336:            fprintf(ficresilk,"*");
                   6337:            /* printf("*"); */
1.342     brouard  6338:          }
1.343     brouard  6339:          iposold=ipos;
                   6340:        }
1.349     brouard  6341:        /* for (kk=1; kk<=cptcovage;kk++) { */
                   6342:        /*   if(!FixedV[Tvar[Tage[kk]]]){ */
                   6343:        /*     fprintf(ficresilk," %g*age",covar[Tvar[Tage[kk]]][i]); */
                   6344:        /*     /\* printf(" %g*age",covar[Tvar[Tage[kk]]][i]); *\/ */
                   6345:        /*   }else{ */
                   6346:        /*     fprintf(ficresilk," %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   6347:        /*     /\* printf(" %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\\/  *\/ */
                   6348:        /*   } */
                   6349:        /* } */
                   6350:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   6351:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   6352:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   6353:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   6354:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   6355:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   6356:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   6357:          }else{ /* fixed covariate */
                   6358:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   6359:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   6360:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   6361:          }
                   6362:          if(ipos!=iposold){ /* Not a product or first of a product */
                   6363:            cotvarvold=cotvarv;
                   6364:          }else{ /* A second product */
                   6365:            /* printf("DEBUG * \n"); */
                   6366:            cotvarv=cotvarv*cotvarvold;
1.342     brouard  6367:          }
1.349     brouard  6368:          cotvarv=cotvarv*agexact;
                   6369:          fprintf(ficresilk," %g*age",cotvarv);
                   6370:          iposold=ipos;
                   6371:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   6372:          cov[ioffset+ipos]=cotvarv;
                   6373:          /* For products */
1.343     brouard  6374:        }
                   6375:        /* printf("\n"); */
1.342     brouard  6376:        /* } /\*  End debugILK *\/ */
                   6377:        fprintf(ficresilk,"\n");
                   6378:       } /* End if globpr */
1.335     brouard  6379:     } /* end of wave */
                   6380:   } /* end of individual */
                   6381:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  6382: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335     brouard  6383:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   6384:   if(globpr==0){ /* First time we count the contributions and weights */
                   6385:     gipmx=ipmx;
                   6386:     gsw=sw;
                   6387:   }
1.343     brouard  6388:   return -l;
1.126     brouard  6389: }
                   6390: 
                   6391: 
                   6392: /*************** function likelione ***********/
1.292     brouard  6393: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  6394: {
                   6395:   /* This routine should help understanding what is done with 
                   6396:      the selection of individuals/waves and
                   6397:      to check the exact contribution to the likelihood.
                   6398:      Plotting could be done.
1.342     brouard  6399:   */
                   6400:   void pstamp(FILE *ficres);
1.343     brouard  6401:   int k, kf, kk, kvar, ncovv, iposold, ipos;
1.126     brouard  6402: 
                   6403:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  6404:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  6405:     strcat(fileresilk,fileresu);
1.126     brouard  6406:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   6407:       printf("Problem with resultfile: %s\n", fileresilk);
                   6408:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   6409:     }
1.342     brouard  6410:     pstamp(ficresilk);fprintf(ficresilk,"# model=1+age+%s\n",model);
1.214     brouard  6411:     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");
                   6412:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  6413:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   6414:     for(k=1; k<=nlstate; k++) 
                   6415:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
1.342     brouard  6416:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total) ");
                   6417: 
                   6418:     /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
                   6419:       for(kf=1;kf <= ncovf; kf++){
                   6420:        fprintf(ficresilk,"V%d",Tvar[TvarFind[kf]]);
                   6421:        /* printf("V%d",Tvar[TvarFind[kf]]); */
                   6422:       }
                   6423:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){
1.343     brouard  6424:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
1.342     brouard  6425:        if(ipos!=iposold){ /* Not a product or first of a product */
                   6426:          /* printf(" %d",ipos); */
                   6427:          fprintf(ficresilk," V%d",TvarVV[ncovv]);
                   6428:        }else{
                   6429:          /* printf("*"); */
                   6430:          fprintf(ficresilk,"*");
1.343     brouard  6431:        }
1.342     brouard  6432:        iposold=ipos;
                   6433:       }
                   6434:       for (kk=1; kk<=cptcovage;kk++) {
                   6435:        if(!FixedV[Tvar[Tage[kk]]]){
                   6436:          /* printf(" %d*age(Fixed)",Tvar[Tage[kk]]); */
                   6437:          fprintf(ficresilk," %d*age(Fixed)",Tvar[Tage[kk]]);
                   6438:        }else{
                   6439:          fprintf(ficresilk," %d*age(Varying)",Tvar[Tage[kk]]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   6440:          /* printf(" %d*age(Varying)",Tvar[Tage[kk]]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   6441:        }
                   6442:       }
                   6443:     /* } /\* End if debugILK *\/ */
                   6444:     /* printf("\n"); */
                   6445:     fprintf(ficresilk,"\n");
                   6446:   } /* End glogpri */
1.126     brouard  6447: 
1.292     brouard  6448:   *fretone=(*func)(p);
1.126     brouard  6449:   if(*globpri !=0){
                   6450:     fclose(ficresilk);
1.205     brouard  6451:     if (mle ==0)
                   6452:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   6453:     else if(mle >=1)
                   6454:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   6455:     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  6456:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  6457:       
1.207     brouard  6458:     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  6459: <img src=\"%s-ori.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  6460:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.343     brouard  6461: <img src=\"%s-dest.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
                   6462:     
                   6463:     for (k=1; k<= nlstate ; k++) {
                   6464:       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 \
                   6465: <img src=\"%s-p%dj.png\">\n",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   6466:       for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.350     brouard  6467:         kvar=Tvar[TvarFind[kf]];  /* variable */
                   6468:         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]]);
                   6469:         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);
                   6470:         fprintf(fichtm,"<img src=\"%s-p%dj-%d.png\">",subdirf2(optionfilefiname,"ILK_"),k,Tvar[TvarFind[kf]]);
1.343     brouard  6471:       }
                   6472:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Loop on the time varying extended covariates (with extension of Vn*Vm */
                   6473:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   6474:        kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   6475:        /* 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]); */
                   6476:        if(ipos!=iposold){ /* Not a product or first of a product */
                   6477:          /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   6478:          /* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); */
                   6479:          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)  */
                   6480:            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> \
                   6481: <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);
                   6482:          } /* End only for dummies time varying (single?) */
                   6483:        }else{ /* Useless product */
                   6484:          /* printf("*"); */
                   6485:          /* fprintf(ficresilk,"*"); */ 
                   6486:        }
                   6487:        iposold=ipos;
                   6488:       } /* For each time varying covariate */
                   6489:     } /* End loop on states */
                   6490: 
                   6491: /*     if(debugILK){ */
                   6492: /*       for(kf=1; kf <= ncovf; kf++){ /\* For each simple dummy covariate of the model *\/ */
                   6493: /*     /\* kvar=Tvar[TvarFind[kf]]; *\/ /\* variable *\/ */
                   6494: /*     for (k=1; k<= nlstate ; k++) { */
                   6495: /*       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> \ */
                   6496: /* <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]]); */
                   6497: /*     } */
                   6498: /*       } */
                   6499: /*       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /\* Loop on the time varying extended covariates (with extension of Vn*Vm *\/ */
                   6500: /*     ipos=TvarVVind[ncovv]; /\* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate *\/ */
                   6501: /*     kvar=TvarVV[ncovv]; /\*  TvarVV={3, 1, 3} gives the name of each varying covariate *\/ */
                   6502: /*     /\* 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]); *\/ */
                   6503: /*     if(ipos!=iposold){ /\* Not a product or first of a product *\/ */
                   6504: /*       /\* fprintf(ficresilk," V%d",TvarVV[ncovv]); *\/ */
                   6505: /*       /\* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); *\/ */
                   6506: /*       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)  *\/ */
                   6507: /*         for (k=1; k<= nlstate ; k++) { */
                   6508: /*           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> \ */
                   6509: /* <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar); */
                   6510: /*         } /\* End state *\/ */
                   6511: /*       } /\* End only for dummies time varying (single?) *\/ */
                   6512: /*     }else{ /\* Useless product *\/ */
                   6513: /*       /\* printf("*"); *\/ */
                   6514: /*       /\* fprintf(ficresilk,"*"); *\/  */
                   6515: /*     } */
                   6516: /*     iposold=ipos; */
                   6517: /*       } /\* For each time varying covariate *\/ */
                   6518: /*     }/\* End debugILK *\/ */
1.207     brouard  6519:     fflush(fichtm);
1.343     brouard  6520:   }/* End globpri */
1.126     brouard  6521:   return;
                   6522: }
                   6523: 
                   6524: 
                   6525: /*********** Maximum Likelihood Estimation ***************/
                   6526: 
                   6527: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   6528: {
1.359     brouard  6529:   int i,j,  jkk=0, iter=0;
1.126     brouard  6530:   double **xi;
1.359     brouard  6531:   /*double fret;*/
                   6532:   /*double fretone;*/ /* Only one call to likelihood */
1.126     brouard  6533:   /*  char filerespow[FILENAMELENGTH];*/
1.354     brouard  6534:   
1.359     brouard  6535:   /*double * p1;*/ /* Shifted parameters from 0 instead of 1 */
1.162     brouard  6536: #ifdef NLOPT
                   6537:   int creturn;
                   6538:   nlopt_opt opt;
                   6539:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   6540:   double *lb;
                   6541:   double minf; /* the minimum objective value, upon return */
1.354     brouard  6542: 
1.162     brouard  6543:   myfunc_data dinst, *d = &dinst;
                   6544: #endif
                   6545: 
                   6546: 
1.126     brouard  6547:   xi=matrix(1,npar,1,npar);
1.357     brouard  6548:   for (i=1;i<=npar;i++)  /* Starting with canonical directions j=1,n xi[i=1,n][j] */
1.126     brouard  6549:     for (j=1;j<=npar;j++)
                   6550:       xi[i][j]=(i==j ? 1.0 : 0.0);
1.359     brouard  6551:   printf("Powell-prax\n");  fprintf(ficlog,"Powell-prax\n");
1.201     brouard  6552:   strcpy(filerespow,"POW_"); 
1.126     brouard  6553:   strcat(filerespow,fileres);
                   6554:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   6555:     printf("Problem with resultfile: %s\n", filerespow);
                   6556:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   6557:   }
                   6558:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   6559:   for (i=1;i<=nlstate;i++)
                   6560:     for(j=1;j<=nlstate+ndeath;j++)
                   6561:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   6562:   fprintf(ficrespow,"\n");
1.162     brouard  6563: #ifdef POWELL
1.319     brouard  6564: #ifdef LINMINORIGINAL
                   6565: #else /* LINMINORIGINAL */
                   6566:   
                   6567:   flatdir=ivector(1,npar); 
                   6568:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   6569: #endif /*LINMINORIGINAL */
                   6570: 
                   6571: #ifdef FLATSUP
                   6572:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   6573:   /* reorganizing p by suppressing flat directions */
                   6574:   for(i=1, jk=1; i <=nlstate; i++){
                   6575:     for(k=1; k <=(nlstate+ndeath); k++){
                   6576:       if (k != i) {
                   6577:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   6578:         if(flatdir[jk]==1){
                   6579:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   6580:         }
                   6581:         for(j=1; j <=ncovmodel; j++){
                   6582:           printf("%12.7f ",p[jk]);
                   6583:           jk++; 
                   6584:         }
                   6585:         printf("\n");
                   6586:       }
                   6587:     }
                   6588:   }
                   6589: /* skipping */
                   6590:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   6591:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   6592:     for(k=1; k <=(nlstate+ndeath); k++){
                   6593:       if (k != i) {
                   6594:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   6595:         if(flatdir[jk]==1){
                   6596:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   6597:           for(j=1; j <=ncovmodel;  jk++,j++){
                   6598:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   6599:             /*q[jjk]=p[jk];*/
                   6600:           }
                   6601:         }else{
                   6602:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   6603:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   6604:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   6605:             /*q[jjk]=p[jk];*/
                   6606:           }
                   6607:         }
                   6608:         printf("\n");
                   6609:       }
                   6610:       fflush(stdout);
                   6611:     }
                   6612:   }
                   6613:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   6614: #else  /* FLATSUP */
1.359     brouard  6615: /*  powell(p,xi,npar,ftol,&iter,&fret,func);*/
                   6616: /*   praxis ( t0, h0, n, prin, x, beale_f ); */
1.364   ! brouard  6617:  int prin=4;
1.362     brouard  6618:   /* double h0=0.25; */
                   6619:   /* double macheps; */
                   6620:   /* double fmin; */
1.359     brouard  6621:   macheps=pow(16.0,-13.0);
                   6622: /* #include "praxis.h" */
                   6623:   /* Be careful that praxis start at x[0] and powell start at p[1] */
                   6624:    /* praxis ( ftol, h0, npar, prin, p, func ); */
                   6625: /* p1= (p+1); */ /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   6626: printf("Praxis Gegenfurtner \n");
                   6627: fprintf(ficlog, "Praxis  Gegenfurtner\n");fflush(ficlog);
                   6628: /* praxis ( ftol, h0, npar, prin, p1, func ); */
                   6629:   /* fmin = praxis(1.e-5,macheps, h, n, prin, x, func); */
1.362     brouard  6630:   ffmin = praxis(ftol,macheps, h0, npar, prin, p, func);
1.359     brouard  6631: printf("End Praxis\n");
1.319     brouard  6632: #endif  /* FLATSUP */
                   6633: 
                   6634: #ifdef LINMINORIGINAL
                   6635: #else
                   6636:       free_ivector(flatdir,1,npar); 
                   6637: #endif  /* LINMINORIGINAL*/
                   6638: #endif /* POWELL */
1.126     brouard  6639: 
1.162     brouard  6640: #ifdef NLOPT
                   6641: #ifdef NEWUOA
                   6642:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   6643: #else
                   6644:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   6645: #endif
                   6646:   lb=vector(0,npar-1);
                   6647:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   6648:   nlopt_set_lower_bounds(opt, lb);
                   6649:   nlopt_set_initial_step1(opt, 0.1);
                   6650:   
                   6651:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   6652:   d->function = func;
                   6653:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   6654:   nlopt_set_min_objective(opt, myfunc, d);
                   6655:   nlopt_set_xtol_rel(opt, ftol);
                   6656:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   6657:     printf("nlopt failed! %d\n",creturn); 
                   6658:   }
                   6659:   else {
                   6660:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   6661:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   6662:     iter=1; /* not equal */
                   6663:   }
                   6664:   nlopt_destroy(opt);
                   6665: #endif
1.319     brouard  6666: #ifdef FLATSUP
                   6667:   /* npared = npar -flatd/ncovmodel; */
                   6668:   /* xired= matrix(1,npared,1,npared); */
                   6669:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   6670:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   6671:   /* free_matrix(xire,1,npared,1,npared); */
                   6672: #else  /* FLATSUP */
                   6673: #endif /* FLATSUP */
1.126     brouard  6674:   free_matrix(xi,1,npar,1,npar);
                   6675:   fclose(ficrespow);
1.203     brouard  6676:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   6677:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  6678:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  6679: 
                   6680: }
                   6681: 
                   6682: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  6683: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  6684: {
                   6685:   double  **a,**y,*x,pd;
1.203     brouard  6686:   /* double **hess; */
1.164     brouard  6687:   int i, j;
1.126     brouard  6688:   int *indx;
                   6689: 
                   6690:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  6691:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  6692:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   6693:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   6694:   double gompertz(double p[]);
1.203     brouard  6695:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  6696: 
                   6697:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   6698:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   6699:   for (i=1;i<=npar;i++){
1.203     brouard  6700:     printf("%d-",i);fflush(stdout);
                   6701:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  6702:    
                   6703:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   6704:     
                   6705:     /*  printf(" %f ",p[i]);
                   6706:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   6707:   }
                   6708:   
                   6709:   for (i=1;i<=npar;i++) {
                   6710:     for (j=1;j<=npar;j++)  {
                   6711:       if (j>i) { 
1.203     brouard  6712:        printf(".%d-%d",i,j);fflush(stdout);
                   6713:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   6714:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  6715:        
                   6716:        hess[j][i]=hess[i][j];    
                   6717:        /*printf(" %lf ",hess[i][j]);*/
                   6718:       }
                   6719:     }
                   6720:   }
                   6721:   printf("\n");
                   6722:   fprintf(ficlog,"\n");
                   6723: 
                   6724:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   6725:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   6726:   
                   6727:   a=matrix(1,npar,1,npar);
                   6728:   y=matrix(1,npar,1,npar);
                   6729:   x=vector(1,npar);
                   6730:   indx=ivector(1,npar);
                   6731:   for (i=1;i<=npar;i++)
                   6732:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   6733:   ludcmp(a,npar,indx,&pd);
                   6734: 
                   6735:   for (j=1;j<=npar;j++) {
                   6736:     for (i=1;i<=npar;i++) x[i]=0;
                   6737:     x[j]=1;
                   6738:     lubksb(a,npar,indx,x);
                   6739:     for (i=1;i<=npar;i++){ 
                   6740:       matcov[i][j]=x[i];
                   6741:     }
                   6742:   }
                   6743: 
                   6744:   printf("\n#Hessian matrix#\n");
                   6745:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   6746:   for (i=1;i<=npar;i++) { 
                   6747:     for (j=1;j<=npar;j++) { 
1.203     brouard  6748:       printf("%.6e ",hess[i][j]);
                   6749:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  6750:     }
                   6751:     printf("\n");
                   6752:     fprintf(ficlog,"\n");
                   6753:   }
                   6754: 
1.203     brouard  6755:   /* printf("\n#Covariance matrix#\n"); */
                   6756:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   6757:   /* for (i=1;i<=npar;i++) {  */
                   6758:   /*   for (j=1;j<=npar;j++) {  */
                   6759:   /*     printf("%.6e ",matcov[i][j]); */
                   6760:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   6761:   /*   } */
                   6762:   /*   printf("\n"); */
                   6763:   /*   fprintf(ficlog,"\n"); */
                   6764:   /* } */
                   6765: 
1.126     brouard  6766:   /* Recompute Inverse */
1.203     brouard  6767:   /* for (i=1;i<=npar;i++) */
                   6768:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   6769:   /* ludcmp(a,npar,indx,&pd); */
                   6770: 
                   6771:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   6772: 
                   6773:   /* for (j=1;j<=npar;j++) { */
                   6774:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   6775:   /*   x[j]=1; */
                   6776:   /*   lubksb(a,npar,indx,x); */
                   6777:   /*   for (i=1;i<=npar;i++){  */
                   6778:   /*     y[i][j]=x[i]; */
                   6779:   /*     printf("%.3e ",y[i][j]); */
                   6780:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   6781:   /*   } */
                   6782:   /*   printf("\n"); */
                   6783:   /*   fprintf(ficlog,"\n"); */
                   6784:   /* } */
                   6785: 
                   6786:   /* Verifying the inverse matrix */
                   6787: #ifdef DEBUGHESS
                   6788:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  6789: 
1.203     brouard  6790:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   6791:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  6792: 
                   6793:   for (j=1;j<=npar;j++) {
                   6794:     for (i=1;i<=npar;i++){ 
1.203     brouard  6795:       printf("%.2f ",y[i][j]);
                   6796:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  6797:     }
                   6798:     printf("\n");
                   6799:     fprintf(ficlog,"\n");
                   6800:   }
1.203     brouard  6801: #endif
1.126     brouard  6802: 
                   6803:   free_matrix(a,1,npar,1,npar);
                   6804:   free_matrix(y,1,npar,1,npar);
                   6805:   free_vector(x,1,npar);
                   6806:   free_ivector(indx,1,npar);
1.203     brouard  6807:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  6808: 
                   6809: 
                   6810: }
                   6811: 
                   6812: /*************** hessian matrix ****************/
                   6813: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  6814: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  6815:   int i;
                   6816:   int l=1, lmax=20;
1.203     brouard  6817:   double k1,k2, res, fx;
1.132     brouard  6818:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  6819:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   6820:   int k=0,kmax=10;
                   6821:   double l1;
                   6822: 
                   6823:   fx=func(x);
                   6824:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  6825:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  6826:     l1=pow(10,l);
                   6827:     delts=delt;
                   6828:     for(k=1 ; k <kmax; k=k+1){
                   6829:       delt = delta*(l1*k);
                   6830:       p2[theta]=x[theta] +delt;
1.145     brouard  6831:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  6832:       p2[theta]=x[theta]-delt;
                   6833:       k2=func(p2)-fx;
                   6834:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  6835:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  6836:       
1.203     brouard  6837: #ifdef DEBUGHESSII
1.126     brouard  6838:       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);
                   6839:       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);
                   6840: #endif
                   6841:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   6842:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   6843:        k=kmax;
                   6844:       }
                   6845:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  6846:        k=kmax; l=lmax*10;
1.126     brouard  6847:       }
                   6848:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   6849:        delts=delt;
                   6850:       }
1.203     brouard  6851:     } /* End loop k */
1.126     brouard  6852:   }
                   6853:   delti[theta]=delts;
                   6854:   return res; 
                   6855:   
                   6856: }
                   6857: 
1.203     brouard  6858: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  6859: {
                   6860:   int i;
1.164     brouard  6861:   int l=1, lmax=20;
1.126     brouard  6862:   double k1,k2,k3,k4,res,fx;
1.132     brouard  6863:   double p2[MAXPARM+1];
1.203     brouard  6864:   int k, kmax=1;
                   6865:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  6866: 
                   6867:   int firstime=0;
1.203     brouard  6868:   
1.126     brouard  6869:   fx=func(x);
1.203     brouard  6870:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  6871:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  6872:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   6873:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  6874:     k1=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:     k2=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:     k3=func(p2)-fx;
                   6883:   
1.203     brouard  6884:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   6885:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  6886:     k4=func(p2)-fx;
1.203     brouard  6887:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   6888:     if(k1*k2*k3*k4 <0.){
1.208     brouard  6889:       firstime=1;
1.203     brouard  6890:       kmax=kmax+10;
1.208     brouard  6891:     }
                   6892:     if(kmax >=10 || firstime ==1){
1.354     brouard  6893:       /* What are the thetai and thetaj? thetai/ncovmodel thetai=(thetai-thetai%ncovmodel)/ncovmodel +thetai%ncovmodel=(line,pos)  */
1.246     brouard  6894:       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);
                   6895:       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  6896:       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);
                   6897:       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);
                   6898:     }
                   6899: #ifdef DEBUGHESSIJ
                   6900:     v1=hess[thetai][thetai];
                   6901:     v2=hess[thetaj][thetaj];
                   6902:     cv12=res;
                   6903:     /* Computing eigen value of Hessian matrix */
                   6904:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6905:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6906:     if ((lc2 <0) || (lc1 <0) ){
                   6907:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   6908:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   6909:       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);
                   6910:       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);
                   6911:     }
1.126     brouard  6912: #endif
                   6913:   }
                   6914:   return res;
                   6915: }
                   6916: 
1.203     brouard  6917:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   6918: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   6919: /* { */
                   6920: /*   int i; */
                   6921: /*   int l=1, lmax=20; */
                   6922: /*   double k1,k2,k3,k4,res,fx; */
                   6923: /*   double p2[MAXPARM+1]; */
                   6924: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   6925: /*   int k=0,kmax=10; */
                   6926: /*   double l1; */
                   6927:   
                   6928: /*   fx=func(x); */
                   6929: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   6930: /*     l1=pow(10,l); */
                   6931: /*     delts=delt; */
                   6932: /*     for(k=1 ; k <kmax; k=k+1){ */
                   6933: /*       delt = delti*(l1*k); */
                   6934: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   6935: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   6936: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   6937: /*       k1=func(p2)-fx; */
                   6938:       
                   6939: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   6940: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   6941: /*       k2=func(p2)-fx; */
                   6942:       
                   6943: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   6944: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   6945: /*       k3=func(p2)-fx; */
                   6946:       
                   6947: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   6948: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   6949: /*       k4=func(p2)-fx; */
                   6950: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   6951: /* #ifdef DEBUGHESSIJ */
                   6952: /*       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); */
                   6953: /*       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); */
                   6954: /* #endif */
                   6955: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   6956: /*     k=kmax; */
                   6957: /*       } */
                   6958: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   6959: /*     k=kmax; l=lmax*10; */
                   6960: /*       } */
                   6961: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   6962: /*     delts=delt; */
                   6963: /*       } */
                   6964: /*     } /\* End loop k *\/ */
                   6965: /*   } */
                   6966: /*   delti[theta]=delts; */
                   6967: /*   return res;  */
                   6968: /* } */
                   6969: 
                   6970: 
1.126     brouard  6971: /************** Inverse of matrix **************/
                   6972: void ludcmp(double **a, int n, int *indx, double *d) 
                   6973: { 
                   6974:   int i,imax,j,k; 
                   6975:   double big,dum,sum,temp; 
                   6976:   double *vv; 
                   6977:  
                   6978:   vv=vector(1,n); 
                   6979:   *d=1.0; 
                   6980:   for (i=1;i<=n;i++) { 
                   6981:     big=0.0; 
                   6982:     for (j=1;j<=n;j++) 
                   6983:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  6984:     if (big == 0.0){
                   6985:       printf(" Singular Hessian matrix at row %d:\n",i);
                   6986:       for (j=1;j<=n;j++) {
                   6987:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   6988:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   6989:       }
                   6990:       fflush(ficlog);
                   6991:       fclose(ficlog);
                   6992:       nrerror("Singular matrix in routine ludcmp"); 
                   6993:     }
1.126     brouard  6994:     vv[i]=1.0/big; 
                   6995:   } 
                   6996:   for (j=1;j<=n;j++) { 
                   6997:     for (i=1;i<j;i++) { 
                   6998:       sum=a[i][j]; 
                   6999:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   7000:       a[i][j]=sum; 
                   7001:     } 
                   7002:     big=0.0; 
                   7003:     for (i=j;i<=n;i++) { 
                   7004:       sum=a[i][j]; 
                   7005:       for (k=1;k<j;k++) 
                   7006:        sum -= a[i][k]*a[k][j]; 
                   7007:       a[i][j]=sum; 
                   7008:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   7009:        big=dum; 
                   7010:        imax=i; 
                   7011:       } 
                   7012:     } 
                   7013:     if (j != imax) { 
                   7014:       for (k=1;k<=n;k++) { 
                   7015:        dum=a[imax][k]; 
                   7016:        a[imax][k]=a[j][k]; 
                   7017:        a[j][k]=dum; 
                   7018:       } 
                   7019:       *d = -(*d); 
                   7020:       vv[imax]=vv[j]; 
                   7021:     } 
                   7022:     indx[j]=imax; 
                   7023:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   7024:     if (j != n) { 
                   7025:       dum=1.0/(a[j][j]); 
                   7026:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   7027:     } 
                   7028:   } 
                   7029:   free_vector(vv,1,n);  /* Doesn't work */
                   7030: ;
                   7031: } 
                   7032: 
                   7033: void lubksb(double **a, int n, int *indx, double b[]) 
                   7034: { 
                   7035:   int i,ii=0,ip,j; 
                   7036:   double sum; 
                   7037:  
                   7038:   for (i=1;i<=n;i++) { 
                   7039:     ip=indx[i]; 
                   7040:     sum=b[ip]; 
                   7041:     b[ip]=b[i]; 
                   7042:     if (ii) 
                   7043:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   7044:     else if (sum) ii=i; 
                   7045:     b[i]=sum; 
                   7046:   } 
                   7047:   for (i=n;i>=1;i--) { 
                   7048:     sum=b[i]; 
                   7049:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   7050:     b[i]=sum/a[i][i]; 
                   7051:   } 
                   7052: } 
                   7053: 
                   7054: void pstamp(FILE *fichier)
                   7055: {
1.196     brouard  7056:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  7057: }
                   7058: 
1.297     brouard  7059: void date2dmy(double date,double *day, double *month, double *year){
                   7060:   double yp=0., yp1=0., yp2=0.;
                   7061:   
                   7062:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   7063:                        fractional in yp1 */
                   7064:   *year=yp;
                   7065:   yp2=modf((yp1*12),&yp);
                   7066:   *month=yp;
                   7067:   yp1=modf((yp2*30.5),&yp);
                   7068:   *day=yp;
                   7069:   if(*day==0) *day=1;
                   7070:   if(*month==0) *month=1;
                   7071: }
                   7072: 
1.253     brouard  7073: 
                   7074: 
1.126     brouard  7075: /************ Frequencies ********************/
1.251     brouard  7076: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  7077:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   7078:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  7079: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  7080:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  7081:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  7082:   int iind=0, iage=0;
                   7083:   int mi; /* Effective wave */
                   7084:   int first;
                   7085:   double ***freq; /* Frequencies */
1.268     brouard  7086:   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 */
                   7087:   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  7088:   double *meanq, *stdq, *idq;
1.226     brouard  7089:   double **meanqt;
                   7090:   double *pp, **prop, *posprop, *pospropt;
                   7091:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   7092:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   7093:   double agebegin, ageend;
                   7094:     
                   7095:   pp=vector(1,nlstate);
1.251     brouard  7096:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  7097:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   7098:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   7099:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   7100:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  7101:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  7102:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  7103:   meanqt=matrix(1,lastpass,1,nqtveff);
                   7104:   strcpy(fileresp,"P_");
                   7105:   strcat(fileresp,fileresu);
                   7106:   /*strcat(fileresphtm,fileresu);*/
                   7107:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   7108:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   7109:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   7110:     exit(0);
                   7111:   }
1.240     brouard  7112:   
1.226     brouard  7113:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   7114:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   7115:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   7116:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   7117:     fflush(ficlog);
                   7118:     exit(70); 
                   7119:   }
                   7120:   else{
                   7121:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  7122: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  7123: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  7124:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   7125:   }
1.319     brouard  7126:   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  7127:   
1.226     brouard  7128:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   7129:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   7130:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   7131:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   7132:     fflush(ficlog);
                   7133:     exit(70); 
1.240     brouard  7134:   } else{
1.226     brouard  7135:     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  7136: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  7137: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  7138:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   7139:   }
1.319     brouard  7140:   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  7141:   
1.253     brouard  7142:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   7143:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  7144:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  7145:   j1=0;
1.126     brouard  7146:   
1.227     brouard  7147:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335     brouard  7148:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  7149:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  7150:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  7151:   
                   7152:   
1.226     brouard  7153:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   7154:      reference=low_education V1=0,V2=0
                   7155:      med_educ                V1=1 V2=0, 
                   7156:      high_educ               V1=0 V2=1
1.330     brouard  7157:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  7158:   */
1.249     brouard  7159:   dateintsum=0;
                   7160:   k2cpt=0;
                   7161: 
1.253     brouard  7162:   if(cptcoveff == 0 )
1.265     brouard  7163:     nl=1;  /* Constant and age model only */
1.253     brouard  7164:   else
                   7165:     nl=2;
1.265     brouard  7166: 
                   7167:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   7168:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335     brouard  7169:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  7170:    *     freq[s1][s2][iage] =0.
                   7171:    *     Loop on iind
                   7172:    *       ++freq[s1][s2][iage] weighted
                   7173:    *     end iind
                   7174:    *     if covariate and j!0
                   7175:    *       headers Variable on one line
                   7176:    *     endif cov j!=0
                   7177:    *     header of frequency table by age
                   7178:    *     Loop on age
                   7179:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   7180:    *       pos+=freq[s1][s2][iage] weighted
                   7181:    *       Loop on s1 initial state
                   7182:    *         fprintf(ficresp
                   7183:    *       end s1
                   7184:    *     end age
                   7185:    *     if j!=0 computes starting values
                   7186:    *     end compute starting values
                   7187:    *   end j1
                   7188:    * end nl 
                   7189:    */
1.253     brouard  7190:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   7191:     if(nj==1)
                   7192:       j=0;  /* First pass for the constant */
1.265     brouard  7193:     else{
1.335     brouard  7194:       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  7195:     }
1.251     brouard  7196:     first=1;
1.332     brouard  7197:     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  7198:       posproptt=0.;
1.330     brouard  7199:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  7200:        scanf("%d", i);*/
                   7201:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  7202:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  7203:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  7204:            freq[i][s2][m]=0;
1.251     brouard  7205:       
                   7206:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  7207:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  7208:          prop[i][m]=0;
                   7209:        posprop[i]=0;
                   7210:        pospropt[i]=0;
                   7211:       }
1.283     brouard  7212:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  7213:         idq[z1]=0.;
                   7214:         meanq[z1]=0.;
                   7215:         stdq[z1]=0.;
1.283     brouard  7216:       }
                   7217:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  7218:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  7219:       /*         meanqt[m][z1]=0.; */
                   7220:       /*       } */
                   7221:       /* }       */
1.251     brouard  7222:       /* dateintsum=0; */
                   7223:       /* k2cpt=0; */
                   7224:       
1.265     brouard  7225:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  7226:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   7227:        bool=1;
                   7228:        if(j !=0){
                   7229:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335     brouard  7230:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   7231:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  7232:                /* if(Tvaraff[z1] ==-20){ */
                   7233:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   7234:                /* }else  if(Tvaraff[z1] ==-10){ */
                   7235:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  7236:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335     brouard  7237:                /* 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); */
                   7238:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
1.338     brouard  7239:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  7240:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  7241:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  7242:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  7243:                  /* 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", */
                   7244:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   7245:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  7246:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   7247:                } /* Onlyf fixed */
                   7248:              } /* end z1 */
1.335     brouard  7249:            } /* cptcoveff > 0 */
1.251     brouard  7250:          } /* end any */
                   7251:        }/* end j==0 */
1.265     brouard  7252:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  7253:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  7254:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  7255:            m=mw[mi][iind];
                   7256:            if(j!=0){
                   7257:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335     brouard  7258:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  7259:                  if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  7260:                    /* iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /\* Good *\/ */
                   7261:                    iv= Tvar[Tmodelind[z1]]; /* Good *//* because cotvar starts now at first at ncovcol+nqv+ntv */ 
1.332     brouard  7262:                    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  7263:                                                                                      value is -1, we don't select. It differs from the 
                   7264:                                                                                      constant and age model which counts them. */
                   7265:                      bool=0; /* not selected */
                   7266:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  7267:                    /* i1=Tvaraff[z1]; */
                   7268:                    /* i2=TnsdVar[i1]; */
                   7269:                    /* i3=nbcode[i1][i2]; */
                   7270:                    /* i4=covar[i1][iind]; */
                   7271:                    /* if(i4 != i3){ */
                   7272:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  7273:                      bool=0;
                   7274:                    }
                   7275:                  }
                   7276:                }
                   7277:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   7278:            } /* end j==0 */
                   7279:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  7280:            if(bool==1){ /*Selected */
1.251     brouard  7281:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   7282:                 and mw[mi+1][iind]. dh depends on stepm. */
                   7283:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   7284:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   7285:              if(m >=firstpass && m <=lastpass){
                   7286:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   7287:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   7288:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   7289:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   7290:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   7291:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   7292:                if (m<lastpass) {
                   7293:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   7294:                  /*   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]); */
                   7295:                  if(s[m][iind]==-1)
                   7296:                    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.));
                   7297:                  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  7298:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   7299:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  7300:                      idq[z1]=idq[z1]+weight[iind];
                   7301:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   7302:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   7303:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  7304:                    }
1.284     brouard  7305:                  }
1.251     brouard  7306:                  /* if((int)agev[m][iind] == 55) */
                   7307:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   7308:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   7309:                  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  7310:                }
1.251     brouard  7311:              } /* end if between passes */  
                   7312:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   7313:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   7314:                k2cpt++;
                   7315:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  7316:              }
1.251     brouard  7317:            }else{
                   7318:              bool=1;
                   7319:            }/* end bool 2 */
                   7320:          } /* end m */
1.284     brouard  7321:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   7322:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   7323:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   7324:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   7325:          /* } */
1.251     brouard  7326:        } /* end bool */
                   7327:       } /* end iind = 1 to imx */
1.319     brouard  7328:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  7329:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   7330:       
                   7331:       
                   7332:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335     brouard  7333:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  7334:         pstamp(ficresp);
1.335     brouard  7335:       if  (cptcoveff>0 && j!=0){
1.265     brouard  7336:         pstamp(ficresp);
1.251     brouard  7337:        printf( "\n#********** Variable "); 
                   7338:        fprintf(ficresp, "\n#********** Variable "); 
                   7339:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   7340:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   7341:        fprintf(ficlog, "\n#********** Variable "); 
1.340     brouard  7342:        for (z1=1; z1<=cptcoveff; z1++){
1.251     brouard  7343:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  7344:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7345:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7346:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7347:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7348:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  7349:          }else{
1.330     brouard  7350:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7351:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7352:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7353:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7354:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  7355:          }
                   7356:        }
                   7357:        printf( "**********\n#");
                   7358:        fprintf(ficresp, "**********\n#");
                   7359:        fprintf(ficresphtm, "**********</h3>\n");
                   7360:        fprintf(ficresphtmfr, "**********</h3>\n");
                   7361:        fprintf(ficlog, "**********\n");
                   7362:       }
1.284     brouard  7363:       /*
                   7364:        Printing means of quantitative variables if any
                   7365:       */
                   7366:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  7367:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  7368:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  7369:        if(weightopt==1){
                   7370:          printf(" Weighted mean and standard deviation of");
                   7371:          fprintf(ficlog," Weighted mean and standard deviation of");
                   7372:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   7373:        }
1.311     brouard  7374:        /* mu = \frac{w x}{\sum w}
                   7375:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   7376:        */
                   7377:        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]));
                   7378:        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]));
                   7379:        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  7380:       }
                   7381:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   7382:       /*       for(m=1;m<=lastpass;m++){ */
                   7383:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   7384:       /*   } */
                   7385:       /* } */
1.283     brouard  7386: 
1.251     brouard  7387:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335     brouard  7388:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  7389:         fprintf(ficresp, " Age");
1.335     brouard  7390:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   7391:          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]]);
                   7392:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7393:        }
1.251     brouard  7394:       for(i=1; i<=nlstate;i++) {
1.335     brouard  7395:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  7396:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   7397:       }
1.335     brouard  7398:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  7399:       fprintf(ficresphtm, "\n");
                   7400:       
                   7401:       /* Header of frequency table by age */
                   7402:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   7403:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  7404:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  7405:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  7406:          if(s2!=0 && m!=0)
                   7407:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  7408:        }
1.226     brouard  7409:       }
1.251     brouard  7410:       fprintf(ficresphtmfr, "\n");
                   7411:     
                   7412:       /* For each age */
                   7413:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   7414:        fprintf(ficresphtm,"<tr>");
                   7415:        if(iage==iagemax+1){
                   7416:          fprintf(ficlog,"1");
                   7417:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   7418:        }else if(iage==iagemax+2){
                   7419:          fprintf(ficlog,"0");
                   7420:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   7421:        }else if(iage==iagemax+3){
                   7422:          fprintf(ficlog,"Total");
                   7423:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   7424:        }else{
1.240     brouard  7425:          if(first==1){
1.251     brouard  7426:            first=0;
                   7427:            printf("See log file for details...\n");
                   7428:          }
                   7429:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   7430:          fprintf(ficlog,"Age %d", iage);
                   7431:        }
1.265     brouard  7432:        for(s1=1; s1 <=nlstate ; s1++){
                   7433:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   7434:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  7435:        }
1.265     brouard  7436:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  7437:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  7438:            pos += freq[s1][m][iage];
                   7439:          if(pp[s1]>=1.e-10){
1.251     brouard  7440:            if(first==1){
1.265     brouard  7441:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  7442:            }
1.265     brouard  7443:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  7444:          }else{
                   7445:            if(first==1)
1.265     brouard  7446:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   7447:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  7448:          }
                   7449:        }
                   7450:       
1.265     brouard  7451:        for(s1=1; s1 <=nlstate ; s1++){ 
                   7452:          /* posprop[s1]=0; */
                   7453:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   7454:            pp[s1] += freq[s1][m][iage];
                   7455:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   7456:       
                   7457:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   7458:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   7459:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   7460:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   7461:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   7462:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   7463:        }
                   7464:        
                   7465:        /* Writing ficresp */
1.335     brouard  7466:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  7467:           if( iage <= iagemax){
                   7468:            fprintf(ficresp," %d",iage);
                   7469:           }
                   7470:         }else if( nj==2){
                   7471:           if( iage <= iagemax){
                   7472:            fprintf(ficresp," %d",iage);
1.335     brouard  7473:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  7474:           }
1.240     brouard  7475:        }
1.265     brouard  7476:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  7477:          if(pos>=1.e-5){
1.251     brouard  7478:            if(first==1)
1.265     brouard  7479:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   7480:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  7481:          }else{
                   7482:            if(first==1)
1.265     brouard  7483:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   7484:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  7485:          }
                   7486:          if( iage <= iagemax){
                   7487:            if(pos>=1.e-5){
1.335     brouard  7488:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  7489:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   7490:               }else if( nj==2){
                   7491:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   7492:               }
                   7493:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   7494:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   7495:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   7496:            } else{
1.335     brouard  7497:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  7498:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  7499:            }
1.240     brouard  7500:          }
1.265     brouard  7501:          pospropt[s1] +=posprop[s1];
                   7502:        } /* end loop s1 */
1.251     brouard  7503:        /* pospropt=0.; */
1.265     brouard  7504:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  7505:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  7506:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  7507:              if(first==1){
1.265     brouard  7508:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  7509:              }
1.265     brouard  7510:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   7511:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  7512:            }
1.265     brouard  7513:            if(s1!=0 && m!=0)
                   7514:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  7515:          }
1.265     brouard  7516:        } /* end loop s1 */
1.251     brouard  7517:        posproptt=0.; 
1.265     brouard  7518:        for(s1=1; s1 <=nlstate; s1++){
                   7519:          posproptt += pospropt[s1];
1.251     brouard  7520:        }
                   7521:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  7522:        fprintf(ficresphtm,"</tr>\n");
1.335     brouard  7523:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  7524:          if(iage <= iagemax)
                   7525:            fprintf(ficresp,"\n");
1.240     brouard  7526:        }
1.251     brouard  7527:        if(first==1)
                   7528:          printf("Others in log...\n");
                   7529:        fprintf(ficlog,"\n");
                   7530:       } /* end loop age iage */
1.265     brouard  7531:       
1.251     brouard  7532:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  7533:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  7534:        if(posproptt < 1.e-5){
1.265     brouard  7535:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  7536:        }else{
1.265     brouard  7537:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  7538:        }
1.226     brouard  7539:       }
1.251     brouard  7540:       fprintf(ficresphtm,"</tr>\n");
                   7541:       fprintf(ficresphtm,"</table>\n");
                   7542:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  7543:       if(posproptt < 1.e-5){
1.251     brouard  7544:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   7545:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  7546:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   7547:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  7548:        invalidvarcomb[j1]=1;
1.226     brouard  7549:       }else{
1.338     brouard  7550:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
1.251     brouard  7551:        invalidvarcomb[j1]=0;
1.226     brouard  7552:       }
1.251     brouard  7553:       fprintf(ficresphtmfr,"</table>\n");
                   7554:       fprintf(ficlog,"\n");
                   7555:       if(j!=0){
                   7556:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  7557:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  7558:          for(k=1; k <=(nlstate+ndeath); k++){
                   7559:            if (k != i) {
1.265     brouard  7560:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  7561:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  7562:                  if(j1==1){ /* All dummy covariates to zero */
                   7563:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   7564:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  7565:                    printf("%d%d ",i,k);
                   7566:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  7567:                    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]));
                   7568:                    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]));
                   7569:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  7570:                  }
1.253     brouard  7571:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   7572:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   7573:                    x[iage]= (double)iage;
                   7574:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  7575:                    /* 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  7576:                  }
1.268     brouard  7577:                  /* Some are not finite, but linreg will ignore these ages */
                   7578:                  no=0;
1.253     brouard  7579:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  7580:                  pstart[s1]=b;
                   7581:                  pstart[s1-1]=a;
1.252     brouard  7582:                }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 */ 
                   7583:                  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]);
                   7584:                  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  7585:                  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  7586:                  printf("%d%d ",i,k);
                   7587:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  7588:                  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  7589:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   7590:                  ;
                   7591:                }
                   7592:                /* printf("%12.7f )", param[i][jj][k]); */
                   7593:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  7594:                s1++; 
1.251     brouard  7595:              } /* end jj */
                   7596:            } /* end k!= i */
                   7597:          } /* end k */
1.265     brouard  7598:        } /* end i, s1 */
1.251     brouard  7599:       } /* end j !=0 */
                   7600:     } /* end selected combination of covariate j1 */
                   7601:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   7602:       printf("#Freqsummary: Starting values for the constants:\n");
                   7603:       fprintf(ficlog,"\n");
1.265     brouard  7604:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  7605:        for(k=1; k <=(nlstate+ndeath); k++){
                   7606:          if (k != i) {
                   7607:            printf("%d%d ",i,k);
                   7608:            fprintf(ficlog,"%d%d ",i,k);
                   7609:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  7610:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  7611:              if(jj==1){ /* Age has to be done */
1.265     brouard  7612:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   7613:                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]));
                   7614:                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  7615:              }
                   7616:              /* printf("%12.7f )", param[i][jj][k]); */
                   7617:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  7618:              s1++; 
1.250     brouard  7619:            }
1.251     brouard  7620:            printf("\n");
                   7621:            fprintf(ficlog,"\n");
1.250     brouard  7622:          }
                   7623:        }
1.284     brouard  7624:       } /* end of state i */
1.251     brouard  7625:       printf("#Freqsummary\n");
                   7626:       fprintf(ficlog,"\n");
1.265     brouard  7627:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   7628:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   7629:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   7630:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   7631:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   7632:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   7633:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   7634:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  7635:          /* } */
                   7636:        }
1.265     brouard  7637:       } /* end loop s1 */
1.251     brouard  7638:       
                   7639:       printf("\n");
                   7640:       fprintf(ficlog,"\n");
                   7641:     } /* end j=0 */
1.249     brouard  7642:   } /* end j */
1.252     brouard  7643: 
1.253     brouard  7644:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  7645:     for(i=1, jk=1; i <=nlstate; i++){
                   7646:       for(j=1; j <=nlstate+ndeath; j++){
                   7647:        if(j!=i){
                   7648:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   7649:          printf("%1d%1d",i,j);
                   7650:          fprintf(ficparo,"%1d%1d",i,j);
                   7651:          for(k=1; k<=ncovmodel;k++){
                   7652:            /*    printf(" %lf",param[i][j][k]); */
                   7653:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   7654:            p[jk]=pstart[jk];
                   7655:            printf(" %f ",pstart[jk]);
                   7656:            fprintf(ficparo," %f ",pstart[jk]);
                   7657:            jk++;
                   7658:          }
                   7659:          printf("\n");
                   7660:          fprintf(ficparo,"\n");
                   7661:        }
                   7662:       }
                   7663:     }
                   7664:   } /* end mle=-2 */
1.226     brouard  7665:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  7666:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  7667:   
1.226     brouard  7668:   fclose(ficresp);
                   7669:   fclose(ficresphtm);
                   7670:   fclose(ficresphtmfr);
1.283     brouard  7671:   free_vector(idq,1,nqfveff);
1.226     brouard  7672:   free_vector(meanq,1,nqfveff);
1.284     brouard  7673:   free_vector(stdq,1,nqfveff);
1.226     brouard  7674:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  7675:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   7676:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  7677:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  7678:   free_vector(pospropt,1,nlstate);
                   7679:   free_vector(posprop,1,nlstate);
1.251     brouard  7680:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  7681:   free_vector(pp,1,nlstate);
                   7682:   /* End of freqsummary */
                   7683: }
1.126     brouard  7684: 
1.268     brouard  7685: /* Simple linear regression */
                   7686: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   7687: 
                   7688:   /* y=a+bx regression */
                   7689:   double   sumx = 0.0;                        /* sum of x                      */
                   7690:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   7691:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   7692:   double   sumy = 0.0;                        /* sum of y                      */
                   7693:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   7694:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   7695:   double yhat;
                   7696:   
                   7697:   double denom=0;
                   7698:   int i;
                   7699:   int ne=*no;
                   7700:   
                   7701:   for ( i=ifi, ne=0;i<=ila;i++) {
                   7702:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   7703:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   7704:       continue;
                   7705:     }
                   7706:     ne=ne+1;
                   7707:     sumx  += x[i];       
                   7708:     sumx2 += x[i]*x[i];  
                   7709:     sumxy += x[i] * y[i];
                   7710:     sumy  += y[i];      
                   7711:     sumy2 += y[i]*y[i]; 
                   7712:     denom = (ne * sumx2 - sumx*sumx);
                   7713:     /* 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); */
                   7714:   } 
                   7715:   
                   7716:   denom = (ne * sumx2 - sumx*sumx);
                   7717:   if (denom == 0) {
                   7718:     // vertical, slope m is infinity
                   7719:     *b = INFINITY;
                   7720:     *a = 0;
                   7721:     if (r) *r = 0;
                   7722:     return 1;
                   7723:   }
                   7724:   
                   7725:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   7726:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   7727:   if (r!=NULL) {
                   7728:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   7729:       sqrt((sumx2 - sumx*sumx/ne) *
                   7730:           (sumy2 - sumy*sumy/ne));
                   7731:   }
                   7732:   *no=ne;
                   7733:   for ( i=ifi, ne=0;i<=ila;i++) {
                   7734:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   7735:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   7736:       continue;
                   7737:     }
                   7738:     ne=ne+1;
                   7739:     yhat = y[i] - *a -*b* x[i];
                   7740:     sume2  += yhat * yhat ;       
                   7741:     
                   7742:     denom = (ne * sumx2 - sumx*sumx);
                   7743:     /* 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); */
                   7744:   } 
                   7745:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   7746:   *sa= *sb * sqrt(sumx2/ne);
                   7747:   
                   7748:   return 0; 
                   7749: }
                   7750: 
1.126     brouard  7751: /************ Prevalence ********************/
1.227     brouard  7752: 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)
                   7753: {  
                   7754:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   7755:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   7756:      We still use firstpass and lastpass as another selection.
                   7757:   */
1.126     brouard  7758:  
1.227     brouard  7759:   int i, m, jk, j1, bool, z1,j, iv;
                   7760:   int mi; /* Effective wave */
                   7761:   int iage;
1.359     brouard  7762:   double agebegin; /*, ageend;*/
1.227     brouard  7763: 
                   7764:   double **prop;
                   7765:   double posprop; 
                   7766:   double  y2; /* in fractional years */
                   7767:   int iagemin, iagemax;
                   7768:   int first; /** to stop verbosity which is redirected to log file */
                   7769: 
                   7770:   iagemin= (int) agemin;
                   7771:   iagemax= (int) agemax;
                   7772:   /*pp=vector(1,nlstate);*/
1.251     brouard  7773:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  7774:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   7775:   j1=0;
1.222     brouard  7776:   
1.227     brouard  7777:   /*j=cptcoveff;*/
                   7778:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  7779:   
1.288     brouard  7780:   first=0;
1.335     brouard  7781:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  7782:     for (i=1; i<=nlstate; i++)  
1.251     brouard  7783:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  7784:        prop[i][iage]=0.0;
                   7785:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   7786:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   7787:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   7788:     
                   7789:     for (i=1; i<=imx; i++) { /* Each individual */
                   7790:       bool=1;
                   7791:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   7792:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   7793:        m=mw[mi][i];
                   7794:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   7795:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   7796:        for (z1=1; z1<=cptcoveff; z1++){
                   7797:          if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  7798:            iv= Tvar[Tmodelind[z1]];/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.332     brouard  7799:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  7800:              bool=0;
                   7801:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  7802:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  7803:              bool=0;
                   7804:            }
                   7805:        }
                   7806:        if(bool==1){ /* Otherwise we skip that wave/person */
                   7807:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   7808:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   7809:          if(m >=firstpass && m <=lastpass){
                   7810:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   7811:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   7812:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   7813:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  7814:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  7815:                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); 
                   7816:                exit(1);
                   7817:              }
                   7818:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   7819:                /*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]]);*/
                   7820:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   7821:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   7822:              } /* end valid statuses */ 
                   7823:            } /* end selection of dates */
                   7824:          } /* end selection of waves */
                   7825:        } /* end bool */
                   7826:       } /* end wave */
                   7827:     } /* end individual */
                   7828:     for(i=iagemin; i <= iagemax+3; i++){  
                   7829:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   7830:        posprop += prop[jk][i]; 
                   7831:       } 
                   7832:       
                   7833:       for(jk=1; jk <=nlstate ; jk++){      
                   7834:        if( i <=  iagemax){ 
                   7835:          if(posprop>=1.e-5){ 
                   7836:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   7837:          } else{
1.288     brouard  7838:            if(!first){
                   7839:              first=1;
1.266     brouard  7840:              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]);
                   7841:            }else{
1.288     brouard  7842:              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  7843:            }
                   7844:          }
                   7845:        } 
                   7846:       }/* end jk */ 
                   7847:     }/* end i */ 
1.222     brouard  7848:      /*} *//* end i1 */
1.227     brouard  7849:   } /* end j1 */
1.222     brouard  7850:   
1.227     brouard  7851:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   7852:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  7853:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  7854: }  /* End of prevalence */
1.126     brouard  7855: 
                   7856: /************* Waves Concatenation ***************/
                   7857: 
                   7858: 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)
                   7859: {
1.298     brouard  7860:   /* 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  7861:      Death is a valid wave (if date is known).
                   7862:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   7863:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  7864:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  7865:   */
1.126     brouard  7866: 
1.224     brouard  7867:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  7868:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   7869:      double sum=0., jmean=0.;*/
1.224     brouard  7870:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  7871:   int j, k=0,jk, ju, jl;
                   7872:   double sum=0.;
                   7873:   first=0;
1.214     brouard  7874:   firstwo=0;
1.217     brouard  7875:   firsthree=0;
1.218     brouard  7876:   firstfour=0;
1.164     brouard  7877:   jmin=100000;
1.126     brouard  7878:   jmax=-1;
                   7879:   jmean=0.;
1.224     brouard  7880: 
                   7881: /* Treating live states */
1.214     brouard  7882:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  7883:     mi=0;  /* First valid wave */
1.227     brouard  7884:     mli=0; /* Last valid wave */
1.309     brouard  7885:     m=firstpass;  /* Loop on waves */
                   7886:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  7887:       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 */
                   7888:        mli=m-1;/* mw[++mi][i]=m-1; */
                   7889:       }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  7890:        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  7891:        mli=m;
1.224     brouard  7892:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   7893:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  7894:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  7895:       }
1.309     brouard  7896:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  7897: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  7898:        break;
1.224     brouard  7899: #else
1.317     brouard  7900:        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  7901:          if(firsthree == 0){
1.302     brouard  7902:            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  7903:            firsthree=1;
1.317     brouard  7904:          }else if(firsthree >=1 && firsthree < 10){
                   7905:            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);
                   7906:            firsthree++;
                   7907:          }else if(firsthree == 10){
                   7908:            printf("Information, too many Information flags: no more reported to log either\n");
                   7909:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   7910:            firsthree++;
                   7911:          }else{
                   7912:            firsthree++;
1.227     brouard  7913:          }
1.309     brouard  7914:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  7915:          mli=m;
                   7916:        }
                   7917:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   7918:          nbwarn++;
1.309     brouard  7919:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  7920:            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);
                   7921:            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);
                   7922:          }
                   7923:          break;
                   7924:        }
                   7925:        break;
1.224     brouard  7926: #endif
1.227     brouard  7927:       }/* End m >= lastpass */
1.126     brouard  7928:     }/* end while */
1.224     brouard  7929: 
1.227     brouard  7930:     /* 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  7931:     /* After last pass */
1.224     brouard  7932: /* Treating death states */
1.214     brouard  7933:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  7934:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   7935:       /* } */
1.126     brouard  7936:       mi++;    /* Death is another wave */
                   7937:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  7938:       /* Only death is a correct wave */
1.126     brouard  7939:       mw[mi][i]=m;
1.257     brouard  7940:     } /* else not in a death state */
1.224     brouard  7941: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  7942:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  7943:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  7944:        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  7945:          nbwarn++;
                   7946:          if(firstfiv==0){
1.309     brouard  7947:            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  7948:            firstfiv=1;
                   7949:          }else{
1.309     brouard  7950:            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  7951:          }
1.309     brouard  7952:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   7953:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  7954:          nberr++;
                   7955:          if(firstwo==0){
1.309     brouard  7956:            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  7957:            firstwo=1;
                   7958:          }
1.309     brouard  7959:          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  7960:        }
1.257     brouard  7961:       }else{ /* if date of interview is unknown */
1.227     brouard  7962:        /* death is known but not confirmed by death status at any wave */
                   7963:        if(firstfour==0){
1.309     brouard  7964:          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  7965:          firstfour=1;
                   7966:        }
1.309     brouard  7967:        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  7968:       }
1.224     brouard  7969:     } /* end if date of death is known */
                   7970: #endif
1.309     brouard  7971:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   7972:     /* wav[i]=mw[mi][i];   */
1.126     brouard  7973:     if(mi==0){
                   7974:       nbwarn++;
                   7975:       if(first==0){
1.227     brouard  7976:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   7977:        first=1;
1.126     brouard  7978:       }
                   7979:       if(first==1){
1.227     brouard  7980:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  7981:       }
                   7982:     } /* end mi==0 */
                   7983:   } /* End individuals */
1.214     brouard  7984:   /* wav and mw are no more changed */
1.223     brouard  7985:        
1.317     brouard  7986:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   7987:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   7988: 
                   7989: 
1.126     brouard  7990:   for(i=1; i<=imx; i++){
                   7991:     for(mi=1; mi<wav[i];mi++){
                   7992:       if (stepm <=0)
1.227     brouard  7993:        dh[mi][i]=1;
1.126     brouard  7994:       else{
1.260     brouard  7995:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  7996:          if (agedc[i] < 2*AGESUP) {
                   7997:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   7998:            if(j==0) j=1;  /* Survives at least one month after exam */
                   7999:            else if(j<0){
                   8000:              nberr++;
1.359     brouard  8001:              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  8002:              j=1; /* Temporary Dangerous patch */
                   8003:              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  8004:              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  8005:              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);
                   8006:            }
                   8007:            k=k+1;
                   8008:            if (j >= jmax){
                   8009:              jmax=j;
                   8010:              ijmax=i;
                   8011:            }
                   8012:            if (j <= jmin){
                   8013:              jmin=j;
                   8014:              ijmin=i;
                   8015:            }
                   8016:            sum=sum+j;
                   8017:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   8018:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   8019:          }
                   8020:        }
                   8021:        else{
                   8022:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  8023: /*       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  8024:                                        
1.227     brouard  8025:          k=k+1;
                   8026:          if (j >= jmax) {
                   8027:            jmax=j;
                   8028:            ijmax=i;
                   8029:          }
                   8030:          else if (j <= jmin){
                   8031:            jmin=j;
                   8032:            ijmin=i;
                   8033:          }
                   8034:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   8035:          /*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]);*/
                   8036:          if(j<0){
                   8037:            nberr++;
1.359     brouard  8038:            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]);
                   8039:            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  8040:          }
                   8041:          sum=sum+j;
                   8042:        }
                   8043:        jk= j/stepm;
                   8044:        jl= j -jk*stepm;
                   8045:        ju= j -(jk+1)*stepm;
                   8046:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   8047:          if(jl==0){
                   8048:            dh[mi][i]=jk;
                   8049:            bh[mi][i]=0;
                   8050:          }else{ /* We want a negative bias in order to only have interpolation ie
                   8051:                  * to avoid the price of an extra matrix product in likelihood */
                   8052:            dh[mi][i]=jk+1;
                   8053:            bh[mi][i]=ju;
                   8054:          }
                   8055:        }else{
                   8056:          if(jl <= -ju){
                   8057:            dh[mi][i]=jk;
                   8058:            bh[mi][i]=jl;       /* bias is positive if real duration
                   8059:                                 * is higher than the multiple of stepm and negative otherwise.
                   8060:                                 */
                   8061:          }
                   8062:          else{
                   8063:            dh[mi][i]=jk+1;
                   8064:            bh[mi][i]=ju;
                   8065:          }
                   8066:          if(dh[mi][i]==0){
                   8067:            dh[mi][i]=1; /* At least one step */
                   8068:            bh[mi][i]=ju; /* At least one step */
                   8069:            /*  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);*/
                   8070:          }
                   8071:        } /* end if mle */
1.126     brouard  8072:       }
                   8073:     } /* end wave */
                   8074:   }
                   8075:   jmean=sum/k;
                   8076:   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  8077:   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  8078: }
1.126     brouard  8079: 
                   8080: /*********** Tricode ****************************/
1.220     brouard  8081:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  8082:  {
                   8083:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   8084:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   8085:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   8086:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   8087:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   8088:     */
1.130     brouard  8089: 
1.242     brouard  8090:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   8091:    int modmaxcovj=0; /* Modality max of covariates j */
                   8092:    int cptcode=0; /* Modality max of covariates j */
                   8093:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  8094: 
                   8095: 
1.242     brouard  8096:    /* cptcoveff=0;  */
                   8097:    /* *cptcov=0; */
1.126     brouard  8098:  
1.242     brouard  8099:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  8100:    for (k=1; k <= maxncov; k++)
                   8101:      for(j=1; j<=2; j++)
                   8102:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  8103: 
1.242     brouard  8104:    /* Loop on covariates without age and products and no quantitative variable */
1.335     brouard  8105:    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  8106:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
1.343     brouard  8107:      /* printf("Testing k=%d, cptcovt=%d\n",k, cptcovt); */
1.349     brouard  8108:      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  8109:        switch(Fixed[k]) {
                   8110:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  8111:         modmaxcovj=0;
                   8112:         modmincovj=0;
1.242     brouard  8113:         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  8114:           /* 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  8115:           ij=(int)(covar[Tvar[k]][i]);
                   8116:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   8117:            * If product of Vn*Vm, still boolean *:
                   8118:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   8119:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   8120:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   8121:              modality of the nth covariate of individual i. */
                   8122:           if (ij > modmaxcovj)
                   8123:             modmaxcovj=ij; 
                   8124:           else if (ij < modmincovj) 
                   8125:             modmincovj=ij; 
1.287     brouard  8126:           if (ij <0 || ij >1 ){
1.311     brouard  8127:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   8128:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   8129:             fflush(ficlog);
                   8130:             exit(1);
1.287     brouard  8131:           }
                   8132:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  8133:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   8134:             exit(1);
                   8135:           }else
                   8136:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   8137:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   8138:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   8139:           /* getting the maximum value of the modality of the covariate
                   8140:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   8141:              female ies 1, then modmaxcovj=1.
                   8142:           */
                   8143:         } /* end for loop on individuals i */
                   8144:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   8145:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   8146:         cptcode=modmaxcovj;
                   8147:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   8148:         /*for (i=0; i<=cptcode; i++) {*/
                   8149:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   8150:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   8151:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   8152:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   8153:             if( j != -1){
                   8154:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   8155:                                  covariate for which somebody answered excluding 
                   8156:                                  undefined. Usually 2: 0 and 1. */
                   8157:             }
                   8158:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   8159:                                     covariate for which somebody answered including 
                   8160:                                     undefined. Usually 3: -1, 0 and 1. */
                   8161:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   8162:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   8163:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  8164:                        
1.242     brouard  8165:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   8166:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   8167:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   8168:         /* modmincovj=3; modmaxcovj = 7; */
                   8169:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   8170:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   8171:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   8172:         /* nbcode[Tvar[j]][ij]=k; */
                   8173:         /* nbcode[Tvar[j]][1]=0; */
                   8174:         /* nbcode[Tvar[j]][2]=1; */
                   8175:         /* nbcode[Tvar[j]][3]=2; */
                   8176:         /* To be continued (not working yet). */
                   8177:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  8178: 
                   8179:         /* 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*/
                   8180:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   8181:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   8182:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   8183:         /*, could be restored in the future */
                   8184:         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  8185:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   8186:             break;
                   8187:           }
                   8188:           ij++;
1.287     brouard  8189:           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  8190:           cptcode = ij; /* New max modality for covar j */
                   8191:         } /* end of loop on modality i=-1 to 1 or more */
                   8192:         break;
                   8193:        case 1: /* Testing on varying covariate, could be simple and
                   8194:                * should look at waves or product of fixed *
                   8195:                * varying. No time to test -1, assuming 0 and 1 only */
                   8196:         ij=0;
                   8197:         for(i=0; i<=1;i++){
                   8198:           nbcode[Tvar[k]][++ij]=i;
                   8199:         }
                   8200:         break;
                   8201:        default:
                   8202:         break;
                   8203:        } /* end switch */
                   8204:      } /* end dummy test */
1.349     brouard  8205:      if(Dummy[k]==1 && Typevar[k] !=1 && Typevar[k] !=3 && Fixed ==0){ /* Fixed Quantitative covariate and not age product */ 
1.311     brouard  8206:        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  8207:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   8208:           printf("Error k=%d \n",k);
                   8209:           exit(1);
                   8210:         }
1.311     brouard  8211:         if(isnan(covar[Tvar[k]][i])){
                   8212:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   8213:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   8214:           fflush(ficlog);
                   8215:           exit(1);
                   8216:          }
                   8217:        }
1.335     brouard  8218:      } /* end Quanti */
1.287     brouard  8219:    } /* 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  8220:   
                   8221:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   8222:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   8223:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   8224:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   8225:      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 */ 
                   8226:      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 */
                   8227:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   8228:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   8229:   
                   8230:    ij=0;
                   8231:    /* 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  8232:    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 */
                   8233:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  8234:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   8235:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335     brouard  8236:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   8237:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   8238:        /* 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  8239:        /* If product not in single variable we don't print results */
                   8240:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335     brouard  8241:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   8242:        /* k=       1    2   3     4       5       6      7       8        9  */
                   8243:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   8244:        /* ij            1    2                                            3  */  
                   8245:        /* Tvaraff[ij]=  4    3                                            1  */
                   8246:        /* Tmodelind[ij]=2    3                                            9  */
                   8247:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  8248:        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*/
                   8249:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   8250:        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 */
                   8251:        if(Fixed[k]!=0)
                   8252:         anyvaryingduminmodel=1;
                   8253:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   8254:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   8255:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   8256:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   8257:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   8258:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   8259:      } 
                   8260:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   8261:    /* ij--; */
                   8262:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335     brouard  8263:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  8264:                * because they can be excluded from the model and real
                   8265:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   8266:    for(j=ij+1; j<= cptcovt; j++){
                   8267:      Tvaraff[j]=0;
                   8268:      Tmodelind[j]=0;
                   8269:    }
                   8270:    for(j=ntveff+1; j<= cptcovt; j++){
                   8271:      TmodelInvind[j]=0;
                   8272:    }
                   8273:    /* To be sorted */
                   8274:    ;
                   8275:  }
1.126     brouard  8276: 
1.145     brouard  8277: 
1.126     brouard  8278: /*********** Health Expectancies ****************/
                   8279: 
1.235     brouard  8280:  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  8281: 
                   8282: {
                   8283:   /* Health expectancies, no variances */
1.329     brouard  8284:   /* cij is the combination in the list of combination of dummy covariates */
                   8285:   /* strstart is a string of time at start of computing */
1.164     brouard  8286:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  8287:   int nhstepma, nstepma; /* Decreasing with age */
                   8288:   double age, agelim, hf;
                   8289:   double ***p3mat;
                   8290:   double eip;
                   8291: 
1.238     brouard  8292:   /* pstamp(ficreseij); */
1.126     brouard  8293:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   8294:   fprintf(ficreseij,"# Age");
                   8295:   for(i=1; i<=nlstate;i++){
                   8296:     for(j=1; j<=nlstate;j++){
                   8297:       fprintf(ficreseij," e%1d%1d ",i,j);
                   8298:     }
                   8299:     fprintf(ficreseij," e%1d. ",i);
                   8300:   }
                   8301:   fprintf(ficreseij,"\n");
                   8302: 
                   8303:   
                   8304:   if(estepm < stepm){
                   8305:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8306:   }
                   8307:   else  hstepm=estepm;   
                   8308:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   8309:    * This is mainly to measure the difference between two models: for example
                   8310:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   8311:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   8312:    * progression in between and thus overestimating or underestimating according
                   8313:    * to the curvature of the survival function. If, for the same date, we 
                   8314:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   8315:    * to compare the new estimate of Life expectancy with the same linear 
                   8316:    * hypothesis. A more precise result, taking into account a more precise
                   8317:    * curvature will be obtained if estepm is as small as stepm. */
                   8318: 
                   8319:   /* For example we decided to compute the life expectancy with the smallest unit */
                   8320:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   8321:      nhstepm is the number of hstepm from age to agelim 
                   8322:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  8323:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  8324:      and note for a fixed period like estepm months */
                   8325:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   8326:      survival function given by stepm (the optimization length). Unfortunately it
                   8327:      means that if the survival funtion is printed only each two years of age and if
                   8328:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   8329:      results. So we changed our mind and took the option of the best precision.
                   8330:   */
                   8331:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   8332: 
                   8333:   agelim=AGESUP;
                   8334:   /* If stepm=6 months */
                   8335:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   8336:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   8337:     
                   8338: /* nhstepm age range expressed in number of stepm */
                   8339:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   8340:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   8341:   /* if (stepm >= YEARM) hstepm=1;*/
                   8342:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   8343:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8344: 
                   8345:   for (age=bage; age<=fage; age ++){ 
                   8346:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   8347:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   8348:     /* if (stepm >= YEARM) hstepm=1;*/
                   8349:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   8350: 
                   8351:     /* If stepm=6 months */
                   8352:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   8353:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  8354:     /* 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  8355:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  8356:     
                   8357:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   8358:     
                   8359:     printf("%d|",(int)age);fflush(stdout);
                   8360:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   8361:     
                   8362:     /* Computing expectancies */
                   8363:     for(i=1; i<=nlstate;i++)
                   8364:       for(j=1; j<=nlstate;j++)
                   8365:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   8366:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   8367:          
                   8368:          /* 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]);*/
                   8369: 
                   8370:        }
                   8371: 
                   8372:     fprintf(ficreseij,"%3.0f",age );
                   8373:     for(i=1; i<=nlstate;i++){
                   8374:       eip=0;
                   8375:       for(j=1; j<=nlstate;j++){
                   8376:        eip +=eij[i][j][(int)age];
                   8377:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   8378:       }
                   8379:       fprintf(ficreseij,"%9.4f", eip );
                   8380:     }
                   8381:     fprintf(ficreseij,"\n");
                   8382:     
                   8383:   }
                   8384:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8385:   printf("\n");
                   8386:   fprintf(ficlog,"\n");
                   8387:   
                   8388: }
                   8389: 
1.235     brouard  8390:  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  8391: 
                   8392: {
                   8393:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  8394:      to initial status i, ei. .
1.126     brouard  8395:   */
1.336     brouard  8396:   /* Very time consuming function, but already optimized with precov */
1.126     brouard  8397:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   8398:   int nhstepma, nstepma; /* Decreasing with age */
                   8399:   double age, agelim, hf;
                   8400:   double ***p3matp, ***p3matm, ***varhe;
                   8401:   double **dnewm,**doldm;
                   8402:   double *xp, *xm;
                   8403:   double **gp, **gm;
                   8404:   double ***gradg, ***trgradg;
                   8405:   int theta;
                   8406: 
                   8407:   double eip, vip;
                   8408: 
                   8409:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   8410:   xp=vector(1,npar);
                   8411:   xm=vector(1,npar);
                   8412:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   8413:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   8414:   
                   8415:   pstamp(ficresstdeij);
                   8416:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   8417:   fprintf(ficresstdeij,"# Age");
                   8418:   for(i=1; i<=nlstate;i++){
                   8419:     for(j=1; j<=nlstate;j++)
                   8420:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   8421:     fprintf(ficresstdeij," e%1d. ",i);
                   8422:   }
                   8423:   fprintf(ficresstdeij,"\n");
                   8424: 
                   8425:   pstamp(ficrescveij);
                   8426:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   8427:   fprintf(ficrescveij,"# Age");
                   8428:   for(i=1; i<=nlstate;i++)
                   8429:     for(j=1; j<=nlstate;j++){
                   8430:       cptj= (j-1)*nlstate+i;
                   8431:       for(i2=1; i2<=nlstate;i2++)
                   8432:        for(j2=1; j2<=nlstate;j2++){
                   8433:          cptj2= (j2-1)*nlstate+i2;
                   8434:          if(cptj2 <= cptj)
                   8435:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   8436:        }
                   8437:     }
                   8438:   fprintf(ficrescveij,"\n");
                   8439:   
                   8440:   if(estepm < stepm){
                   8441:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8442:   }
                   8443:   else  hstepm=estepm;   
                   8444:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   8445:    * This is mainly to measure the difference between two models: for example
                   8446:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   8447:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   8448:    * progression in between and thus overestimating or underestimating according
                   8449:    * to the curvature of the survival function. If, for the same date, we 
                   8450:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   8451:    * to compare the new estimate of Life expectancy with the same linear 
                   8452:    * hypothesis. A more precise result, taking into account a more precise
                   8453:    * curvature will be obtained if estepm is as small as stepm. */
                   8454: 
                   8455:   /* For example we decided to compute the life expectancy with the smallest unit */
                   8456:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   8457:      nhstepm is the number of hstepm from age to agelim 
                   8458:      nstepm is the number of stepm from age to agelin. 
                   8459:      Look at hpijx to understand the reason of that which relies in memory size
                   8460:      and note for a fixed period like estepm months */
                   8461:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   8462:      survival function given by stepm (the optimization length). Unfortunately it
                   8463:      means that if the survival funtion is printed only each two years of age and if
                   8464:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   8465:      results. So we changed our mind and took the option of the best precision.
                   8466:   */
                   8467:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   8468: 
                   8469:   /* If stepm=6 months */
                   8470:   /* nhstepm age range expressed in number of stepm */
                   8471:   agelim=AGESUP;
                   8472:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   8473:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   8474:   /* if (stepm >= YEARM) hstepm=1;*/
                   8475:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   8476:   
                   8477:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8478:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8479:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   8480:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   8481:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   8482:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   8483: 
                   8484:   for (age=bage; age<=fage; age ++){ 
                   8485:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   8486:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   8487:     /* if (stepm >= YEARM) hstepm=1;*/
                   8488:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  8489:                
1.126     brouard  8490:     /* If stepm=6 months */
                   8491:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   8492:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   8493:     
                   8494:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  8495:                
1.126     brouard  8496:     /* Computing  Variances of health expectancies */
                   8497:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   8498:        decrease memory allocation */
                   8499:     for(theta=1; theta <=npar; theta++){
                   8500:       for(i=1; i<=npar; i++){ 
1.222     brouard  8501:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   8502:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  8503:       }
1.235     brouard  8504:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   8505:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  8506:                        
1.126     brouard  8507:       for(j=1; j<= nlstate; j++){
1.222     brouard  8508:        for(i=1; i<=nlstate; i++){
                   8509:          for(h=0; h<=nhstepm-1; h++){
                   8510:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   8511:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   8512:          }
                   8513:        }
1.126     brouard  8514:       }
1.218     brouard  8515:                        
1.126     brouard  8516:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  8517:        for(h=0; h<=nhstepm-1; h++){
                   8518:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   8519:        }
1.126     brouard  8520:     }/* End theta */
                   8521:     
                   8522:     
                   8523:     for(h=0; h<=nhstepm-1; h++)
                   8524:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  8525:        for(theta=1; theta <=npar; theta++)
                   8526:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  8527:     
1.218     brouard  8528:                
1.222     brouard  8529:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  8530:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  8531:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  8532:                
1.222     brouard  8533:     printf("%d|",(int)age);fflush(stdout);
                   8534:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   8535:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  8536:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  8537:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   8538:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   8539:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   8540:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   8541:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  8542:       }
                   8543:     }
1.320     brouard  8544:     /* if((int)age ==50){ */
                   8545:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   8546:     /* } */
1.126     brouard  8547:     /* Computing expectancies */
1.235     brouard  8548:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  8549:     for(i=1; i<=nlstate;i++)
                   8550:       for(j=1; j<=nlstate;j++)
1.222     brouard  8551:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   8552:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  8553:                                        
1.222     brouard  8554:          /* 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  8555:                                        
1.222     brouard  8556:        }
1.269     brouard  8557: 
                   8558:     /* Standard deviation of expectancies ij */                
1.126     brouard  8559:     fprintf(ficresstdeij,"%3.0f",age );
                   8560:     for(i=1; i<=nlstate;i++){
                   8561:       eip=0.;
                   8562:       vip=0.;
                   8563:       for(j=1; j<=nlstate;j++){
1.222     brouard  8564:        eip += eij[i][j][(int)age];
                   8565:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   8566:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   8567:        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  8568:       }
                   8569:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   8570:     }
                   8571:     fprintf(ficresstdeij,"\n");
1.218     brouard  8572:                
1.269     brouard  8573:     /* Variance of expectancies ij */          
1.126     brouard  8574:     fprintf(ficrescveij,"%3.0f",age );
                   8575:     for(i=1; i<=nlstate;i++)
                   8576:       for(j=1; j<=nlstate;j++){
1.222     brouard  8577:        cptj= (j-1)*nlstate+i;
                   8578:        for(i2=1; i2<=nlstate;i2++)
                   8579:          for(j2=1; j2<=nlstate;j2++){
                   8580:            cptj2= (j2-1)*nlstate+i2;
                   8581:            if(cptj2 <= cptj)
                   8582:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   8583:          }
1.126     brouard  8584:       }
                   8585:     fprintf(ficrescveij,"\n");
1.218     brouard  8586:                
1.126     brouard  8587:   }
                   8588:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   8589:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   8590:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   8591:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   8592:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8593:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8594:   printf("\n");
                   8595:   fprintf(ficlog,"\n");
1.218     brouard  8596:        
1.126     brouard  8597:   free_vector(xm,1,npar);
                   8598:   free_vector(xp,1,npar);
                   8599:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   8600:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   8601:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   8602: }
1.218     brouard  8603:  
1.126     brouard  8604: /************ Variance ******************/
1.235     brouard  8605:  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  8606:  {
1.361     brouard  8607:    /** Computes the matrix of variance covariance of health expectancies e.j= sum_i w_i e_ij where w_i depends of popbased,
                   8608:     * either cross-sectional or implied.
                   8609:     * 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  8610:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   8611:     * double **newm;
                   8612:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   8613:     */
1.218     brouard  8614:   
                   8615:    /* int movingaverage(); */
                   8616:    double **dnewm,**doldm;
                   8617:    double **dnewmp,**doldmp;
                   8618:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  8619:    int first=0;
1.218     brouard  8620:    int k;
                   8621:    double *xp;
1.279     brouard  8622:    double **gp, **gm;  /**< for var eij */
                   8623:    double ***gradg, ***trgradg; /**< for var eij */
                   8624:    double **gradgp, **trgradgp; /**< for var p point j */
                   8625:    double *gpp, *gmp; /**< for var p point j */
1.362     brouard  8626:    double **varppt; /**< for var p.3 p.death nlstate+1 to nlstate+ndeath */
1.218     brouard  8627:    double ***p3mat;
                   8628:    double age,agelim, hf;
                   8629:    /* double ***mobaverage; */
                   8630:    int theta;
                   8631:    char digit[4];
                   8632:    char digitp[25];
                   8633: 
                   8634:    char fileresprobmorprev[FILENAMELENGTH];
                   8635: 
                   8636:    if(popbased==1){
                   8637:      if(mobilav!=0)
                   8638:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   8639:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   8640:    }
                   8641:    else 
                   8642:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  8643: 
1.218     brouard  8644:    /* if (mobilav!=0) { */
                   8645:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8646:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   8647:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   8648:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   8649:    /*   } */
                   8650:    /* } */
                   8651: 
                   8652:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   8653:    sprintf(digit,"%-d",ij);
                   8654:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   8655:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   8656:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   8657:    strcat(fileresprobmorprev,fileresu);
                   8658:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   8659:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   8660:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   8661:    }
                   8662:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   8663:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   8664:    pstamp(ficresprobmorprev);
                   8665:    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  8666:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.337     brouard  8667: 
                   8668:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
                   8669:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
                   8670:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   8671:    /* } */
                   8672:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
1.344     brouard  8673:      /* fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); */
1.337     brouard  8674:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  8675:    }
1.337     brouard  8676:    /* for(j=1;j<=cptcoveff;j++)  */
                   8677:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
1.238     brouard  8678:    fprintf(ficresprobmorprev,"\n");
                   8679: 
1.218     brouard  8680:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   8681:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   8682:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   8683:      for(i=1; i<=nlstate;i++)
                   8684:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   8685:    }  
                   8686:    fprintf(ficresprobmorprev,"\n");
                   8687:   
                   8688:    fprintf(ficgp,"\n# Routine varevsij");
                   8689:    fprintf(ficgp,"\nunset title \n");
                   8690:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   8691:    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");
                   8692:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  8693: 
1.361     brouard  8694:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath); /* In fact, currently a double */
1.218     brouard  8695:    pstamp(ficresvij);
                   8696:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   8697:    if(popbased==1)
                   8698:      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);
                   8699:    else
                   8700:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   8701:    fprintf(ficresvij,"# Age");
                   8702:    for(i=1; i<=nlstate;i++)
                   8703:      for(j=1; j<=nlstate;j++)
                   8704:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   8705:    fprintf(ficresvij,"\n");
                   8706: 
                   8707:    xp=vector(1,npar);
                   8708:    dnewm=matrix(1,nlstate,1,npar);
                   8709:    doldm=matrix(1,nlstate,1,nlstate);
                   8710:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   8711:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   8712: 
                   8713:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   8714:    gpp=vector(nlstate+1,nlstate+ndeath);
                   8715:    gmp=vector(nlstate+1,nlstate+ndeath);
                   8716:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  8717:   
1.218     brouard  8718:    if(estepm < stepm){
                   8719:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   8720:    }
                   8721:    else  hstepm=estepm;   
                   8722:    /* For example we decided to compute the life expectancy with the smallest unit */
                   8723:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   8724:       nhstepm is the number of hstepm from age to agelim 
                   8725:       nstepm is the number of stepm from age to agelim. 
                   8726:       Look at function hpijx to understand why because of memory size limitations, 
                   8727:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   8728:       survival function given by stepm (the optimization length). Unfortunately it
                   8729:       means that if the survival funtion is printed every two years of age and if
                   8730:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   8731:       results. So we changed our mind and took the option of the best precision.
                   8732:    */
                   8733:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   8734:    agelim = AGESUP;
                   8735:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   8736:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   8737:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   8738:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8739:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   8740:      gp=matrix(0,nhstepm,1,nlstate);
                   8741:      gm=matrix(0,nhstepm,1,nlstate);
                   8742:                
                   8743:                
                   8744:      for(theta=1; theta <=npar; theta++){
                   8745:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   8746:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   8747:        }
1.279     brouard  8748:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   8749:        * returns into prlim .
1.288     brouard  8750:        */
1.242     brouard  8751:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  8752: 
                   8753:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  8754:        if (popbased==1) {
                   8755:         if(mobilav ==0){
                   8756:           for(i=1; i<=nlstate;i++)
                   8757:             prlim[i][i]=probs[(int)age][i][ij];
                   8758:         }else{ /* mobilav */ 
                   8759:           for(i=1; i<=nlstate;i++)
                   8760:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   8761:         }
                   8762:        }
1.361     brouard  8763:        /**< Computes the shifted plus (gp) transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  8764:        */                      
                   8765:        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  8766:        /**< 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  8767:        * at horizon h in state j including mortality.
                   8768:        */
1.218     brouard  8769:        for(j=1; j<= nlstate; j++){
                   8770:         for(h=0; h<=nhstepm; h++){
                   8771:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
1.361     brouard  8772:             gp[h][j] += prlim[i][i]*p3mat[i][j][h]; /* gp[h][j]= w_i h_pij */
1.218     brouard  8773:         }
                   8774:        }
1.279     brouard  8775:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  8776:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  8777:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  8778:        */
1.361     brouard  8779:        for(j=nlstate+1;j<=nlstate+ndeath;j++){ /* Currently only once for theta plus  p.3(age) Sum_i wi pi3*/
1.218     brouard  8780:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   8781:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  8782:        }
                   8783:        
                   8784:        /* Again with minus shift */
1.218     brouard  8785:                        
                   8786:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   8787:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  8788: 
1.242     brouard  8789:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  8790:                        
                   8791:        if (popbased==1) {
                   8792:         if(mobilav ==0){
                   8793:           for(i=1; i<=nlstate;i++)
                   8794:             prlim[i][i]=probs[(int)age][i][ij];
                   8795:         }else{ /* mobilav */ 
                   8796:           for(i=1; i<=nlstate;i++)
                   8797:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   8798:         }
                   8799:        }
                   8800:                        
1.361     brouard  8801:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  /* Still minus */
1.218     brouard  8802:                        
1.361     brouard  8803:        for(j=1; j<= nlstate; j++){  /* gm[h][j]= Sum_i of wi * pij =  h_p.j */
1.218     brouard  8804:         for(h=0; h<=nhstepm; h++){
                   8805:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   8806:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   8807:         }
                   8808:        }
                   8809:        /* This for computing probability of death (h=1 means
                   8810:          computed over hstepm matrices product = hstepm*stepm months) 
1.361     brouard  8811:          as a weighted average of prlim. j is death. gmp[3]=sum_i w_i*p_i3=p.3 minus theta
1.218     brouard  8812:        */
1.361     brouard  8813:        for(j=nlstate+1;j<=nlstate+ndeath;j++){  /* Currently only once theta_minus  p.3=Sum_i wi pi3*/
1.218     brouard  8814:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   8815:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   8816:        }    
1.279     brouard  8817:        /* end shifting computations */
                   8818: 
1.361     brouard  8819:        /**< Computing gradient of p.j matrix at horizon h and still for one parameter of vector theta
                   8820:        * equation 31 and 32
1.279     brouard  8821:        */
1.361     brouard  8822:        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)
                   8823:                                  * equation 24 */
1.218     brouard  8824:         for(h=0; h<=nhstepm; h++){
                   8825:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   8826:         }
1.361     brouard  8827:        /**< Gradient of overall mortality p.3 (or p.death) 
1.279     brouard  8828:        */
1.361     brouard  8829:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* computes grad of p.3 from wi+pi3 grad p.3 (theta) */
1.218     brouard  8830:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   8831:        }
                   8832:                        
                   8833:      } /* End theta */
1.279     brouard  8834:      
1.361     brouard  8835:      /* We got the gradient matrix for each theta and each state j of gradg(h]theta][j)=grad(_hp.j(theta) */           
                   8836:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar);
1.218     brouard  8837:                
1.361     brouard  8838:      for(h=0; h<=nhstepm; h++) /* veij */ /* computes the transposed of grad  (_hp.j(theta)*/
1.218     brouard  8839:        for(j=1; j<=nlstate;j++)
                   8840:         for(theta=1; theta <=npar; theta++)
                   8841:           trgradg[h][j][theta]=gradg[h][theta][j];
                   8842:                
1.361     brouard  8843:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* computes transposed of grad p.3 (theta)*/
1.218     brouard  8844:        for(theta=1; theta <=npar; theta++)
                   8845:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  8846:      /**< as well as its transposed matrix 
                   8847:       */               
1.218     brouard  8848:                
                   8849:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   8850:      for(i=1;i<=nlstate;i++)
                   8851:        for(j=1;j<=nlstate;j++)
                   8852:         vareij[i][j][(int)age] =0.;
1.279     brouard  8853: 
                   8854:      /* Computing trgradg by matcov by gradg at age and summing over h
1.361     brouard  8855:       * and k (nhstepm) formula 32 of article
                   8856:       * Lievre-Brouard-Heathcote so that for each j, computes the cov(e.j,e.k) (formula 31).
                   8857:       * for given h and k computes trgradg[h](i,j) matcov (theta) gradg(k)(i,j) into vareij[i][j] which is
                   8858:       cov(e.i,e.j) and sums on h and k
                   8859:       * including the covariances.
1.279     brouard  8860:       */
                   8861:      
1.218     brouard  8862:      for(h=0;h<=nhstepm;h++){
                   8863:        for(k=0;k<=nhstepm;k++){
                   8864:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   8865:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   8866:         for(i=1;i<=nlstate;i++)
                   8867:           for(j=1;j<=nlstate;j++)
1.361     brouard  8868:             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)
                   8869:                                                             including the covariances of e.j */
1.218     brouard  8870:        }
                   8871:      }
                   8872:                
1.361     brouard  8873:      /* Mortality: pptj is p.3 or p.death = trgradgp by cov by gradgp, variance of
                   8874:       * p.3=1-p..=1-sum i p.i  overall mortality computed directly because
1.279     brouard  8875:       * we compute the grad (wix pijx) instead of grad (pijx),even if
1.361     brouard  8876:       * wix is independent of theta. 
1.279     brouard  8877:       */
1.218     brouard  8878:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   8879:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   8880:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   8881:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
1.361     brouard  8882:         varppt[j][i]=doldmp[j][i];  /* This is the variance of p.3 */
1.218     brouard  8883:      /* end ppptj */
                   8884:      /*  x centered again */
                   8885:                
1.242     brouard  8886:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  8887:                
                   8888:      if (popbased==1) {
                   8889:        if(mobilav ==0){
                   8890:         for(i=1; i<=nlstate;i++)
                   8891:           prlim[i][i]=probs[(int)age][i][ij];
                   8892:        }else{ /* mobilav */ 
                   8893:         for(i=1; i<=nlstate;i++)
                   8894:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   8895:        }
                   8896:      }
                   8897:                
                   8898:      /* This for computing probability of death (h=1 means
                   8899:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   8900:        as a weighted average of prlim.
                   8901:      */
1.235     brouard  8902:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  8903:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   8904:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
1.361     brouard  8905:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; /* gmp[j] is p.3 */
1.218     brouard  8906:      }    
                   8907:      /* end probability of death */
                   8908:                
                   8909:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   8910:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
1.361     brouard  8911:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));/* p.3 (STD p.3) */
1.218     brouard  8912:        for(i=1; i<=nlstate;i++){
1.361     brouard  8913:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]); /* wi, pi3 */
1.218     brouard  8914:        }
                   8915:      } 
                   8916:      fprintf(ficresprobmorprev,"\n");
                   8917:                
                   8918:      fprintf(ficresvij,"%.0f ",age );
                   8919:      for(i=1; i<=nlstate;i++)
                   8920:        for(j=1; j<=nlstate;j++){
                   8921:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   8922:        }
                   8923:      fprintf(ficresvij,"\n");
                   8924:      free_matrix(gp,0,nhstepm,1,nlstate);
                   8925:      free_matrix(gm,0,nhstepm,1,nlstate);
                   8926:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   8927:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   8928:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8929:    } /* End age */
                   8930:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   8931:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   8932:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   8933:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   8934:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   8935:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   8936:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   8937:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   8938:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   8939:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   8940:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   8941:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   8942:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   8943:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   8944:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   8945:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   8946:    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);
                   8947:    /*  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  8948:     */
1.218     brouard  8949:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   8950:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  8951: 
1.218     brouard  8952:    free_vector(xp,1,npar);
                   8953:    free_matrix(doldm,1,nlstate,1,nlstate);
                   8954:    free_matrix(dnewm,1,nlstate,1,npar);
                   8955:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   8956:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   8957:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   8958:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8959:    fclose(ficresprobmorprev);
                   8960:    fflush(ficgp);
                   8961:    fflush(fichtm); 
                   8962:  }  /* end varevsij */
1.126     brouard  8963: 
                   8964: /************ Variance of prevlim ******************/
1.269     brouard  8965:  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  8966: {
1.205     brouard  8967:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  8968:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  8969: 
1.268     brouard  8970:   double **dnewmpar,**doldm;
1.126     brouard  8971:   int i, j, nhstepm, hstepm;
                   8972:   double *xp;
                   8973:   double *gp, *gm;
                   8974:   double **gradg, **trgradg;
1.208     brouard  8975:   double **mgm, **mgp;
1.126     brouard  8976:   double age,agelim;
                   8977:   int theta;
                   8978:   
                   8979:   pstamp(ficresvpl);
1.288     brouard  8980:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  8981:   fprintf(ficresvpl,"# Age ");
                   8982:   if(nresult >=1)
                   8983:     fprintf(ficresvpl," Result# ");
1.126     brouard  8984:   for(i=1; i<=nlstate;i++)
                   8985:       fprintf(ficresvpl," %1d-%1d",i,i);
                   8986:   fprintf(ficresvpl,"\n");
                   8987: 
                   8988:   xp=vector(1,npar);
1.268     brouard  8989:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  8990:   doldm=matrix(1,nlstate,1,nlstate);
                   8991:   
                   8992:   hstepm=1*YEARM; /* Every year of age */
                   8993:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   8994:   agelim = AGESUP;
                   8995:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   8996:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   8997:     if (stepm >= YEARM) hstepm=1;
                   8998:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   8999:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  9000:     mgp=matrix(1,npar,1,nlstate);
                   9001:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  9002:     gp=vector(1,nlstate);
                   9003:     gm=vector(1,nlstate);
                   9004: 
                   9005:     for(theta=1; theta <=npar; theta++){
                   9006:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   9007:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   9008:       }
1.288     brouard  9009:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   9010:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   9011:       /* else */
                   9012:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  9013:       for(i=1;i<=nlstate;i++){
1.126     brouard  9014:        gp[i] = prlim[i][i];
1.208     brouard  9015:        mgp[theta][i] = prlim[i][i];
                   9016:       }
1.126     brouard  9017:       for(i=1; i<=npar; i++) /* Computes gradient */
                   9018:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  9019:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   9020:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   9021:       /* else */
                   9022:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  9023:       for(i=1;i<=nlstate;i++){
1.126     brouard  9024:        gm[i] = prlim[i][i];
1.208     brouard  9025:        mgm[theta][i] = prlim[i][i];
                   9026:       }
1.126     brouard  9027:       for(i=1;i<=nlstate;i++)
                   9028:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  9029:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  9030:     } /* End theta */
                   9031: 
                   9032:     trgradg =matrix(1,nlstate,1,npar);
                   9033: 
                   9034:     for(j=1; j<=nlstate;j++)
                   9035:       for(theta=1; theta <=npar; theta++)
                   9036:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  9037:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   9038:     /*   printf("\nmgm mgp %d ",(int)age); */
                   9039:     /*   for(j=1; j<=nlstate;j++){ */
                   9040:     /*         printf(" %d ",j); */
                   9041:     /*         for(theta=1; theta <=npar; theta++) */
                   9042:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   9043:     /*         printf("\n "); */
                   9044:     /*   } */
                   9045:     /* } */
                   9046:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   9047:     /*   printf("\n gradg %d ",(int)age); */
                   9048:     /*   for(j=1; j<=nlstate;j++){ */
                   9049:     /*         printf("%d ",j); */
                   9050:     /*         for(theta=1; theta <=npar; theta++) */
                   9051:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   9052:     /*         printf("\n "); */
                   9053:     /*   } */
                   9054:     /* } */
1.126     brouard  9055: 
                   9056:     for(i=1;i<=nlstate;i++)
                   9057:       varpl[i][(int)age] =0.;
1.209     brouard  9058:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  9059:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   9060:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  9061:     }else{
1.268     brouard  9062:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   9063:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  9064:     }
1.126     brouard  9065:     for(i=1;i<=nlstate;i++)
                   9066:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   9067: 
                   9068:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  9069:     if(nresult >=1)
                   9070:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  9071:     for(i=1; i<=nlstate;i++){
1.126     brouard  9072:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  9073:       /* for(j=1;j<=nlstate;j++) */
                   9074:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   9075:     }
1.126     brouard  9076:     fprintf(ficresvpl,"\n");
                   9077:     free_vector(gp,1,nlstate);
                   9078:     free_vector(gm,1,nlstate);
1.208     brouard  9079:     free_matrix(mgm,1,npar,1,nlstate);
                   9080:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  9081:     free_matrix(gradg,1,npar,1,nlstate);
                   9082:     free_matrix(trgradg,1,nlstate,1,npar);
                   9083:   } /* End age */
                   9084: 
                   9085:   free_vector(xp,1,npar);
                   9086:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  9087:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   9088: 
                   9089: }
                   9090: 
                   9091: 
                   9092: /************ Variance of backprevalence limit ******************/
1.269     brouard  9093:  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  9094: {
                   9095:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   9096:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   9097: 
                   9098:   double **dnewmpar,**doldm;
                   9099:   int i, j, nhstepm, hstepm;
                   9100:   double *xp;
                   9101:   double *gp, *gm;
                   9102:   double **gradg, **trgradg;
                   9103:   double **mgm, **mgp;
                   9104:   double age,agelim;
                   9105:   int theta;
                   9106:   
                   9107:   pstamp(ficresvbl);
                   9108:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   9109:   fprintf(ficresvbl,"# Age ");
                   9110:   if(nresult >=1)
                   9111:     fprintf(ficresvbl," Result# ");
                   9112:   for(i=1; i<=nlstate;i++)
                   9113:       fprintf(ficresvbl," %1d-%1d",i,i);
                   9114:   fprintf(ficresvbl,"\n");
                   9115: 
                   9116:   xp=vector(1,npar);
                   9117:   dnewmpar=matrix(1,nlstate,1,npar);
                   9118:   doldm=matrix(1,nlstate,1,nlstate);
                   9119:   
                   9120:   hstepm=1*YEARM; /* Every year of age */
                   9121:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   9122:   agelim = AGEINF;
                   9123:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   9124:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   9125:     if (stepm >= YEARM) hstepm=1;
                   9126:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   9127:     gradg=matrix(1,npar,1,nlstate);
                   9128:     mgp=matrix(1,npar,1,nlstate);
                   9129:     mgm=matrix(1,npar,1,nlstate);
                   9130:     gp=vector(1,nlstate);
                   9131:     gm=vector(1,nlstate);
                   9132: 
                   9133:     for(theta=1; theta <=npar; theta++){
                   9134:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   9135:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   9136:       }
                   9137:       if(mobilavproj > 0 )
                   9138:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   9139:       else
                   9140:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   9141:       for(i=1;i<=nlstate;i++){
                   9142:        gp[i] = bprlim[i][i];
                   9143:        mgp[theta][i] = bprlim[i][i];
                   9144:       }
                   9145:      for(i=1; i<=npar; i++) /* Computes gradient */
                   9146:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   9147:        if(mobilavproj > 0 )
                   9148:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   9149:        else
                   9150:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   9151:       for(i=1;i<=nlstate;i++){
                   9152:        gm[i] = bprlim[i][i];
                   9153:        mgm[theta][i] = bprlim[i][i];
                   9154:       }
                   9155:       for(i=1;i<=nlstate;i++)
                   9156:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   9157:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   9158:     } /* End theta */
                   9159: 
                   9160:     trgradg =matrix(1,nlstate,1,npar);
                   9161: 
                   9162:     for(j=1; j<=nlstate;j++)
                   9163:       for(theta=1; theta <=npar; theta++)
                   9164:        trgradg[j][theta]=gradg[theta][j];
                   9165:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   9166:     /*   printf("\nmgm mgp %d ",(int)age); */
                   9167:     /*   for(j=1; j<=nlstate;j++){ */
                   9168:     /*         printf(" %d ",j); */
                   9169:     /*         for(theta=1; theta <=npar; theta++) */
                   9170:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   9171:     /*         printf("\n "); */
                   9172:     /*   } */
                   9173:     /* } */
                   9174:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   9175:     /*   printf("\n gradg %d ",(int)age); */
                   9176:     /*   for(j=1; j<=nlstate;j++){ */
                   9177:     /*         printf("%d ",j); */
                   9178:     /*         for(theta=1; theta <=npar; theta++) */
                   9179:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   9180:     /*         printf("\n "); */
                   9181:     /*   } */
                   9182:     /* } */
                   9183: 
                   9184:     for(i=1;i<=nlstate;i++)
                   9185:       varbpl[i][(int)age] =0.;
                   9186:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   9187:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   9188:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   9189:     }else{
                   9190:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   9191:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   9192:     }
                   9193:     for(i=1;i<=nlstate;i++)
                   9194:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   9195: 
                   9196:     fprintf(ficresvbl,"%.0f ",age );
                   9197:     if(nresult >=1)
                   9198:       fprintf(ficresvbl,"%d ",nres );
                   9199:     for(i=1; i<=nlstate;i++)
                   9200:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   9201:     fprintf(ficresvbl,"\n");
                   9202:     free_vector(gp,1,nlstate);
                   9203:     free_vector(gm,1,nlstate);
                   9204:     free_matrix(mgm,1,npar,1,nlstate);
                   9205:     free_matrix(mgp,1,npar,1,nlstate);
                   9206:     free_matrix(gradg,1,npar,1,nlstate);
                   9207:     free_matrix(trgradg,1,nlstate,1,npar);
                   9208:   } /* End age */
                   9209: 
                   9210:   free_vector(xp,1,npar);
                   9211:   free_matrix(doldm,1,nlstate,1,npar);
                   9212:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  9213: 
                   9214: }
                   9215: 
                   9216: /************ Variance of one-step probabilities  ******************/
                   9217: 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  9218:  {
                   9219:    int i, j=0,  k1, l1, tj;
                   9220:    int k2, l2, j1,  z1;
                   9221:    int k=0, l;
                   9222:    int first=1, first1, first2;
1.326     brouard  9223:    int nres=0; /* New */
1.222     brouard  9224:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   9225:    double **dnewm,**doldm;
                   9226:    double *xp;
                   9227:    double *gp, *gm;
                   9228:    double **gradg, **trgradg;
                   9229:    double **mu;
                   9230:    double age, cov[NCOVMAX+1];
                   9231:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   9232:    int theta;
                   9233:    char fileresprob[FILENAMELENGTH];
                   9234:    char fileresprobcov[FILENAMELENGTH];
                   9235:    char fileresprobcor[FILENAMELENGTH];
                   9236:    double ***varpij;
                   9237: 
                   9238:    strcpy(fileresprob,"PROB_"); 
1.356     brouard  9239:    strcat(fileresprob,fileresu);
1.222     brouard  9240:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   9241:      printf("Problem with resultfile: %s\n", fileresprob);
                   9242:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   9243:    }
                   9244:    strcpy(fileresprobcov,"PROBCOV_"); 
                   9245:    strcat(fileresprobcov,fileresu);
                   9246:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   9247:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   9248:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   9249:    }
                   9250:    strcpy(fileresprobcor,"PROBCOR_"); 
                   9251:    strcat(fileresprobcor,fileresu);
                   9252:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   9253:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   9254:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   9255:    }
                   9256:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   9257:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   9258:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   9259:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   9260:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   9261:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   9262:    pstamp(ficresprob);
                   9263:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   9264:    fprintf(ficresprob,"# Age");
                   9265:    pstamp(ficresprobcov);
                   9266:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   9267:    fprintf(ficresprobcov,"# Age");
                   9268:    pstamp(ficresprobcor);
                   9269:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   9270:    fprintf(ficresprobcor,"# Age");
1.126     brouard  9271: 
                   9272: 
1.222     brouard  9273:    for(i=1; i<=nlstate;i++)
                   9274:      for(j=1; j<=(nlstate+ndeath);j++){
                   9275:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   9276:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   9277:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   9278:      }  
                   9279:    /* fprintf(ficresprob,"\n");
                   9280:       fprintf(ficresprobcov,"\n");
                   9281:       fprintf(ficresprobcor,"\n");
                   9282:    */
                   9283:    xp=vector(1,npar);
                   9284:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   9285:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   9286:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   9287:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   9288:    first=1;
                   9289:    fprintf(ficgp,"\n# Routine varprob");
                   9290:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   9291:    fprintf(fichtm,"\n");
                   9292: 
1.288     brouard  9293:    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  9294:    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);
                   9295:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  9296: and drawn. It helps understanding how is the covariance between two incidences.\
                   9297:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  9298:    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  9299: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   9300: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   9301: standard deviations wide on each axis. <br>\
                   9302:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   9303:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   9304: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   9305: 
1.222     brouard  9306:    cov[1]=1;
                   9307:    /* tj=cptcoveff; */
1.225     brouard  9308:    tj = (int) pow(2,cptcoveff);
1.222     brouard  9309:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   9310:    j1=0;
1.332     brouard  9311: 
                   9312:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   9313:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.342     brouard  9314:      /* 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  9315:      if(tj != 1 && TKresult[nres]!= j1)
                   9316:        continue;
                   9317: 
                   9318:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   9319:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   9320:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  9321:      if  (cptcovn>0) {
1.334     brouard  9322:        fprintf(ficresprob, "\n#********** Variable ");
                   9323:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   9324:        fprintf(ficgp, "\n#********** Variable ");
                   9325:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   9326:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   9327: 
                   9328:        /* Including quantitative variables of the resultline to be done */
                   9329:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
1.343     brouard  9330:         /* printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model); */
1.338     brouard  9331:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   9332:         /* 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  9333:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   9334:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   9335:             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  */
                   9336:             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  */
                   9337:             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  */
                   9338:             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  */
                   9339:             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  */
                   9340:             fprintf(ficresprob,"fixed ");
                   9341:             fprintf(ficresprobcov,"fixed ");
                   9342:             fprintf(ficgp,"fixed ");
                   9343:             fprintf(fichtmcov,"fixed ");
                   9344:             fprintf(ficresprobcor,"fixed ");
                   9345:           }else{
                   9346:             fprintf(ficresprob,"varyi ");
                   9347:             fprintf(ficresprobcov,"varyi ");
                   9348:             fprintf(ficgp,"varyi ");
                   9349:             fprintf(fichtmcov,"varyi ");
                   9350:             fprintf(ficresprobcor,"varyi ");
                   9351:           }
                   9352:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   9353:           /* For each selected (single) quantitative value */
1.337     brouard  9354:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
1.334     brouard  9355:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   9356:             fprintf(ficresprob,"fixed ");
                   9357:             fprintf(ficresprobcov,"fixed ");
                   9358:             fprintf(ficgp,"fixed ");
                   9359:             fprintf(fichtmcov,"fixed ");
                   9360:             fprintf(ficresprobcor,"fixed ");
                   9361:           }else{
                   9362:             fprintf(ficresprob,"varyi ");
                   9363:             fprintf(ficresprobcov,"varyi ");
                   9364:             fprintf(ficgp,"varyi ");
                   9365:             fprintf(fichtmcov,"varyi ");
                   9366:             fprintf(ficresprobcor,"varyi ");
                   9367:           }
                   9368:         }else{
                   9369:           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 */
                   9370:           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 */
                   9371:           exit(1);
                   9372:         }
                   9373:        } /* End loop on variable of this resultline */
                   9374:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  9375:        fprintf(ficresprob, "**********\n#\n");
                   9376:        fprintf(ficresprobcov, "**********\n#\n");
                   9377:        fprintf(ficgp, "**********\n#\n");
                   9378:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   9379:        fprintf(ficresprobcor, "**********\n#");    
                   9380:        if(invalidvarcomb[j1]){
                   9381:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   9382:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   9383:         continue;
                   9384:        }
                   9385:      }
                   9386:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   9387:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   9388:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   9389:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  9390:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  9391:        cov[2]=age;
                   9392:        if(nagesqr==1)
                   9393:         cov[3]= age*age;
1.334     brouard  9394:        /* New code end of combination but for each resultline */
                   9395:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  9396:         if(Typevar[k1]==1 || Typevar[k1] ==3){ /* A product with age */
1.334     brouard  9397:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  9398:         }else{
1.334     brouard  9399:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  9400:         }
1.334     brouard  9401:        }/* End of loop on model equation */
                   9402: /* Old code */
                   9403:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   9404:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   9405:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   9406:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   9407:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   9408:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   9409:        /*                                                                  * 1  1 1 1 1 */
                   9410:        /*                                                                  * 2  2 1 1 1 */
                   9411:        /*                                                                  * 3  1 2 1 1 */
                   9412:        /*                                                                  *\/ */
                   9413:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   9414:        /* } */
                   9415:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   9416:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   9417:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   9418:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   9419:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   9420:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   9421:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   9422:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   9423:        /*         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]); */
                   9424:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   9425:        /*         /\* exit(1); *\/ */
                   9426:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   9427:        /*       } */
                   9428:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   9429:        /* } */
                   9430:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   9431:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   9432:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   9433:        /*           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]])]; */
                   9434:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   9435:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   9436:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   9437:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   9438:        /*         } */
                   9439:        /*       }else{ */
                   9440:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   9441:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   9442:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   9443:        /*         }else{ */
                   9444:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   9445:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   9446:        /*         } */
                   9447:        /*       } */
                   9448:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   9449:        /* } */                 
1.326     brouard  9450: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  9451:        for(theta=1; theta <=npar; theta++){
                   9452:         for(i=1; i<=npar; i++)
                   9453:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  9454:                                
1.222     brouard  9455:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  9456:                                
1.222     brouard  9457:         k=0;
                   9458:         for(i=1; i<= (nlstate); i++){
                   9459:           for(j=1; j<=(nlstate+ndeath);j++){
                   9460:             k=k+1;
                   9461:             gp[k]=pmmij[i][j];
                   9462:           }
                   9463:         }
1.220     brouard  9464:                                
1.222     brouard  9465:         for(i=1; i<=npar; i++)
                   9466:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  9467:                                
1.222     brouard  9468:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   9469:         k=0;
                   9470:         for(i=1; i<=(nlstate); i++){
                   9471:           for(j=1; j<=(nlstate+ndeath);j++){
                   9472:             k=k+1;
                   9473:             gm[k]=pmmij[i][j];
                   9474:           }
                   9475:         }
1.220     brouard  9476:                                
1.222     brouard  9477:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   9478:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   9479:        }
1.126     brouard  9480: 
1.222     brouard  9481:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   9482:         for(theta=1; theta <=npar; theta++)
                   9483:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  9484:                        
1.222     brouard  9485:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   9486:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  9487:                        
1.222     brouard  9488:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  9489:                        
1.222     brouard  9490:        k=0;
                   9491:        for(i=1; i<=(nlstate); i++){
                   9492:         for(j=1; j<=(nlstate+ndeath);j++){
                   9493:           k=k+1;
                   9494:           mu[k][(int) age]=pmmij[i][j];
                   9495:         }
                   9496:        }
                   9497:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   9498:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   9499:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  9500:                        
1.222     brouard  9501:        /*printf("\n%d ",(int)age);
                   9502:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   9503:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   9504:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   9505:         }*/
1.220     brouard  9506:                        
1.222     brouard  9507:        fprintf(ficresprob,"\n%d ",(int)age);
                   9508:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   9509:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  9510:                        
1.222     brouard  9511:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   9512:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   9513:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   9514:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   9515:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   9516:        }
                   9517:        i=0;
                   9518:        for (k=1; k<=(nlstate);k++){
                   9519:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   9520:           i++;
                   9521:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   9522:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   9523:           for (j=1; j<=i;j++){
                   9524:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   9525:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   9526:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   9527:           }
                   9528:         }
                   9529:        }/* end of loop for state */
                   9530:      } /* end of loop for age */
                   9531:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   9532:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   9533:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   9534:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   9535:     
                   9536:      /* Confidence intervalle of pij  */
                   9537:      /*
                   9538:        fprintf(ficgp,"\nunset parametric;unset label");
                   9539:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   9540:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   9541:        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);
                   9542:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   9543:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   9544:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   9545:      */
                   9546:                
                   9547:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   9548:      first1=1;first2=2;
                   9549:      for (k2=1; k2<=(nlstate);k2++){
                   9550:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   9551:         if(l2==k2) continue;
                   9552:         j=(k2-1)*(nlstate+ndeath)+l2;
                   9553:         for (k1=1; k1<=(nlstate);k1++){
                   9554:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   9555:             if(l1==k1) continue;
                   9556:             i=(k1-1)*(nlstate+ndeath)+l1;
                   9557:             if(i<=j) continue;
                   9558:             for (age=bage; age<=fage; age ++){ 
                   9559:               if ((int)age %5==0){
                   9560:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   9561:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   9562:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   9563:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   9564:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   9565:                 c12=cv12/sqrt(v1*v2);
                   9566:                 /* Computing eigen value of matrix of covariance */
                   9567:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   9568:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   9569:                 if ((lc2 <0) || (lc1 <0) ){
                   9570:                   if(first2==1){
                   9571:                     first1=0;
                   9572:                     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);
                   9573:                   }
                   9574:                   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);
                   9575:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   9576:                   /* lc2=fabs(lc2); */
                   9577:                 }
1.220     brouard  9578:                                                                
1.222     brouard  9579:                 /* Eigen vectors */
1.280     brouard  9580:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   9581:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   9582:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   9583:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   9584:                 }else
                   9585:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  9586:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   9587:                 v21=(lc1-v1)/cv12*v11;
                   9588:                 v12=-v21;
                   9589:                 v22=v11;
                   9590:                 tnalp=v21/v11;
                   9591:                 if(first1==1){
                   9592:                   first1=0;
                   9593:                   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);
                   9594:                 }
                   9595:                 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);
                   9596:                 /*printf(fignu*/
                   9597:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   9598:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   9599:                 if(first==1){
                   9600:                   first=0;
                   9601:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   9602:                   fprintf(ficgp,"\nset parametric;unset label");
                   9603:                   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);
                   9604:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  9605:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  9606:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  9607: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  9608:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   9609:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   9610:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   9611:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   9612:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   9613:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   9614:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   9615:                   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  9616:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   9617:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  9618:                 }else{
                   9619:                   first=0;
                   9620:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   9621:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   9622:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   9623:                   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  9624:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   9625:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  9626:                 }/* if first */
                   9627:               } /* age mod 5 */
                   9628:             } /* end loop age */
                   9629:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   9630:             first=1;
                   9631:           } /*l12 */
                   9632:         } /* k12 */
                   9633:        } /*l1 */
                   9634:      }/* k1 */
1.332     brouard  9635:    }  /* loop on combination of covariates j1 */
1.326     brouard  9636:    } /* loop on nres */
1.222     brouard  9637:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   9638:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   9639:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   9640:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   9641:    free_vector(xp,1,npar);
                   9642:    fclose(ficresprob);
                   9643:    fclose(ficresprobcov);
                   9644:    fclose(ficresprobcor);
                   9645:    fflush(ficgp);
                   9646:    fflush(fichtmcov);
                   9647:  }
1.126     brouard  9648: 
                   9649: 
                   9650: /******************* Printing html file ***********/
1.201     brouard  9651: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  9652:                  int lastpass, int stepm, int weightopt, char model[],\
                   9653:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  9654:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   9655:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   9656:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.359     brouard  9657:   int jj1, k1, cpt, nres;
1.319     brouard  9658:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  9659:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   9660:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   9661: </ul>");
1.319     brouard  9662: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   9663: /* </ul>", model); */
1.214     brouard  9664:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   9665:    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",
                   9666:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  9667:    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  9668:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   9669:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  9670:    fprintf(fichtm,"\
                   9671:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  9672:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  9673:    fprintf(fichtm,"\
1.217     brouard  9674:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   9675:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   9676:    fprintf(fichtm,"\
1.288     brouard  9677:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  9678:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  9679:    fprintf(fichtm,"\
1.288     brouard  9680:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  9681:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   9682:    fprintf(fichtm,"\
1.211     brouard  9683:  - (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  9684:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  9685:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  9686:    if(prevfcast==1){
                   9687:      fprintf(fichtm,"\
                   9688:  - Prevalence projections by age and states:                           \
1.201     brouard  9689:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  9690:    }
1.126     brouard  9691: 
                   9692: 
1.225     brouard  9693:    m=pow(2,cptcoveff);
1.222     brouard  9694:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  9695: 
1.317     brouard  9696:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  9697: 
                   9698:    jj1=0;
                   9699: 
                   9700:    fprintf(fichtm," \n<ul>");
1.337     brouard  9701:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9702:      /* k1=nres; */
1.338     brouard  9703:      k1=TKresult[nres];
                   9704:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
1.337     brouard  9705:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   9706:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   9707:    /*     continue; */
1.264     brouard  9708:      jj1++;
                   9709:      if (cptcovn > 0) {
                   9710:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
1.337     brouard  9711:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   9712:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  9713:        }
1.337     brouard  9714:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   9715:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   9716:        /* } */
                   9717:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9718:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   9719:        /* } */
1.264     brouard  9720:        fprintf(fichtm,"\">");
                   9721:        
                   9722:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   9723:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  9724:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9725:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  9726:        }
1.337     brouard  9727:        /* fprintf(fichtm,"************ Results for covariates"); */
                   9728:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   9729:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   9730:        /* } */
                   9731:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9732:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   9733:        /* } */
1.264     brouard  9734:        if(invalidvarcomb[k1]){
                   9735:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   9736:         continue;
                   9737:        }
                   9738:        fprintf(fichtm,"</a></li>");
                   9739:      } /* cptcovn >0 */
                   9740:    }
1.317     brouard  9741:    fprintf(fichtm," \n</ul>");
1.264     brouard  9742: 
1.222     brouard  9743:    jj1=0;
1.237     brouard  9744: 
1.337     brouard  9745:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9746:      /* k1=nres; */
1.338     brouard  9747:      k1=TKresult[nres];
                   9748:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9749:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   9750:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   9751:    /*     continue; */
1.220     brouard  9752: 
1.222     brouard  9753:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   9754:      jj1++;
                   9755:      if (cptcovn > 0) {
1.264     brouard  9756:        fprintf(fichtm,"\n<p><a name=\"rescov");
1.337     brouard  9757:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9758:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  9759:        }
1.337     brouard  9760:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9761:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   9762:        /* } */
1.264     brouard  9763:        fprintf(fichtm,"\"</a>");
                   9764:  
1.222     brouard  9765:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  9766:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9767:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   9768:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  9769:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   9770:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  9771:        }
1.230     brouard  9772:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.338     brouard  9773:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  9774:        if(invalidvarcomb[k1]){
                   9775:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   9776:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   9777:         continue;
                   9778:        }
                   9779:      }
                   9780:      /* aij, bij */
1.259     brouard  9781:      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  9782: <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  9783:      /* Pij */
1.241     brouard  9784:      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> \
                   9785: <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  9786:      /* Quasi-incidences */
                   9787:      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  9788:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  9789:  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  9790: 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> \
                   9791: <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  9792:      /* Survival functions (period) in state j */
                   9793:      for(cpt=1; cpt<=nlstate;cpt++){
1.359     brouard  9794:        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  9795:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   9796:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  9797:      }
                   9798:      /* State specific survival functions (period) */
                   9799:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  9800:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
1.359     brouard  9801:  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  9802:  <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);
                   9803:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   9804:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  9805:      }
1.288     brouard  9806:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  9807:      for(cpt=1; cpt<=nlstate;cpt++){
1.359     brouard  9808:        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  9809:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
1.329     brouard  9810:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  9811:      }
1.296     brouard  9812:      if(prevbcast==1){
1.288     brouard  9813:        /* Backward prevalence in each health state */
1.222     brouard  9814:        for(cpt=1; cpt<=nlstate;cpt++){
1.338     brouard  9815:         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);
                   9816:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
                   9817:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  9818:        }
1.217     brouard  9819:      }
1.222     brouard  9820:      if(prevfcast==1){
1.288     brouard  9821:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  9822:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  9823:         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);
                   9824:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   9825:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   9826:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  9827:        }
                   9828:      }
1.296     brouard  9829:      if(prevbcast==1){
1.268     brouard  9830:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   9831:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  9832:         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  9833:  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 \
                   9834:  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  9835: 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);
                   9836:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   9837:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  9838:        }
                   9839:      }
1.220     brouard  9840:         
1.222     brouard  9841:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  9842:        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);
                   9843:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   9844:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  9845:      }
                   9846:      /* } /\* end i1 *\/ */
1.337     brouard  9847:    }/* End k1=nres */
1.222     brouard  9848:    fprintf(fichtm,"</ul>");
1.126     brouard  9849: 
1.222     brouard  9850:    fprintf(fichtm,"\
1.126     brouard  9851: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  9852:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  9853:  - 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  9854: But because parameters are usually highly correlated (a higher incidence of disability \
                   9855: and a higher incidence of recovery can give very close observed transition) it might \
                   9856: be very useful to look not only at linear confidence intervals estimated from the \
                   9857: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   9858: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   9859: covariance matrix of the one-step probabilities. \
                   9860: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  9861: 
1.222     brouard  9862:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   9863:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   9864:    fprintf(fichtm,"\
1.126     brouard  9865:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  9866:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  9867: 
1.222     brouard  9868:    fprintf(fichtm,"\
1.126     brouard  9869:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  9870:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   9871:    fprintf(fichtm,"\
1.126     brouard  9872:  - 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): \
                   9873:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  9874:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  9875:    fprintf(fichtm,"\
1.126     brouard  9876:  - (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): \
                   9877:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  9878:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  9879:    fprintf(fichtm,"\
1.288     brouard  9880:  - 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  9881:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   9882:    fprintf(fichtm,"\
1.128     brouard  9883:  - 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  9884:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   9885:    fprintf(fichtm,"\
1.288     brouard  9886:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  9887:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  9888: 
                   9889: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   9890: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   9891: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   9892: /*     <br>",fileres,fileres,fileres,fileres); */
                   9893: /*  else  */
1.338     brouard  9894: /*    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  9895:    fflush(fichtm);
1.126     brouard  9896: 
1.225     brouard  9897:    m=pow(2,cptcoveff);
1.222     brouard  9898:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  9899: 
1.317     brouard  9900:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   9901: 
                   9902:   jj1=0;
                   9903: 
                   9904:    fprintf(fichtm," \n<ul>");
1.337     brouard  9905:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9906:      /* k1=nres; */
1.338     brouard  9907:      k1=TKresult[nres];
1.337     brouard  9908:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   9909:      /* if(m != 1 && TKresult[nres]!= k1) */
                   9910:      /*   continue; */
1.317     brouard  9911:      jj1++;
                   9912:      if (cptcovn > 0) {
                   9913:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
1.337     brouard  9914:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9915:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  9916:        }
                   9917:        fprintf(fichtm,"\">");
                   9918:        
                   9919:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   9920:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  9921:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9922:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  9923:        }
                   9924:        if(invalidvarcomb[k1]){
                   9925:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   9926:         continue;
                   9927:        }
                   9928:        fprintf(fichtm,"</a></li>");
                   9929:      } /* cptcovn >0 */
1.337     brouard  9930:    } /* End nres */
1.317     brouard  9931:    fprintf(fichtm," \n</ul>");
                   9932: 
1.222     brouard  9933:    jj1=0;
1.237     brouard  9934: 
1.241     brouard  9935:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9936:      /* k1=nres; */
1.338     brouard  9937:      k1=TKresult[nres];
                   9938:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9939:      /* for(k1=1; k1<=m;k1++){ */
                   9940:      /* if(m != 1 && TKresult[nres]!= k1) */
                   9941:      /*   continue; */
1.222     brouard  9942:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   9943:      jj1++;
1.126     brouard  9944:      if (cptcovn > 0) {
1.317     brouard  9945:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
1.337     brouard  9946:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9947:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  9948:        }
                   9949:        fprintf(fichtm,"\"</a>");
                   9950:        
1.126     brouard  9951:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  9952:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
                   9953:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   9954:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  9955:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  9956:        }
1.237     brouard  9957: 
1.338     brouard  9958:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  9959: 
1.222     brouard  9960:        if(invalidvarcomb[k1]){
                   9961:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   9962:         continue;
                   9963:        }
1.337     brouard  9964:      } /* If cptcovn >0 */
1.126     brouard  9965:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  9966:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  9967: 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);
                   9968:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   9969:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  9970:      }
                   9971:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.360     brouard  9972: health expectancies in each live state (1 to %d) with confidence intervals \
                   9973: on left y-scale as well as proportions of time spent in each live state \
                   9974: (with confidence intervals) on right y-scale 0 to 100%%.\
                   9975:  If popbased=1 the smooth (due to the model)                           \
1.128     brouard  9976: true period expectancies (those weighted with period prevalences are also\
                   9977:  drawn in addition to the population based expectancies computed using\
1.314     brouard  9978:  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);
                   9979:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   9980:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  9981:      /* } /\* end i1 *\/ */
1.241     brouard  9982:   }/* End nres */
1.222     brouard  9983:    fprintf(fichtm,"</ul>");
                   9984:    fflush(fichtm);
1.126     brouard  9985: }
                   9986: 
                   9987: /******************* Gnuplot file **************/
1.296     brouard  9988: 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  9989: 
1.354     brouard  9990:   char dirfileres[256],optfileres[256];
                   9991:   char gplotcondition[256], gplotlabel[256];
1.343     brouard  9992:   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  9993:   int lv=0, vlv=0, kl=0;
1.130     brouard  9994:   int ng=0;
1.201     brouard  9995:   int vpopbased;
1.223     brouard  9996:   int ioffset; /* variable offset for columns */
1.270     brouard  9997:   int iyearc=1; /* variable column for year of projection  */
                   9998:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  9999:   int nres=0; /* Index of resultline */
1.266     brouard  10000:   int istart=1; /* For starting graphs in projections */
1.219     brouard  10001: 
1.126     brouard  10002: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   10003: /*     printf("Problem with file %s",optionfilegnuplot); */
                   10004: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   10005: /*   } */
                   10006: 
                   10007:   /*#ifdef windows */
                   10008:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  10009:   /*#endif */
1.225     brouard  10010:   m=pow(2,cptcoveff);
1.126     brouard  10011: 
1.274     brouard  10012:   /* diagram of the model */
                   10013:   fprintf(ficgp,"\n#Diagram of the model \n");
                   10014:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   10015:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   10016:   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);
                   10017: 
1.343     brouard  10018:   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  10019:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   10020:   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);
                   10021:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   10022:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   10023:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   10024:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   10025: 
1.202     brouard  10026:   /* Contribution to likelihood */
                   10027:   /* Plot the probability implied in the likelihood */
1.223     brouard  10028:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   10029:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   10030:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   10031:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  10032: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  10033:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   10034: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  10035:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   10036:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   10037:   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));
                   10038:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   10039:   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));
                   10040:   for (i=1; i<= nlstate ; i ++) {
                   10041:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   10042:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   10043:     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);
                   10044:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   10045:       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);
                   10046:     }
                   10047:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   10048:   }
                   10049:   /* 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 */               
                   10050:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   10051:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   10052:   fprintf(ficgp,"\nset out;unset log\n");
                   10053:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  10054: 
1.343     brouard  10055:   /* Plot the probability implied in the likelihood by covariate value */
                   10056:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
                   10057:   /* if(debugILK==1){ */
                   10058:   for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.347     brouard  10059:     kvar=Tvar[TvarFind[kf]]; /* variable name */
                   10060:     /* k=18+Tvar[TvarFind[kf]];/\*offset because there are 18 columns in the ILK_ file but could be placed else where *\/ */
1.350     brouard  10061:     /* k=18+kf;/\*offset because there are 18 columns in the ILK_ file *\/ */
1.356     brouard  10062:     /* k=19+kf;/\*offset because there are 19 columns in the ILK_ file *\/ */
1.355     brouard  10063:     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  10064:     for (i=1; i<= nlstate ; i ++) {
                   10065:       fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   10066:       fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
1.348     brouard  10067:       if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   10068:        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);
                   10069:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   10070:          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);
                   10071:        }
                   10072:       }else{
                   10073:        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);
                   10074:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   10075:          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);
                   10076:        }
1.343     brouard  10077:       }
                   10078:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   10079:     }
                   10080:   } /* End of each covariate dummy */
                   10081:   for(ncovv=1, iposold=0, kk=0; ncovv <= ncovvt ; ncovv++){
                   10082:     /* Other example        V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   10083:      *     kmodel       =     1   2     3     4         5        6        7       8        9
                   10084:      *  varying                   1     2                                 3       4        5
                   10085:      *  ncovv                     1     2                                3 4     5 6      7 8
                   10086:      * TvarVV[ncovv]             V3     5                                1 3     3 5      1 5
                   10087:      * TvarVVind[ncovv]=kmodel    2     3                                7 7     8 8      9 9
                   10088:      * TvarFind[kmodel]       1   0     0     0         0        0        0       0        0
                   10089:      * kdata     ncovcol=[V1 V2] nqv=0 ntv=[V3 V4] nqtv=V5
                   10090:      * Dummy[kmodel]          0   0     1     2         2        3        1       1        1
                   10091:      */
                   10092:     ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   10093:     kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   10094:     /* 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]); */
                   10095:     if(ipos!=iposold){ /* Not a product or first of a product */
                   10096:       /* printf(" %d",ipos); */
                   10097:       /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   10098:       /* printf(" DebugILK ficgp suite ipos=%d != iposold=%d\n", ipos, iposold); */
                   10099:       kk++; /* Position of the ncovv column in ILK_ */
                   10100:       k=18+ncovf+kk; /*offset because there are 18 columns in the ILK_ file plus ncovf fixed covariate */
                   10101:       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)  */
                   10102:        for (i=1; i<= nlstate ; i ++) {
                   10103:          fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   10104:          fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   10105: 
1.348     brouard  10106:            /* printf("Before DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
1.343     brouard  10107:          if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   10108:            /* printf("DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
                   10109:            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);
                   10110:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   10111:              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);
                   10112:            }
                   10113:          }else{
                   10114:            /* printf("DebugILK gnuplotversion=%g <5.2\n",gnuplotversion); */
                   10115:            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);
                   10116:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   10117:              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);
                   10118:            }
                   10119:          }
                   10120:          fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   10121:        }
                   10122:       }/* End if dummy varying */
                   10123:     }else{ /*Product */
                   10124:       /* printf("*"); */
                   10125:       /* fprintf(ficresilk,"*"); */
                   10126:     }
                   10127:     iposold=ipos;
                   10128:   } /* For each time varying covariate */
                   10129:   /* } /\* debugILK==1 *\/ */
                   10130:   /* 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 */               
                   10131:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   10132:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   10133:   fprintf(ficgp,"\nset out;unset log\n");
                   10134:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   10135: 
                   10136: 
                   10137:   
1.126     brouard  10138:   strcpy(dirfileres,optionfilefiname);
                   10139:   strcpy(optfileres,"vpl");
1.223     brouard  10140:   /* 1eme*/
1.238     brouard  10141:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
1.337     brouard  10142:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
1.236     brouard  10143:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10144:        k1=TKresult[nres];
1.338     brouard  10145:        if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.238     brouard  10146:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.337     brouard  10147:        /* if(m != 1 && TKresult[nres]!= k1) */
                   10148:        /*   continue; */
1.238     brouard  10149:        /* We are interested in selected combination by the resultline */
1.246     brouard  10150:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  10151:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  10152:        strcpy(gplotlabel,"(");
1.337     brouard  10153:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10154:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10155:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10156: 
                   10157:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
                   10158:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
                   10159:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10160:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10161:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10162:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10163:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
                   10164:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
                   10165:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
                   10166:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10167:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10168:        /* } */
                   10169:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10170:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
                   10171:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10172:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.264     brouard  10173:        }
                   10174:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  10175:        /* printf("\n#\n"); */
1.238     brouard  10176:        fprintf(ficgp,"\n#\n");
                   10177:        if(invalidvarcomb[k1]){
1.260     brouard  10178:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  10179:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10180:          continue;
                   10181:        }
1.235     brouard  10182:       
1.241     brouard  10183:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   10184:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  10185:        /* 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  10186:        fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  10187:        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);
                   10188:        /* 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); */
                   10189:       /* k1-1 error should be nres-1*/
1.238     brouard  10190:        for (i=1; i<= nlstate ; i ++) {
                   10191:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10192:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   10193:        }
1.288     brouard  10194:        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  10195:        for (i=1; i<= nlstate ; i ++) {
                   10196:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10197:          else fprintf(ficgp," %%*lf (%%*lf)");
                   10198:        } 
1.260     brouard  10199:        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  10200:        for (i=1; i<= nlstate ; i ++) {
                   10201:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10202:          else fprintf(ficgp," %%*lf (%%*lf)");
                   10203:        }  
1.265     brouard  10204:        /* 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)); */
                   10205:        
                   10206:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   10207:         if(cptcoveff ==0){
1.271     brouard  10208:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  10209:        }else{
                   10210:          kl=0;
                   10211:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  10212:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   10213:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  10214:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   10215:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   10216:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   10217:            vlv= nbcode[Tvaraff[k]][lv];
                   10218:            kl++;
                   10219:            /* 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 *\/ */
                   10220:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   10221:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   10222:            /* ''  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*/
                   10223:            if(k==cptcoveff){
                   10224:              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], \
                   10225:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   10226:            }else{
                   10227:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   10228:              kl++;
                   10229:            }
                   10230:          } /* end covariate */
                   10231:        } /* end if no covariate */
                   10232: 
1.296     brouard  10233:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  10234:          /* 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  10235:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  10236:          if(cptcoveff ==0){
1.245     brouard  10237:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  10238:          }else{
                   10239:            kl=0;
                   10240:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  10241:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   10242:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  10243:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   10244:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   10245:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  10246:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   10247:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  10248:              kl++;
1.238     brouard  10249:              /* 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 *\/ */
                   10250:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   10251:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   10252:              /* ''  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*/
                   10253:              if(k==cptcoveff){
1.245     brouard  10254:                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  10255:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  10256:              }else{
1.332     brouard  10257:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  10258:                kl++;
                   10259:              }
                   10260:            } /* end covariate */
                   10261:          } /* end if no covariate */
1.296     brouard  10262:          if(prevbcast == 1){
1.268     brouard  10263:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   10264:            /* k1-1 error should be nres-1*/
                   10265:            for (i=1; i<= nlstate ; i ++) {
                   10266:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10267:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   10268:            }
1.271     brouard  10269:            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  10270:            for (i=1; i<= nlstate ; i ++) {
                   10271:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10272:              else fprintf(ficgp," %%*lf (%%*lf)");
                   10273:            } 
1.276     brouard  10274:            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  10275:            for (i=1; i<= nlstate ; i ++) {
                   10276:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10277:              else fprintf(ficgp," %%*lf (%%*lf)");
                   10278:            } 
1.274     brouard  10279:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  10280:          } /* end if backprojcast */
1.296     brouard  10281:        } /* end if prevbcast */
1.276     brouard  10282:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   10283:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  10284:       } /* nres */
1.337     brouard  10285:     /* } /\* k1 *\/ */
1.201     brouard  10286:   } /* cpt */
1.235     brouard  10287: 
                   10288:   
1.126     brouard  10289:   /*2 eme*/
1.337     brouard  10290:   /* for (k1=1; k1<= m ; k1 ++){   */
1.238     brouard  10291:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10292:       k1=TKresult[nres];
1.338     brouard  10293:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10294:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10295:       /*       continue; */
1.238     brouard  10296:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  10297:       strcpy(gplotlabel,"(");
1.337     brouard  10298:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10299:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10300:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10301:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10302:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10303:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10304:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10305:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10306:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10307:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10308:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10309:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10310:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10311:       /* } */
                   10312:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
                   10313:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10314:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10315:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10316:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  10317:       }
1.264     brouard  10318:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  10319:       fprintf(ficgp,"\n#\n");
1.223     brouard  10320:       if(invalidvarcomb[k1]){
                   10321:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10322:        continue;
                   10323:       }
1.219     brouard  10324:                        
1.241     brouard  10325:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  10326:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  10327:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   10328:        if(vpopbased==0){
1.360     brouard  10329:          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  10330:        }else
1.238     brouard  10331:          fprintf(ficgp,"\nreplot ");
1.360     brouard  10332:        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  10333:          k=2*i;
1.360     brouard  10334:          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 */
                   10335:          for (j=1; j<= nlstate+1 ; j ++) { /* e.. e.1 e.2 again j-1 is the state of end, wlim_i eij*/
                   10336:            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 */
                   10337:            else fprintf(ficgp," %%*lf (%%*lf)");  /* skipping that field with a star */
1.238     brouard  10338:          }   
                   10339:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
1.360     brouard  10340:          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  10341:          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  10342:          for (j=1; j<= nlstate+1 ; j ++) {
                   10343:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   10344:            else fprintf(ficgp," %%*lf (%%*lf)");
                   10345:          }   
                   10346:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  10347:          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  10348:          for (j=1; j<= nlstate+1 ; j ++) {
                   10349:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   10350:            else fprintf(ficgp," %%*lf (%%*lf)");
                   10351:          }   
1.360     brouard  10352:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0,\\\n"); /* ,\\\n added for th percentage graphs */
1.238     brouard  10353:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   10354:        } /* state */
1.360     brouard  10355:        /* again for the percentag spent in state i-1=1 to i-1=nlstate */
                   10356:        for (i=2; i<= nlstate+1 ; i ++) { /* For state i-1=0 is LE, while i-1=1 to nlstate are origin state */
                   10357:          k=2*i;
                   10358:          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 */
                   10359:          for (j=1; j<= nlstate ; j ++)
                   10360:            fprintf(ficgp," %%*lf (%%*lf)"); /* Skipping TLE and LE to read %LE only */
                   10361:          for (j=1; j<= nlstate+1 ; j ++) { /* e.. e.1 e.2 again j-1 is the state of end, wlim_i eij*/
                   10362:            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 */
                   10363:            else fprintf(ficgp," %%*lf (%%*lf)");  /* skipping that field with a star */
                   10364:          }   
                   10365:          if (i== 1) fprintf(ficgp,"\" t\"%%TLE\" w l lt %d axis x1y2, \\\n",i); /* Not used */
                   10366:          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  */
                   10367:          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);
                   10368:          for (j=1; j<= nlstate ; j ++)
                   10369:            fprintf(ficgp," %%*lf (%%*lf)"); /* Skipping TLE and LE to read %LE only */
                   10370:          for (j=1; j<= nlstate+1 ; j ++) {
                   10371:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   10372:            else fprintf(ficgp," %%*lf (%%*lf)");
                   10373:          }   
                   10374:          fprintf(ficgp,"\" t\"\" w l lt 0 axis x1y2,");
                   10375:          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);
                   10376:          for (j=1; j<= nlstate ; j ++)
                   10377:            fprintf(ficgp," %%*lf (%%*lf)"); /* Skipping TLE and LE to read %LE only */
                   10378:          for (j=1; j<= nlstate+1 ; j ++) {
                   10379:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   10380:            else fprintf(ficgp," %%*lf (%%*lf)");
                   10381:          }   
                   10382:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0 axis x1y2");
                   10383:          else fprintf(ficgp,"\" t\"\" w l lt 0 axis x1y2,\\\n");
                   10384:        } /* state for percent */
1.238     brouard  10385:       } /* vpopbased */
1.264     brouard  10386:       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  10387:     } /* end nres */
1.337     brouard  10388:   /* } /\* k1 end 2 eme*\/ */
1.238     brouard  10389:        
                   10390:        
                   10391:   /*3eme*/
1.337     brouard  10392:   /* for (k1=1; k1<= m ; k1 ++){ */
1.238     brouard  10393:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10394:       k1=TKresult[nres];
1.338     brouard  10395:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10396:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10397:       /*       continue; */
1.238     brouard  10398: 
1.332     brouard  10399:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  10400:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  10401:        strcpy(gplotlabel,"(");
1.337     brouard  10402:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10403:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10404:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10405:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10406:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10407:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   10408:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10409:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10410:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10411:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10412:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10413:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10414:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10415:        /* } */
                   10416:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10417:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   10418:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   10419:        }
1.264     brouard  10420:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  10421:        fprintf(ficgp,"\n#\n");
                   10422:        if(invalidvarcomb[k1]){
                   10423:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10424:          continue;
                   10425:        }
                   10426:                        
                   10427:        /*       k=2+nlstate*(2*cpt-2); */
                   10428:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  10429:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  10430:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  10431:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  10432: 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  10433:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   10434:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   10435:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   10436:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   10437:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   10438:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  10439:                                
1.238     brouard  10440:        */
                   10441:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  10442:          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  10443:          /*    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  10444:                                
1.238     brouard  10445:        } 
1.261     brouard  10446:        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  10447:       }
1.264     brouard  10448:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  10449:     } /* end nres */
1.337     brouard  10450:   /* } /\* end kl 3eme *\/ */
1.126     brouard  10451:   
1.223     brouard  10452:   /* 4eme */
1.201     brouard  10453:   /* Survival functions (period) from state i in state j by initial state i */
1.337     brouard  10454:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
1.238     brouard  10455:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10456:       k1=TKresult[nres];
1.338     brouard  10457:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10458:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10459:       /*       continue; */
1.238     brouard  10460:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  10461:        strcpy(gplotlabel,"(");
1.337     brouard  10462:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
                   10463:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10464:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10465:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10466:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10467:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10468:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10469:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10470:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10471:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10472:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10473:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10474:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10475:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10476:        /* } */
                   10477:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10478:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10479:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  10480:        }       
1.264     brouard  10481:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  10482:        fprintf(ficgp,"\n#\n");
                   10483:        if(invalidvarcomb[k1]){
                   10484:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10485:          continue;
1.223     brouard  10486:        }
1.238     brouard  10487:       
1.241     brouard  10488:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  10489:        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  10490:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   10491: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   10492:        k=3;
                   10493:        for (i=1; i<= nlstate ; i ++){
                   10494:          if(i==1){
                   10495:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   10496:          }else{
                   10497:            fprintf(ficgp,", '' ");
                   10498:          }
                   10499:          l=(nlstate+ndeath)*(i-1)+1;
                   10500:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   10501:          for (j=2; j<= nlstate+ndeath ; j ++)
                   10502:            fprintf(ficgp,"+$%d",k+l+j-1);
                   10503:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   10504:        } /* nlstate */
1.264     brouard  10505:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  10506:       } /* end cpt state*/ 
                   10507:     } /* end nres */
1.337     brouard  10508:   /* } /\* end covariate k1 *\/   */
1.238     brouard  10509: 
1.220     brouard  10510: /* 5eme */
1.201     brouard  10511:   /* Survival functions (period) from state i in state j by final state j */
1.337     brouard  10512:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
1.238     brouard  10513:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10514:       k1=TKresult[nres];
1.338     brouard  10515:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10516:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10517:       /*       continue; */
1.238     brouard  10518:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  10519:        strcpy(gplotlabel,"(");
1.238     brouard  10520:        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  10521:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10522:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10523:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10524:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10525:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10526:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10527:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10528:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10529:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10530:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10531:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10532:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10533:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10534:        /* } */
                   10535:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10536:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10537:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  10538:        }       
1.264     brouard  10539:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  10540:        fprintf(ficgp,"\n#\n");
                   10541:        if(invalidvarcomb[k1]){
                   10542:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10543:          continue;
                   10544:        }
1.227     brouard  10545:       
1.241     brouard  10546:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  10547:        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  10548:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   10549: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   10550:        k=3;
                   10551:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   10552:          if(j==1)
                   10553:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   10554:          else
                   10555:            fprintf(ficgp,", '' ");
                   10556:          l=(nlstate+ndeath)*(cpt-1) +j;
                   10557:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   10558:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   10559:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   10560:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   10561:        } /* nlstate */
                   10562:        fprintf(ficgp,", '' ");
                   10563:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   10564:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   10565:          l=(nlstate+ndeath)*(cpt-1) +j;
                   10566:          if(j < nlstate)
                   10567:            fprintf(ficgp,"$%d +",k+l);
                   10568:          else
                   10569:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   10570:        }
1.264     brouard  10571:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  10572:       } /* end cpt state*/ 
1.337     brouard  10573:     /* } /\* end covariate *\/   */
1.238     brouard  10574:   } /* end nres */
1.227     brouard  10575:   
1.220     brouard  10576: /* 6eme */
1.202     brouard  10577:   /* CV preval stable (period) for each covariate */
1.337     brouard  10578:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  10579:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10580:      k1=TKresult[nres];
1.338     brouard  10581:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10582:      /* if(m != 1 && TKresult[nres]!= k1) */
                   10583:      /*  continue; */
1.255     brouard  10584:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  10585:       strcpy(gplotlabel,"(");      
1.288     brouard  10586:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  10587:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10588:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10589:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10590:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10591:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10592:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10593:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10594:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10595:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10596:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10597:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10598:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10599:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10600:       /* } */
                   10601:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10602:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10603:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  10604:       }        
1.264     brouard  10605:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  10606:       fprintf(ficgp,"\n#\n");
1.223     brouard  10607:       if(invalidvarcomb[k1]){
1.227     brouard  10608:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10609:        continue;
1.223     brouard  10610:       }
1.227     brouard  10611:       
1.241     brouard  10612:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  10613:       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  10614:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  10615: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  10616:       k=3; /* Offset */
1.255     brouard  10617:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  10618:        if(i==1)
                   10619:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   10620:        else
                   10621:          fprintf(ficgp,", '' ");
1.255     brouard  10622:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  10623:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   10624:        for (j=2; j<= nlstate ; j ++)
                   10625:          fprintf(ficgp,"+$%d",k+l+j-1);
                   10626:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  10627:       } /* nlstate */
1.264     brouard  10628:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  10629:     } /* end cpt state*/ 
                   10630:   } /* end covariate */  
1.227     brouard  10631:   
                   10632:   
1.220     brouard  10633: /* 7eme */
1.296     brouard  10634:   if(prevbcast == 1){
1.288     brouard  10635:     /* CV backward prevalence  for each covariate */
1.337     brouard  10636:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  10637:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10638:       k1=TKresult[nres];
1.338     brouard  10639:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10640:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10641:       /*       continue; */
1.268     brouard  10642:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  10643:        strcpy(gplotlabel,"(");      
1.288     brouard  10644:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  10645:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10646:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10647:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10648:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10649:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10650:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10651:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10652:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10653:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10654:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10655:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10656:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10657:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10658:        /* } */
                   10659:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10660:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10661:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  10662:        }       
1.264     brouard  10663:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  10664:        fprintf(ficgp,"\n#\n");
                   10665:        if(invalidvarcomb[k1]){
                   10666:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10667:          continue;
                   10668:        }
                   10669:        
1.241     brouard  10670:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  10671:        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  10672:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  10673: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  10674:        k=3; /* Offset */
1.268     brouard  10675:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  10676:          if(i==1)
                   10677:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   10678:          else
                   10679:            fprintf(ficgp,", '' ");
                   10680:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  10681:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  10682:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   10683:          /* 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  10684:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  10685:          /* for (j=2; j<= nlstate ; j ++) */
                   10686:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   10687:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  10688:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  10689:        } /* nlstate */
1.264     brouard  10690:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  10691:       } /* end cpt state*/ 
                   10692:     } /* end covariate */  
1.296     brouard  10693:   } /* End if prevbcast */
1.218     brouard  10694:   
1.223     brouard  10695:   /* 8eme */
1.218     brouard  10696:   if(prevfcast==1){
1.288     brouard  10697:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  10698:     
1.337     brouard  10699:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  10700:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10701:       k1=TKresult[nres];
1.338     brouard  10702:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10703:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10704:       /*       continue; */
1.211     brouard  10705:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  10706:        strcpy(gplotlabel,"(");      
1.288     brouard  10707:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  10708:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10709:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10710:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10711:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   10712:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   10713:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10714:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10715:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10716:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10717:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10718:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10719:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10720:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10721:        /* } */
                   10722:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10723:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10724:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  10725:        }       
1.264     brouard  10726:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  10727:        fprintf(ficgp,"\n#\n");
                   10728:        if(invalidvarcomb[k1]){
                   10729:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10730:          continue;
                   10731:        }
                   10732:        
                   10733:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  10734:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  10735:        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  10736:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  10737: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  10738: 
                   10739:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   10740:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   10741:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   10742:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  10743:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10744:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   10745:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10746:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  10747:          if(i==istart){
1.227     brouard  10748:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   10749:          }else{
                   10750:            fprintf(ficgp,",\\\n '' ");
                   10751:          }
                   10752:          if(cptcoveff ==0){ /* No covariate */
                   10753:            ioffset=2; /* Age is in 2 */
                   10754:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   10755:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   10756:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   10757:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   10758:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  10759:            if(i==nlstate+1){
1.270     brouard  10760:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  10761:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   10762:              fprintf(ficgp,",\\\n '' ");
                   10763:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  10764:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  10765:                     offyear,                           \
1.268     brouard  10766:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  10767:            }else
1.227     brouard  10768:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   10769:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   10770:          }else{ /* more than 2 covariates */
1.270     brouard  10771:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   10772:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10773:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   10774:            iyearc=ioffset-1;
                   10775:            iagec=ioffset;
1.227     brouard  10776:            fprintf(ficgp," u %d:(",ioffset); 
                   10777:            kl=0;
                   10778:            strcpy(gplotcondition,"(");
1.351     brouard  10779:            /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
1.332     brouard  10780:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
1.351     brouard  10781:            for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10782:              /* lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10783:              lv=Tvresult[nres][k];
                   10784:              vlv=TinvDoQresult[nres][Tvresult[nres][k]];
1.227     brouard  10785:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   10786:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   10787:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  10788:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
1.351     brouard  10789:              /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
1.227     brouard  10790:              kl++;
1.364   ! brouard  10791:              /* Problem with quantitative variables TinvDoQresult[nres] */
1.351     brouard  10792:              /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
1.364   ! brouard  10793:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,lv, kl+1, vlv );/* Solved but quantitative must be shifted */
1.227     brouard  10794:              kl++;
1.351     brouard  10795:              if(k <cptcovs && cptcovs>1)
1.227     brouard  10796:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   10797:            }
                   10798:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   10799:            /* 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 *\/ */
                   10800:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   10801:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   10802:            /* ''  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*/
                   10803:            if(i==nlstate+1){
1.270     brouard  10804:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   10805:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  10806:              fprintf(ficgp,",\\\n '' ");
1.364   ! brouard  10807:              fprintf(ficgp," u %d:(",iagec); /* Below iyearc should be increades if quantitative variable in the reult line */
        !          10808:              /* $7==6 && $8==2.47 ) && (($9-$10) == 1953 ) ? $12/(1.-$24) : 1/0):7 with labels center not */
        !          10809:              /* but was  && $7==6 && $8==2 ) && (($7-$8) == 1953 ) ? $12/(1.-$24) : 1/0):7 with labels center not */
1.270     brouard  10810:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   10811:                      iyearc, iagec, offyear,                           \
                   10812:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  10813: /*  '' 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  10814:            }else{
                   10815:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   10816:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   10817:            }
                   10818:          } /* end if covariate */
                   10819:        } /* nlstate */
1.264     brouard  10820:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  10821:       } /* end cpt state*/
                   10822:     } /* end covariate */
                   10823:   } /* End if prevfcast */
1.227     brouard  10824:   
1.296     brouard  10825:   if(prevbcast==1){
1.268     brouard  10826:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   10827:     
1.337     brouard  10828:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.268     brouard  10829:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10830:      k1=TKresult[nres];
1.338     brouard  10831:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10832:        /* if(m != 1 && TKresult[nres]!= k1) */
                   10833:        /*      continue; */
1.268     brouard  10834:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   10835:        strcpy(gplotlabel,"(");      
                   10836:        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  10837:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10838:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10839:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10840:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   10841:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   10842:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   10843:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10844:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10845:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10846:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10847:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10848:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10849:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10850:        /* } */
                   10851:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10852:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10853:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.268     brouard  10854:        }       
                   10855:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   10856:        fprintf(ficgp,"\n#\n");
                   10857:        if(invalidvarcomb[k1]){
                   10858:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10859:          continue;
                   10860:        }
                   10861:        
                   10862:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   10863:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   10864:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   10865:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   10866: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   10867: 
                   10868:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   10869:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   10870:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   10871:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   10872:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10873:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   10874:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10875:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   10876:          if(i==istart){
                   10877:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   10878:          }else{
                   10879:            fprintf(ficgp,",\\\n '' ");
                   10880:          }
1.351     brouard  10881:          /* if(cptcoveff ==0){ /\* No covariate *\/ */
                   10882:          if(cptcovs ==0){ /* No covariate */
1.268     brouard  10883:            ioffset=2; /* Age is in 2 */
                   10884:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   10885:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   10886:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   10887:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   10888:            fprintf(ficgp," u %d:(", ioffset); 
                   10889:            if(i==nlstate+1){
1.270     brouard  10890:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  10891:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   10892:              fprintf(ficgp,",\\\n '' ");
                   10893:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  10894:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  10895:                     offbyear,                          \
                   10896:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   10897:            }else
                   10898:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   10899:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   10900:          }else{ /* more than 2 covariates */
1.270     brouard  10901:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   10902:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10903:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   10904:            iyearc=ioffset-1;
                   10905:            iagec=ioffset;
1.268     brouard  10906:            fprintf(ficgp," u %d:(",ioffset); 
                   10907:            kl=0;
                   10908:            strcpy(gplotcondition,"(");
1.337     brouard  10909:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
1.338     brouard  10910:              if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
1.337     brouard  10911:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
                   10912:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   10913:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   10914:                lv=Tvresult[nres][k];
                   10915:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
                   10916:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   10917:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   10918:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   10919:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   10920:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10921:                kl++;
                   10922:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   10923:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
                   10924:                kl++;
1.338     brouard  10925:                if(k <cptcovs && cptcovs>1)
1.337     brouard  10926:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   10927:              }
1.268     brouard  10928:            }
                   10929:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   10930:            /* 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 *\/ */
                   10931:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   10932:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   10933:            /* ''  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*/
                   10934:            if(i==nlstate+1){
1.270     brouard  10935:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   10936:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  10937:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  10938:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  10939:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  10940:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   10941:                      iyearc,iagec,offbyear,                            \
                   10942:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  10943: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   10944:            }else{
                   10945:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   10946:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   10947:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   10948:            }
                   10949:          } /* end if covariate */
                   10950:        } /* nlstate */
                   10951:        fprintf(ficgp,"\nset out; unset label;\n");
                   10952:       } /* end cpt state*/
                   10953:     } /* end covariate */
1.296     brouard  10954:   } /* End if prevbcast */
1.268     brouard  10955:   
1.227     brouard  10956:   
1.238     brouard  10957:   /* 9eme writing MLE parameters */
                   10958:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  10959:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  10960:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  10961:     for(k=1; k <=(nlstate+ndeath); k++){
                   10962:       if (k != i) {
1.227     brouard  10963:        fprintf(ficgp,"#   current state %d\n",k);
                   10964:        for(j=1; j <=ncovmodel; j++){
                   10965:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   10966:          jk++; 
                   10967:        }
                   10968:        fprintf(ficgp,"\n");
1.126     brouard  10969:       }
                   10970:     }
1.223     brouard  10971:   }
1.187     brouard  10972:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  10973:   
1.145     brouard  10974:   /*goto avoid;*/
1.238     brouard  10975:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   10976:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  10977:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   10978:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   10979:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   10980:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   10981:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   10982:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   10983:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   10984:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   10985:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   10986:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   10987:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   10988:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   10989:   fprintf(ficgp,"#\n");
1.223     brouard  10990:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  10991:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.338     brouard  10992:     fprintf(ficgp,"#model=1+age+%s \n",model);
1.238     brouard  10993:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.351     brouard  10994:     /* fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/\* to be checked *\/ */
                   10995:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcovs,m);/* to be checked */
1.337     brouard  10996:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
1.237     brouard  10997:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10998:      /* k1=nres; */
1.338     brouard  10999:       k1=TKresult[nres];
                   11000:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  11001:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
1.264     brouard  11002:       strcpy(gplotlabel,"(");
1.276     brouard  11003:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.337     brouard  11004:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   11005:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
                   11006:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
                   11007:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   11008:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   11009:       }
                   11010:       /* if(m != 1 && TKresult[nres]!= k1) */
                   11011:       /*       continue; */
                   11012:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
                   11013:       /* strcpy(gplotlabel,"("); */
                   11014:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
                   11015:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   11016:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   11017:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   11018:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   11019:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   11020:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   11021:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   11022:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   11023:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   11024:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   11025:       /* } */
                   11026:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11027:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   11028:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   11029:       /* }      */
1.264     brouard  11030:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  11031:       fprintf(ficgp,"\n#\n");
1.264     brouard  11032:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  11033:       fprintf(ficgp,"\nset key outside ");
                   11034:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   11035:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  11036:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   11037:       if (ng==1){
                   11038:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   11039:        fprintf(ficgp,"\nunset log y");
                   11040:       }else if (ng==2){
                   11041:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   11042:        fprintf(ficgp,"\nset log y");
                   11043:       }else if (ng==3){
                   11044:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   11045:        fprintf(ficgp,"\nset log y");
                   11046:       }else
                   11047:        fprintf(ficgp,"\nunset title ");
                   11048:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   11049:       i=1;
                   11050:       for(k2=1; k2<=nlstate; k2++) {
                   11051:        k3=i;
                   11052:        for(k=1; k<=(nlstate+ndeath); k++) {
                   11053:          if (k != k2){
                   11054:            switch( ng) {
                   11055:            case 1:
                   11056:              if(nagesqr==0)
                   11057:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   11058:              else /* nagesqr =1 */
                   11059:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   11060:              break;
                   11061:            case 2: /* ng=2 */
                   11062:              if(nagesqr==0)
                   11063:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   11064:              else /* nagesqr =1 */
                   11065:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   11066:              break;
                   11067:            case 3:
                   11068:              if(nagesqr==0)
                   11069:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   11070:              else /* nagesqr =1 */
                   11071:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   11072:              break;
                   11073:            }
                   11074:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  11075:            ijp=1; /* product no age */
                   11076:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   11077:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  11078:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  11079:              switch(Typevar[j]){
                   11080:              case 1:
                   11081:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   11082:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   11083:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   11084:                      if(DummyV[j]==0){/* Bug valgrind */
                   11085:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   11086:                      }else{ /* quantitative */
                   11087:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   11088:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   11089:                      }
                   11090:                      ij++;
1.268     brouard  11091:                    }
1.237     brouard  11092:                  }
1.329     brouard  11093:                }
                   11094:                break;
                   11095:              case 2:
                   11096:                if(cptcovprod >0){
                   11097:                  if(j==Tprod[ijp]) { /* */ 
                   11098:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   11099:                    if(ijp <=cptcovprod) { /* Product */
                   11100:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   11101:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   11102:                          /* 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)]); */
                   11103:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   11104:                        }else{ /* Vn is dummy and Vm is quanti */
                   11105:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11106:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   11107:                        }
                   11108:                      }else{ /* Vn*Vm Vn is quanti */
                   11109:                        if(DummyV[Tvard[ijp][2]]==0){
                   11110:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   11111:                        }else{ /* Both quanti */
                   11112:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   11113:                        }
1.268     brouard  11114:                      }
1.329     brouard  11115:                      ijp++;
1.237     brouard  11116:                    }
1.329     brouard  11117:                  } /* end Tprod */
                   11118:                }
                   11119:                break;
1.349     brouard  11120:              case 3:
                   11121:                if(cptcovdageprod >0){
                   11122:                  /* if(j==Tprod[ijp]) { */ /* not necessary */ 
                   11123:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
1.350     brouard  11124:                    if(ijp <=cptcovprod) { /* Product Vn*Vm and age*VN*Vm*/
                   11125:                      if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   11126:                        if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  11127:                          /* 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)]); */
                   11128:                          fprintf(ficgp,"+p%d*%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   11129:                        }else{ /* Vn is dummy and Vm is quanti */
                   11130:                          /* 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  11131:                          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  11132:                        }
1.350     brouard  11133:                      }else{ /* age* Vn*Vm Vn is quanti HERE */
1.349     brouard  11134:                        if(DummyV[Tvard[ijp][2]]==0){
1.350     brouard  11135:                          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  11136:                        }else{ /* Both quanti */
1.350     brouard  11137:                          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  11138:                        }
                   11139:                      }
                   11140:                      ijp++;
                   11141:                    }
                   11142:                    /* } */ /* end Tprod */
                   11143:                }
                   11144:                break;
1.329     brouard  11145:              case 0:
                   11146:                /* simple covariate */
1.264     brouard  11147:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  11148:                if(Dummy[j]==0){
                   11149:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   11150:                }else{ /* quantitative */
                   11151:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  11152:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  11153:                }
1.329     brouard  11154:               /* end simple */
                   11155:                break;
                   11156:              default:
                   11157:                break;
                   11158:              } /* end switch */
1.237     brouard  11159:            } /* end j */
1.329     brouard  11160:          }else{ /* k=k2 */
                   11161:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   11162:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   11163:            }else
                   11164:              i=i-ncovmodel;
1.223     brouard  11165:          }
1.227     brouard  11166:          
1.223     brouard  11167:          if(ng != 1){
                   11168:            fprintf(ficgp,")/(1");
1.227     brouard  11169:            
1.264     brouard  11170:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  11171:              if(nagesqr==0)
1.264     brouard  11172:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  11173:              else /* nagesqr =1 */
1.264     brouard  11174:                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  11175:               
1.223     brouard  11176:              ij=1;
1.329     brouard  11177:              ijp=1;
                   11178:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   11179:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   11180:                switch(Typevar[j]){
                   11181:                case 1:
                   11182:                  if(cptcovage >0){ 
                   11183:                    if(j==Tage[ij]) { /* Bug valgrind */
                   11184:                      if(ij <=cptcovage) { /* Bug valgrind */
                   11185:                        if(DummyV[j]==0){/* Bug valgrind */
                   11186:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   11187:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   11188:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   11189:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   11190:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   11191:                        }else{ /* quantitative */
                   11192:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   11193:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   11194:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   11195:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   11196:                        }
                   11197:                        ij++;
                   11198:                      }
                   11199:                    }
                   11200:                  }
                   11201:                  break;
                   11202:                case 2:
                   11203:                  if(cptcovprod >0){
                   11204:                    if(j==Tprod[ijp]) { /* */ 
                   11205:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   11206:                      if(ijp <=cptcovprod) { /* Product */
                   11207:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   11208:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   11209:                            /* 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)]); */
                   11210:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   11211:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   11212:                          }else{ /* Vn is dummy and Vm is quanti */
                   11213:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11214:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   11215:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11216:                          }
                   11217:                        }else{ /* Vn*Vm Vn is quanti */
                   11218:                          if(DummyV[Tvard[ijp][2]]==0){
                   11219:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   11220:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   11221:                          }else{ /* Both quanti */
                   11222:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   11223:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11224:                          } 
                   11225:                        }
                   11226:                        ijp++;
                   11227:                      }
                   11228:                    } /* end Tprod */
                   11229:                  } /* end if */
                   11230:                  break;
1.349     brouard  11231:                case 3:
                   11232:                  if(cptcovdageprod >0){
                   11233:                    /* if(j==Tprod[ijp]) { /\* *\/  */
                   11234:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   11235:                      if(ijp <=cptcovprod) { /* Product */
1.350     brouard  11236:                        if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   11237:                          if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  11238:                            /* 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  11239:                            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  11240:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   11241:                          }else{ /* Vn is dummy and Vm is quanti */
                   11242:                            /* 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  11243:                            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  11244:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11245:                          }
                   11246:                        }else{ /* Vn*Vm Vn is quanti */
1.350     brouard  11247:                          if(DummyV[Tvardk[ijp][2]]==0){
                   11248:                            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  11249:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   11250:                          }else{ /* Both quanti */
1.350     brouard  11251:                            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  11252:                            /* fprintf(ficgp,"+p%d*%f*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11253:                          } 
                   11254:                        }
                   11255:                        ijp++;
                   11256:                      }
                   11257:                    /* } /\* end Tprod *\/ */
                   11258:                  } /* end if */
                   11259:                  break;
1.329     brouard  11260:                case 0: 
                   11261:                  /* simple covariate */
                   11262:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   11263:                  if(Dummy[j]==0){
                   11264:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   11265:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   11266:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   11267:                  }else{ /* quantitative */
                   11268:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   11269:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   11270:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   11271:                  }
                   11272:                  /* end simple */
                   11273:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   11274:                  break;
                   11275:                default:
                   11276:                  break;
                   11277:                } /* end switch */
1.223     brouard  11278:              }
                   11279:              fprintf(ficgp,")");
                   11280:            }
                   11281:            fprintf(ficgp,")");
                   11282:            if(ng ==2)
1.276     brouard  11283:              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  11284:            else /* ng= 3 */
1.276     brouard  11285:              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  11286:           }else{ /* end ng <> 1 */
1.223     brouard  11287:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  11288:              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  11289:          }
                   11290:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   11291:            fprintf(ficgp,",");
                   11292:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   11293:            fprintf(ficgp,",");
                   11294:          i=i+ncovmodel;
                   11295:        } /* end k */
                   11296:       } /* end k2 */
1.276     brouard  11297:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   11298:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.337     brouard  11299:     } /* end resultline */
1.223     brouard  11300:   } /* end ng */
                   11301:   /* avoid: */
                   11302:   fflush(ficgp); 
1.126     brouard  11303: }  /* end gnuplot */
                   11304: 
                   11305: 
                   11306: /*************** Moving average **************/
1.219     brouard  11307: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  11308:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  11309:    
1.222     brouard  11310:    int i, cpt, cptcod;
                   11311:    int modcovmax =1;
                   11312:    int mobilavrange, mob;
                   11313:    int iage=0;
1.288     brouard  11314:    int firstA1=0, firstA2=0;
1.222     brouard  11315: 
1.266     brouard  11316:    double sum=0., sumr=0.;
1.222     brouard  11317:    double age;
1.266     brouard  11318:    double *sumnewp, *sumnewm, *sumnewmr;
                   11319:    double *agemingood, *agemaxgood; 
                   11320:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  11321:   
                   11322:   
1.278     brouard  11323:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   11324:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  11325: 
                   11326:    sumnewp = vector(1,ncovcombmax);
                   11327:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  11328:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  11329:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  11330:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  11331:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  11332:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  11333: 
                   11334:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  11335:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  11336:      sumnewp[cptcod]=0.;
1.266     brouard  11337:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   11338:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  11339:    }
                   11340:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   11341:   
1.266     brouard  11342:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   11343:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  11344:      else mobilavrange=mobilav;
                   11345:      for (age=bage; age<=fage; age++)
                   11346:        for (i=1; i<=nlstate;i++)
                   11347:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   11348:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   11349:      /* We keep the original values on the extreme ages bage, fage and for 
                   11350:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   11351:        we use a 5 terms etc. until the borders are no more concerned. 
                   11352:      */ 
                   11353:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   11354:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  11355:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   11356:           sumnewm[cptcod]=0.;
                   11357:           for (i=1; i<=nlstate;i++){
1.222     brouard  11358:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   11359:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   11360:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   11361:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   11362:             }
                   11363:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  11364:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   11365:           } /* end i */
                   11366:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   11367:         } /* end cptcod */
1.222     brouard  11368:        }/* end age */
                   11369:      }/* end mob */
1.266     brouard  11370:    }else{
                   11371:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  11372:      return -1;
1.266     brouard  11373:    }
                   11374: 
                   11375:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  11376:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   11377:      if(invalidvarcomb[cptcod]){
                   11378:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   11379:        continue;
                   11380:      }
1.219     brouard  11381: 
1.266     brouard  11382:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   11383:        sumnewm[cptcod]=0.;
                   11384:        sumnewmr[cptcod]=0.;
                   11385:        for (i=1; i<=nlstate;i++){
                   11386:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   11387:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   11388:        }
                   11389:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   11390:         agemingoodr[cptcod]=age;
                   11391:        }
                   11392:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   11393:           agemingood[cptcod]=age;
                   11394:        }
                   11395:      } /* age */
                   11396:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  11397:        sumnewm[cptcod]=0.;
1.266     brouard  11398:        sumnewmr[cptcod]=0.;
1.222     brouard  11399:        for (i=1; i<=nlstate;i++){
                   11400:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  11401:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   11402:        }
                   11403:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   11404:         agemaxgoodr[cptcod]=age;
1.222     brouard  11405:        }
                   11406:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  11407:         agemaxgood[cptcod]=age;
                   11408:        }
                   11409:      } /* age */
                   11410:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   11411:      /* but they will change */
1.288     brouard  11412:      firstA1=0;firstA2=0;
1.266     brouard  11413:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   11414:        sumnewm[cptcod]=0.;
                   11415:        sumnewmr[cptcod]=0.;
                   11416:        for (i=1; i<=nlstate;i++){
                   11417:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   11418:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   11419:        }
                   11420:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   11421:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   11422:           agemaxgoodr[cptcod]=age;  /* age min */
                   11423:           for (i=1; i<=nlstate;i++)
                   11424:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   11425:         }else{ /* bad we change the value with the values of good ages */
                   11426:           for (i=1; i<=nlstate;i++){
                   11427:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   11428:           } /* i */
                   11429:         } /* end bad */
                   11430:        }else{
                   11431:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   11432:           agemaxgood[cptcod]=age;
                   11433:         }else{ /* bad we change the value with the values of good ages */
                   11434:           for (i=1; i<=nlstate;i++){
                   11435:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   11436:           } /* i */
                   11437:         } /* end bad */
                   11438:        }/* end else */
                   11439:        sum=0.;sumr=0.;
                   11440:        for (i=1; i<=nlstate;i++){
                   11441:         sum+=mobaverage[(int)age][i][cptcod];
                   11442:         sumr+=probs[(int)age][i][cptcod];
                   11443:        }
                   11444:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  11445:         if(!firstA1){
                   11446:           firstA1=1;
                   11447:           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);
                   11448:         }
                   11449:         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  11450:        } /* end bad */
                   11451:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   11452:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  11453:         if(!firstA2){
                   11454:           firstA2=1;
                   11455:           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);
                   11456:         }
                   11457:         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  11458:        } /* end bad */
                   11459:      }/* age */
1.266     brouard  11460: 
                   11461:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  11462:        sumnewm[cptcod]=0.;
1.266     brouard  11463:        sumnewmr[cptcod]=0.;
1.222     brouard  11464:        for (i=1; i<=nlstate;i++){
                   11465:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  11466:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   11467:        } 
                   11468:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   11469:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   11470:           agemingoodr[cptcod]=age;
                   11471:           for (i=1; i<=nlstate;i++)
                   11472:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   11473:         }else{ /* bad we change the value with the values of good ages */
                   11474:           for (i=1; i<=nlstate;i++){
                   11475:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   11476:           } /* i */
                   11477:         } /* end bad */
                   11478:        }else{
                   11479:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   11480:           agemingood[cptcod]=age;
                   11481:         }else{ /* bad */
                   11482:           for (i=1; i<=nlstate;i++){
                   11483:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   11484:           } /* i */
                   11485:         } /* end bad */
                   11486:        }/* end else */
                   11487:        sum=0.;sumr=0.;
                   11488:        for (i=1; i<=nlstate;i++){
                   11489:         sum+=mobaverage[(int)age][i][cptcod];
                   11490:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  11491:        }
1.266     brouard  11492:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  11493:         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  11494:        } /* end bad */
                   11495:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   11496:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  11497:         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  11498:        } /* end bad */
                   11499:      }/* age */
1.266     brouard  11500: 
1.222     brouard  11501:                
                   11502:      for (age=bage; age<=fage; age++){
1.235     brouard  11503:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  11504:        sumnewp[cptcod]=0.;
                   11505:        sumnewm[cptcod]=0.;
                   11506:        for (i=1; i<=nlstate;i++){
                   11507:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   11508:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   11509:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   11510:        }
                   11511:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   11512:      }
                   11513:      /* printf("\n"); */
                   11514:      /* } */
1.266     brouard  11515: 
1.222     brouard  11516:      /* brutal averaging */
1.266     brouard  11517:      /* for (i=1; i<=nlstate;i++){ */
                   11518:      /*   for (age=1; age<=bage; age++){ */
                   11519:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   11520:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   11521:      /*   }     */
                   11522:      /*   for (age=fage; age<=AGESUP; age++){ */
                   11523:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   11524:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   11525:      /*   } */
                   11526:      /* } /\* end i status *\/ */
                   11527:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   11528:      /*   for (age=1; age<=AGESUP; age++){ */
                   11529:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   11530:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   11531:      /*   } */
                   11532:      /* } */
1.222     brouard  11533:    }/* end cptcod */
1.266     brouard  11534:    free_vector(agemaxgoodr,1, ncovcombmax);
                   11535:    free_vector(agemaxgood,1, ncovcombmax);
                   11536:    free_vector(agemingood,1, ncovcombmax);
                   11537:    free_vector(agemingoodr,1, ncovcombmax);
                   11538:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  11539:    free_vector(sumnewm,1, ncovcombmax);
                   11540:    free_vector(sumnewp,1, ncovcombmax);
                   11541:    return 0;
                   11542:  }/* End movingaverage */
1.218     brouard  11543:  
1.126     brouard  11544: 
1.296     brouard  11545:  
1.126     brouard  11546: /************** Forecasting ******************/
1.296     brouard  11547: /* 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)*/
                   11548: 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){
                   11549:   /* dateintemean, mean date of interviews
                   11550:      dateprojd, year, month, day of starting projection 
                   11551:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  11552:      agemin, agemax range of age
                   11553:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   11554:   */
1.296     brouard  11555:   /* double anprojd, mprojd, jprojd; */
                   11556:   /* double anprojf, mprojf, jprojf; */
1.359     brouard  11557:   int yearp, stepsize, hstepm, nhstepm, j, k, i, h,  nres=0;
1.126     brouard  11558:   double agec; /* generic age */
1.359     brouard  11559:   double agelim, ppij;
                   11560:   /*double *popcount;*/
1.126     brouard  11561:   double ***p3mat;
1.218     brouard  11562:   /* double ***mobaverage; */
1.126     brouard  11563:   char fileresf[FILENAMELENGTH];
                   11564: 
                   11565:   agelim=AGESUP;
1.211     brouard  11566:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   11567:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   11568:      We still use firstpass and lastpass as another selection.
                   11569:   */
1.214     brouard  11570:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   11571:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  11572:  
1.201     brouard  11573:   strcpy(fileresf,"F_"); 
                   11574:   strcat(fileresf,fileresu);
1.126     brouard  11575:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   11576:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   11577:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   11578:   }
1.235     brouard  11579:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   11580:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  11581: 
1.225     brouard  11582:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  11583: 
                   11584: 
                   11585:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11586:   if (stepm<=12) stepsize=1;
                   11587:   if(estepm < stepm){
                   11588:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   11589:   }
1.270     brouard  11590:   else{
                   11591:     hstepm=estepm;   
                   11592:   }
                   11593:   if(estepm > stepm){ /* Yes every two year */
                   11594:     stepsize=2;
                   11595:   }
1.296     brouard  11596:   hstepm=hstepm/stepm;
1.126     brouard  11597: 
1.296     brouard  11598:   
                   11599:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   11600:   /*                              fractional in yp1 *\/ */
                   11601:   /* aintmean=yp; */
                   11602:   /* yp2=modf((yp1*12),&yp); */
                   11603:   /* mintmean=yp; */
                   11604:   /* yp1=modf((yp2*30.5),&yp); */
                   11605:   /* jintmean=yp; */
                   11606:   /* if(jintmean==0) jintmean=1; */
                   11607:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  11608: 
1.296     brouard  11609: 
                   11610:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   11611:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   11612:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.351     brouard  11613:   /* i1=pow(2,cptcoveff); */
                   11614:   /* if (cptcovn < 1){i1=1;} */
1.126     brouard  11615:   
1.296     brouard  11616:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  11617:   
                   11618:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  11619:   
1.126     brouard  11620: /*           if (h==(int)(YEARM*yearp)){ */
1.351     brouard  11621:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11622:     k=TKresult[nres];
                   11623:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   11624:     /*  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) *\/ */
                   11625:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   11626:     /*   continue; */
                   11627:     /* if(invalidvarcomb[k]){ */
                   11628:     /*   printf("\nCombination (%d) projection ignored because no cases \n",k);  */
                   11629:     /*   continue; */
                   11630:     /* } */
1.227     brouard  11631:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
1.351     brouard  11632:     for(j=1;j<=cptcovs;j++){
                   11633:       /* for(j=1;j<=cptcoveff;j++) { */
                   11634:     /*   /\* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); *\/ */
                   11635:     /*   fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11636:     /* } */
                   11637:     /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11638:     /*   fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11639:     /* } */
                   11640:       fprintf(ficresf," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.235     brouard  11641:     }
1.351     brouard  11642:  
1.227     brouard  11643:     fprintf(ficresf," yearproj age");
                   11644:     for(j=1; j<=nlstate+ndeath;j++){ 
                   11645:       for(i=1; i<=nlstate;i++)               
                   11646:        fprintf(ficresf," p%d%d",i,j);
                   11647:       fprintf(ficresf," wp.%d",j);
                   11648:     }
1.296     brouard  11649:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  11650:       fprintf(ficresf,"\n");
1.296     brouard  11651:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  11652:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   11653:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  11654:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   11655:        nhstepm = nhstepm/hstepm; 
                   11656:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11657:        oldm=oldms;savm=savms;
1.268     brouard  11658:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  11659:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  11660:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  11661:        for (h=0; h<=nhstepm; h++){
                   11662:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  11663:            break;
                   11664:          }
                   11665:        }
                   11666:        fprintf(ficresf,"\n");
1.351     brouard  11667:        /* for(j=1;j<=cptcoveff;j++)  */
                   11668:        for(j=1;j<=cptcovs;j++) 
                   11669:          fprintf(ficresf,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.332     brouard  11670:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
1.351     brouard  11671:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* TnsdVar[Tvaraff]  correct *\/ */
1.296     brouard  11672:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  11673:        
                   11674:        for(j=1; j<=nlstate+ndeath;j++) {
                   11675:          ppij=0.;
                   11676:          for(i=1; i<=nlstate;i++) {
1.278     brouard  11677:            if (mobilav>=1)
                   11678:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   11679:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   11680:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   11681:            }
1.268     brouard  11682:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   11683:          } /* end i */
                   11684:          fprintf(ficresf," %.3f", ppij);
                   11685:        }/* end j */
1.227     brouard  11686:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11687:       } /* end agec */
1.266     brouard  11688:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   11689:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  11690:     } /* end yearp */
                   11691:   } /* end  k */
1.219     brouard  11692:        
1.126     brouard  11693:   fclose(ficresf);
1.215     brouard  11694:   printf("End of Computing forecasting \n");
                   11695:   fprintf(ficlog,"End of Computing forecasting\n");
                   11696: 
1.126     brouard  11697: }
                   11698: 
1.269     brouard  11699: /************** Back Forecasting ******************/
1.296     brouard  11700:  /* 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){ */
                   11701:  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){
                   11702:   /* back1, year, month, day of starting backprojection
1.267     brouard  11703:      agemin, agemax range of age
                   11704:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  11705:      anback2 year of end of backprojection (same day and month as back1).
                   11706:      prevacurrent and prev are prevalences.
1.267     brouard  11707:   */
1.359     brouard  11708:   int yearp, stepsize, hstepm, nhstepm, j, k,  i, h, nres=0;
1.267     brouard  11709:   double agec; /* generic age */
1.359     brouard  11710:   double agelim, ppij, ppi; /* ,jintmean,mintmean,aintmean;*/
                   11711:   /*double *popcount;*/
1.267     brouard  11712:   double ***p3mat;
                   11713:   /* double ***mobaverage; */
                   11714:   char fileresfb[FILENAMELENGTH];
                   11715:  
1.268     brouard  11716:   agelim=AGEINF;
1.267     brouard  11717:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   11718:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   11719:      We still use firstpass and lastpass as another selection.
                   11720:   */
                   11721:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   11722:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   11723: 
                   11724:   /*Do we need to compute prevalence again?*/
                   11725: 
                   11726:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   11727:   
                   11728:   strcpy(fileresfb,"FB_");
                   11729:   strcat(fileresfb,fileresu);
                   11730:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   11731:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   11732:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   11733:   }
                   11734:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   11735:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   11736:   
                   11737:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   11738:   
                   11739:    
                   11740:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11741:   if (stepm<=12) stepsize=1;
                   11742:   if(estepm < stepm){
                   11743:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   11744:   }
1.270     brouard  11745:   else{
                   11746:     hstepm=estepm;   
                   11747:   }
                   11748:   if(estepm >= stepm){ /* Yes every two year */
                   11749:     stepsize=2;
                   11750:   }
1.267     brouard  11751:   
                   11752:   hstepm=hstepm/stepm;
1.296     brouard  11753:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   11754:   /*                              fractional in yp1 *\/ */
                   11755:   /* aintmean=yp; */
                   11756:   /* yp2=modf((yp1*12),&yp); */
                   11757:   /* mintmean=yp; */
                   11758:   /* yp1=modf((yp2*30.5),&yp); */
                   11759:   /* jintmean=yp; */
                   11760:   /* if(jintmean==0) jintmean=1; */
                   11761:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  11762:   
1.351     brouard  11763:   /* i1=pow(2,cptcoveff); */
                   11764:   /* if (cptcovn < 1){i1=1;} */
1.267     brouard  11765:   
1.296     brouard  11766:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   11767:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  11768:   
                   11769:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   11770:   
1.351     brouard  11771:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11772:     k=TKresult[nres];
                   11773:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   11774:   /* for(k=1; k<=i1;k++){ */
                   11775:   /*   if(i1 != 1 && TKresult[nres]!= k) */
                   11776:   /*     continue; */
                   11777:   /*   if(invalidvarcomb[k]){ */
                   11778:   /*     printf("\nCombination (%d) projection ignored because no cases \n",k);  */
                   11779:   /*     continue; */
                   11780:   /*   } */
1.268     brouard  11781:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.351     brouard  11782:     for(j=1;j<=cptcovs;j++){
                   11783:     /* for(j=1;j<=cptcoveff;j++) { */
                   11784:     /*   fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11785:     /* } */
                   11786:       fprintf(ficresfb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.267     brouard  11787:     }
1.351     brouard  11788:    /*  fprintf(ficrespij,"******\n"); */
                   11789:    /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11790:    /*    fprintf(ficresfb," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11791:    /*  } */
1.267     brouard  11792:     fprintf(ficresfb," yearbproj age");
                   11793:     for(j=1; j<=nlstate+ndeath;j++){
                   11794:       for(i=1; i<=nlstate;i++)
1.268     brouard  11795:        fprintf(ficresfb," b%d%d",i,j);
                   11796:       fprintf(ficresfb," b.%d",j);
1.267     brouard  11797:     }
1.296     brouard  11798:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  11799:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   11800:       fprintf(ficresfb,"\n");
1.296     brouard  11801:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  11802:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  11803:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   11804:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  11805:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  11806:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  11807:        nhstepm = nhstepm/hstepm;
                   11808:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11809:        oldm=oldms;savm=savms;
1.268     brouard  11810:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  11811:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  11812:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  11813:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   11814:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   11815:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  11816:        for (h=0; h<=nhstepm; h++){
1.268     brouard  11817:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   11818:            break;
                   11819:          }
                   11820:        }
                   11821:        fprintf(ficresfb,"\n");
1.351     brouard  11822:        /* for(j=1;j<=cptcoveff;j++) */
                   11823:        for(j=1;j<=cptcovs;j++)
                   11824:          fprintf(ficresfb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11825:          /* fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.296     brouard  11826:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  11827:        for(i=1; i<=nlstate+ndeath;i++) {
                   11828:          ppij=0.;ppi=0.;
                   11829:          for(j=1; j<=nlstate;j++) {
                   11830:            /* if (mobilav==1) */
1.269     brouard  11831:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   11832:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   11833:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   11834:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  11835:              /* else { */
                   11836:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   11837:              /* } */
1.268     brouard  11838:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   11839:          } /* end j */
                   11840:          if(ppi <0.99){
                   11841:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   11842:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   11843:          }
                   11844:          fprintf(ficresfb," %.3f", ppij);
                   11845:        }/* end j */
1.267     brouard  11846:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11847:       } /* end agec */
                   11848:     } /* end yearp */
                   11849:   } /* end k */
1.217     brouard  11850:   
1.267     brouard  11851:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  11852:   
1.267     brouard  11853:   fclose(ficresfb);
                   11854:   printf("End of Computing Back forecasting \n");
                   11855:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  11856:        
1.267     brouard  11857: }
1.217     brouard  11858: 
1.269     brouard  11859: /* Variance of prevalence limit: varprlim */
                   11860:  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  11861:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  11862:  
                   11863:    char fileresvpl[FILENAMELENGTH];  
                   11864:    FILE *ficresvpl;
                   11865:    double **oldm, **savm;
                   11866:    double **varpl; /* Variances of prevalence limits by age */   
                   11867:    int i1, k, nres, j ;
                   11868:    
                   11869:     strcpy(fileresvpl,"VPL_");
                   11870:     strcat(fileresvpl,fileresu);
                   11871:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  11872:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  11873:       exit(0);
                   11874:     }
1.288     brouard  11875:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   11876:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  11877:     
                   11878:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   11879:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   11880:     
                   11881:     i1=pow(2,cptcoveff);
                   11882:     if (cptcovn < 1){i1=1;}
                   11883: 
1.337     brouard  11884:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11885:        k=TKresult[nres];
1.338     brouard  11886:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  11887:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
1.269     brouard  11888:       if(i1 != 1 && TKresult[nres]!= k)
                   11889:        continue;
                   11890:       fprintf(ficresvpl,"\n#****** ");
                   11891:       printf("\n#****** ");
                   11892:       fprintf(ficlog,"\n#****** ");
1.337     brouard  11893:       for(j=1;j<=cptcovs;j++) {
                   11894:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11895:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11896:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11897:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11898:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.269     brouard  11899:       }
1.337     brouard  11900:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   11901:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11902:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11903:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11904:       /* }      */
1.269     brouard  11905:       fprintf(ficresvpl,"******\n");
                   11906:       printf("******\n");
                   11907:       fprintf(ficlog,"******\n");
                   11908:       
                   11909:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   11910:       oldm=oldms;savm=savms;
                   11911:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   11912:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   11913:       /*}*/
                   11914:     }
                   11915:     
                   11916:     fclose(ficresvpl);
1.288     brouard  11917:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   11918:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  11919: 
                   11920:  }
                   11921: /* Variance of back prevalence: varbprlim */
                   11922:  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){
                   11923:       /*------- Variance of back (stable) prevalence------*/
                   11924: 
                   11925:    char fileresvbl[FILENAMELENGTH];  
                   11926:    FILE  *ficresvbl;
                   11927: 
                   11928:    double **oldm, **savm;
                   11929:    double **varbpl; /* Variances of back prevalence limits by age */   
                   11930:    int i1, k, nres, j ;
                   11931: 
                   11932:    strcpy(fileresvbl,"VBL_");
                   11933:    strcat(fileresvbl,fileresu);
                   11934:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   11935:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   11936:      exit(0);
                   11937:    }
                   11938:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   11939:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   11940:    
                   11941:    
                   11942:    i1=pow(2,cptcoveff);
                   11943:    if (cptcovn < 1){i1=1;}
                   11944:    
1.337     brouard  11945:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11946:      k=TKresult[nres];
1.338     brouard  11947:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  11948:     /* for(k=1; k<=i1;k++){ */
                   11949:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   11950:     /*          continue; */
1.269     brouard  11951:        fprintf(ficresvbl,"\n#****** ");
                   11952:        printf("\n#****** ");
                   11953:        fprintf(ficlog,"\n#****** ");
1.337     brouard  11954:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
1.338     brouard  11955:         printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   11956:         fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   11957:         fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
1.337     brouard  11958:        /* for(j=1;j<=cptcoveff;j++) { */
                   11959:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11960:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11961:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11962:        /* } */
                   11963:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   11964:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11965:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11966:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
1.269     brouard  11967:        }
                   11968:        fprintf(ficresvbl,"******\n");
                   11969:        printf("******\n");
                   11970:        fprintf(ficlog,"******\n");
                   11971:        
                   11972:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   11973:        oldm=oldms;savm=savms;
                   11974:        
                   11975:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   11976:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   11977:        /*}*/
                   11978:      }
                   11979:    
                   11980:    fclose(ficresvbl);
                   11981:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   11982:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   11983: 
                   11984:  } /* End of varbprlim */
                   11985: 
1.126     brouard  11986: /************** Forecasting *****not tested NB*************/
1.227     brouard  11987: /* 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  11988:   
1.227     brouard  11989: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   11990: /*   int *popage; */
                   11991: /*   double calagedatem, agelim, kk1, kk2; */
                   11992: /*   double *popeffectif,*popcount; */
                   11993: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   11994: /*   /\* double ***mobaverage; *\/ */
                   11995: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  11996: 
1.227     brouard  11997: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   11998: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   11999: /*   agelim=AGESUP; */
                   12000: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  12001:   
1.227     brouard  12002: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  12003:   
                   12004:   
1.227     brouard  12005: /*   strcpy(filerespop,"POP_");  */
                   12006: /*   strcat(filerespop,fileresu); */
                   12007: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   12008: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   12009: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   12010: /*   } */
                   12011: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   12012: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  12013: 
1.227     brouard  12014: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  12015: 
1.227     brouard  12016: /*   /\* if (mobilav!=0) { *\/ */
                   12017: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   12018: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   12019: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   12020: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   12021: /*   /\*   } *\/ */
                   12022: /*   /\* } *\/ */
1.126     brouard  12023: 
1.227     brouard  12024: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   12025: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  12026:   
1.227     brouard  12027: /*   agelim=AGESUP; */
1.126     brouard  12028:   
1.227     brouard  12029: /*   hstepm=1; */
                   12030: /*   hstepm=hstepm/stepm;  */
1.218     brouard  12031:        
1.227     brouard  12032: /*   if (popforecast==1) { */
                   12033: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   12034: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   12035: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   12036: /*     }  */
                   12037: /*     popage=ivector(0,AGESUP); */
                   12038: /*     popeffectif=vector(0,AGESUP); */
                   12039: /*     popcount=vector(0,AGESUP); */
1.126     brouard  12040:     
1.227     brouard  12041: /*     i=1;    */
                   12042: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  12043:     
1.227     brouard  12044: /*     imx=i; */
                   12045: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   12046: /*   } */
1.218     brouard  12047:   
1.227     brouard  12048: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   12049: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   12050: /*       k=k+1; */
                   12051: /*       fprintf(ficrespop,"\n#******"); */
                   12052: /*       for(j=1;j<=cptcoveff;j++) { */
                   12053: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   12054: /*       } */
                   12055: /*       fprintf(ficrespop,"******\n"); */
                   12056: /*       fprintf(ficrespop,"# Age"); */
                   12057: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   12058: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  12059:       
1.227     brouard  12060: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   12061: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  12062:        
1.227     brouard  12063: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   12064: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   12065: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  12066:          
1.227     brouard  12067: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   12068: /*       oldm=oldms;savm=savms; */
                   12069: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  12070:          
1.227     brouard  12071: /*       for (h=0; h<=nhstepm; h++){ */
                   12072: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   12073: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   12074: /*         }  */
                   12075: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   12076: /*           kk1=0.;kk2=0; */
                   12077: /*           for(i=1; i<=nlstate;i++) {               */
                   12078: /*             if (mobilav==1)  */
                   12079: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   12080: /*             else { */
                   12081: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   12082: /*             } */
                   12083: /*           } */
                   12084: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   12085: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   12086: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   12087: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   12088: /*           } */
                   12089: /*         } */
                   12090: /*         for(i=1; i<=nlstate;i++){ */
                   12091: /*           kk1=0.; */
                   12092: /*           for(j=1; j<=nlstate;j++){ */
                   12093: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   12094: /*           } */
                   12095: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   12096: /*         } */
1.218     brouard  12097:            
1.227     brouard  12098: /*         if (h==(int)(calagedatem+12*cpt)) */
                   12099: /*           for(j=1; j<=nlstate;j++)  */
                   12100: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   12101: /*       } */
                   12102: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   12103: /*     } */
                   12104: /*       } */
1.218     brouard  12105:       
1.227     brouard  12106: /*       /\******\/ */
1.218     brouard  12107:       
1.227     brouard  12108: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   12109: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   12110: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   12111: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   12112: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  12113:          
1.227     brouard  12114: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   12115: /*       oldm=oldms;savm=savms; */
                   12116: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   12117: /*       for (h=0; h<=nhstepm; h++){ */
                   12118: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   12119: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   12120: /*         }  */
                   12121: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   12122: /*           kk1=0.;kk2=0; */
                   12123: /*           for(i=1; i<=nlstate;i++) {               */
                   12124: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   12125: /*           } */
                   12126: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   12127: /*         } */
                   12128: /*       } */
                   12129: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   12130: /*     } */
                   12131: /*       } */
                   12132: /*     }  */
                   12133: /*   } */
1.218     brouard  12134:   
1.227     brouard  12135: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  12136:   
1.227     brouard  12137: /*   if (popforecast==1) { */
                   12138: /*     free_ivector(popage,0,AGESUP); */
                   12139: /*     free_vector(popeffectif,0,AGESUP); */
                   12140: /*     free_vector(popcount,0,AGESUP); */
                   12141: /*   } */
                   12142: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   12143: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   12144: /*   fclose(ficrespop); */
                   12145: /* } /\* End of popforecast *\/ */
1.218     brouard  12146:  
1.126     brouard  12147: int fileappend(FILE *fichier, char *optionfich)
                   12148: {
                   12149:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   12150:     printf("Problem with file: %s\n", optionfich);
                   12151:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   12152:     return (0);
                   12153:   }
                   12154:   fflush(fichier);
                   12155:   return (1);
                   12156: }
                   12157: 
                   12158: 
                   12159: /**************** function prwizard **********************/
                   12160: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   12161: {
                   12162: 
                   12163:   /* Wizard to print covariance matrix template */
                   12164: 
1.164     brouard  12165:   char ca[32], cb[32];
                   12166:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  12167:   int numlinepar;
                   12168: 
                   12169:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12170:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12171:   for(i=1; i <=nlstate; i++){
                   12172:     jj=0;
                   12173:     for(j=1; j <=nlstate+ndeath; j++){
                   12174:       if(j==i) continue;
                   12175:       jj++;
                   12176:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   12177:       printf("%1d%1d",i,j);
                   12178:       fprintf(ficparo,"%1d%1d",i,j);
                   12179:       for(k=1; k<=ncovmodel;k++){
                   12180:        /*        printf(" %lf",param[i][j][k]); */
                   12181:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   12182:        printf(" 0.");
                   12183:        fprintf(ficparo," 0.");
                   12184:       }
                   12185:       printf("\n");
                   12186:       fprintf(ficparo,"\n");
                   12187:     }
                   12188:   }
                   12189:   printf("# Scales (for hessian or gradient estimation)\n");
                   12190:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   12191:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   12192:   for(i=1; i <=nlstate; i++){
                   12193:     jj=0;
                   12194:     for(j=1; j <=nlstate+ndeath; j++){
                   12195:       if(j==i) continue;
                   12196:       jj++;
                   12197:       fprintf(ficparo,"%1d%1d",i,j);
                   12198:       printf("%1d%1d",i,j);
                   12199:       fflush(stdout);
                   12200:       for(k=1; k<=ncovmodel;k++){
                   12201:        /*      printf(" %le",delti3[i][j][k]); */
                   12202:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   12203:        printf(" 0.");
                   12204:        fprintf(ficparo," 0.");
                   12205:       }
                   12206:       numlinepar++;
                   12207:       printf("\n");
                   12208:       fprintf(ficparo,"\n");
                   12209:     }
                   12210:   }
                   12211:   printf("# Covariance matrix\n");
                   12212: /* # 121 Var(a12)\n\ */
                   12213: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   12214: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   12215: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   12216: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   12217: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   12218: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   12219: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   12220:   fflush(stdout);
                   12221:   fprintf(ficparo,"# Covariance matrix\n");
                   12222:   /* # 121 Var(a12)\n\ */
                   12223:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   12224:   /* #   ...\n\ */
                   12225:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   12226:   
                   12227:   for(itimes=1;itimes<=2;itimes++){
                   12228:     jj=0;
                   12229:     for(i=1; i <=nlstate; i++){
                   12230:       for(j=1; j <=nlstate+ndeath; j++){
                   12231:        if(j==i) continue;
                   12232:        for(k=1; k<=ncovmodel;k++){
                   12233:          jj++;
                   12234:          ca[0]= k+'a'-1;ca[1]='\0';
                   12235:          if(itimes==1){
                   12236:            printf("#%1d%1d%d",i,j,k);
                   12237:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   12238:          }else{
                   12239:            printf("%1d%1d%d",i,j,k);
                   12240:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   12241:            /*  printf(" %.5le",matcov[i][j]); */
                   12242:          }
                   12243:          ll=0;
                   12244:          for(li=1;li <=nlstate; li++){
                   12245:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   12246:              if(lj==li) continue;
                   12247:              for(lk=1;lk<=ncovmodel;lk++){
                   12248:                ll++;
                   12249:                if(ll<=jj){
                   12250:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   12251:                  if(ll<jj){
                   12252:                    if(itimes==1){
                   12253:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12254:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12255:                    }else{
                   12256:                      printf(" 0.");
                   12257:                      fprintf(ficparo," 0.");
                   12258:                    }
                   12259:                  }else{
                   12260:                    if(itimes==1){
                   12261:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   12262:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   12263:                    }else{
                   12264:                      printf(" 0.");
                   12265:                      fprintf(ficparo," 0.");
                   12266:                    }
                   12267:                  }
                   12268:                }
                   12269:              } /* end lk */
                   12270:            } /* end lj */
                   12271:          } /* end li */
                   12272:          printf("\n");
                   12273:          fprintf(ficparo,"\n");
                   12274:          numlinepar++;
                   12275:        } /* end k*/
                   12276:       } /*end j */
                   12277:     } /* end i */
                   12278:   } /* end itimes */
                   12279: 
                   12280: } /* end of prwizard */
                   12281: /******************* Gompertz Likelihood ******************************/
                   12282: double gompertz(double x[])
                   12283: { 
1.302     brouard  12284:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  12285:   int i,n=0; /* n is the size of the sample */
                   12286: 
1.220     brouard  12287:   for (i=1;i<=imx ; i++) {
1.126     brouard  12288:     sump=sump+weight[i];
                   12289:     /*    sump=sump+1;*/
                   12290:     num=num+1;
                   12291:   }
1.302     brouard  12292:   L=0.0;
                   12293:   /* agegomp=AGEGOMP; */
1.126     brouard  12294:   /* for (i=0; i<=imx; i++) 
                   12295:      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]);*/
                   12296: 
1.302     brouard  12297:   for (i=1;i<=imx ; i++) {
                   12298:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   12299:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   12300:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   12301:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   12302:      * +
                   12303:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   12304:      */
                   12305:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   12306:        if (cens[i] == 1){
                   12307:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   12308:        } else if (cens[i] == 0){
1.126     brouard  12309:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.362     brouard  12310:          +log(fabs(x[1])/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   12311:        /* +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM); */  /* To be seen */
1.302     brouard  12312:       } else
                   12313:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  12314:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  12315:        L=L+A*weight[i];
1.126     brouard  12316:        /*      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  12317:      }
                   12318:   }
1.126     brouard  12319: 
1.302     brouard  12320:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  12321:  
                   12322:   return -2*L*num/sump;
                   12323: }
                   12324: 
1.136     brouard  12325: #ifdef GSL
                   12326: /******************* Gompertz_f Likelihood ******************************/
                   12327: double gompertz_f(const gsl_vector *v, void *params)
                   12328: { 
1.302     brouard  12329:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  12330:   double *x= (double *) v->data;
                   12331:   int i,n=0; /* n is the size of the sample */
                   12332: 
                   12333:   for (i=0;i<=imx-1 ; i++) {
                   12334:     sump=sump+weight[i];
                   12335:     /*    sump=sump+1;*/
                   12336:     num=num+1;
                   12337:   }
                   12338:  
                   12339:  
                   12340:   /* for (i=0; i<=imx; i++) 
                   12341:      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]);*/
                   12342:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   12343:   for (i=1;i<=imx ; i++)
                   12344:     {
                   12345:       if (cens[i] == 1 && wav[i]>1)
                   12346:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   12347:       
                   12348:       if (cens[i] == 0 && wav[i]>1)
                   12349:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   12350:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   12351:       
                   12352:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   12353:       if (wav[i] > 1 ) { /* ??? */
                   12354:        LL=LL+A*weight[i];
                   12355:        /*      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]);*/
                   12356:       }
                   12357:     }
                   12358: 
                   12359:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   12360:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   12361:  
                   12362:   return -2*LL*num/sump;
                   12363: }
                   12364: #endif
                   12365: 
1.126     brouard  12366: /******************* Printing html file ***********/
1.201     brouard  12367: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  12368:                  int lastpass, int stepm, int weightopt, char model[],\
                   12369:                  int imx,  double p[],double **matcov,double agemortsup){
                   12370:   int i,k;
                   12371: 
                   12372:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   12373:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   12374:   for (i=1;i<=2;i++) 
                   12375:     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  12376:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  12377:   fprintf(fichtm,"</ul>");
                   12378: 
                   12379: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   12380: 
                   12381:  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>");
                   12382: 
                   12383:  for (k=agegomp;k<(agemortsup-2);k++) 
                   12384:    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]);
                   12385: 
                   12386:  
                   12387:   fflush(fichtm);
                   12388: }
                   12389: 
                   12390: /******************* Gnuplot file **************/
1.201     brouard  12391: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  12392: 
                   12393:   char dirfileres[132],optfileres[132];
1.164     brouard  12394: 
1.359     brouard  12395:   /*int ng;*/
1.126     brouard  12396: 
                   12397: 
                   12398:   /*#ifdef windows */
                   12399:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   12400:     /*#endif */
                   12401: 
                   12402: 
                   12403:   strcpy(dirfileres,optionfilefiname);
                   12404:   strcpy(optfileres,"vpl");
1.199     brouard  12405:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  12406:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  12407:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  12408:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  12409:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   12410: 
                   12411: } 
                   12412: 
1.136     brouard  12413: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   12414: {
1.126     brouard  12415: 
1.136     brouard  12416:   /*-------- data file ----------*/
                   12417:   FILE *fic;
                   12418:   char dummy[]="                         ";
1.359     brouard  12419:   int i = 0, j = 0, n = 0, iv = 0;/* , v;*/
1.223     brouard  12420:   int lstra;
1.136     brouard  12421:   int linei, month, year,iout;
1.302     brouard  12422:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  12423:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  12424:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  12425:   char *stratrunc;
1.223     brouard  12426: 
1.349     brouard  12427:   /* DummyV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
                   12428:   /* FixedV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
1.339     brouard  12429:   
                   12430:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
                   12431:   
1.136     brouard  12432:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  12433:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   12434:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  12435:   }
1.126     brouard  12436: 
1.302     brouard  12437:     /* Is it a BOM UTF-8 Windows file? */
                   12438:   /* First data line */
                   12439:   linei=0;
                   12440:   while(fgets(line, MAXLINE, fic)) {
                   12441:     noffset=0;
                   12442:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   12443:     {
                   12444:       noffset=noffset+3;
                   12445:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   12446:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   12447:       fflush(ficlog); return 1;
                   12448:     }
                   12449:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   12450:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   12451:     {
                   12452:       noffset=noffset+2;
1.304     brouard  12453:       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);
                   12454:       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  12455:       fflush(ficlog); return 1;
                   12456:     }
                   12457:     else if( line[0] == 0 && line[1] == 0)
                   12458:     {
                   12459:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   12460:        noffset=noffset+4;
1.304     brouard  12461:        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);
                   12462:        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  12463:        fflush(ficlog); return 1;
                   12464:       }
                   12465:     } else{
                   12466:       ;/*printf(" Not a BOM file\n");*/
                   12467:     }
                   12468:         /* If line starts with a # it is a comment */
                   12469:     if (line[noffset] == '#') {
                   12470:       linei=linei+1;
                   12471:       break;
                   12472:     }else{
                   12473:       break;
                   12474:     }
                   12475:   }
                   12476:   fclose(fic);
                   12477:   if((fic=fopen(datafile,"r"))==NULL)    {
                   12478:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   12479:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   12480:   }
                   12481:   /* Not a Bom file */
                   12482:   
1.136     brouard  12483:   i=1;
                   12484:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   12485:     linei=linei+1;
                   12486:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   12487:       if(line[j] == '\t')
                   12488:        line[j] = ' ';
                   12489:     }
                   12490:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   12491:       ;
                   12492:     };
                   12493:     line[j+1]=0;  /* Trims blanks at end of line */
                   12494:     if(line[0]=='#'){
                   12495:       fprintf(ficlog,"Comment line\n%s\n",line);
                   12496:       printf("Comment line\n%s\n",line);
                   12497:       continue;
                   12498:     }
                   12499:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  12500:     strcpy(line, linetmp);
1.223     brouard  12501:     
                   12502:     /* Loops on waves */
                   12503:     for (j=maxwav;j>=1;j--){
                   12504:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  12505:        cutv(stra, strb, line, ' '); 
                   12506:        if(strb[0]=='.') { /* Missing value */
                   12507:          lval=-1;
                   12508:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
1.341     brouard  12509:          cotvar[j][ncovcol+nqv+ntv+iv][i]=-1; /* For performance reasons */
1.238     brouard  12510:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   12511:            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);
                   12512:            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);
                   12513:            return 1;
                   12514:          }
                   12515:        }else{
                   12516:          errno=0;
                   12517:          /* what_kind_of_number(strb); */
                   12518:          dval=strtod(strb,&endptr); 
                   12519:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   12520:          /* if(strb != endptr && *endptr == '\0') */
                   12521:          /*    dval=dlval; */
                   12522:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   12523:          if( strb[0]=='\0' || (*endptr != '\0')){
                   12524:            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);
                   12525:            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);
                   12526:            return 1;
                   12527:          }
                   12528:          cotqvar[j][iv][i]=dval; 
1.341     brouard  12529:          cotvar[j][ncovcol+nqv+ntv+iv][i]=dval; /* because cotvar starts now at first ntv */ 
1.238     brouard  12530:        }
                   12531:        strcpy(line,stra);
1.223     brouard  12532:       }/* end loop ntqv */
1.225     brouard  12533:       
1.223     brouard  12534:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  12535:        cutv(stra, strb, line, ' '); 
                   12536:        if(strb[0]=='.') { /* Missing value */
                   12537:          lval=-1;
                   12538:        }else{
                   12539:          errno=0;
                   12540:          lval=strtol(strb,&endptr,10); 
                   12541:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   12542:          if( strb[0]=='\0' || (*endptr != '\0')){
                   12543:            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);
                   12544:            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);
                   12545:            return 1;
                   12546:          }
                   12547:        }
                   12548:        if(lval <-1 || lval >1){
                   12549:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  12550:  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  12551:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  12552:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   12553:  build V1=0 V2=0 for the reference value (1),\n                                \
                   12554:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  12555:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  12556:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  12557:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  12558:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  12559:  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  12560:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  12561:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   12562:  build V1=0 V2=0 for the reference value (1),\n                                \
                   12563:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  12564:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  12565:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  12566:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  12567:          return 1;
                   12568:        }
1.341     brouard  12569:        cotvar[j][ncovcol+nqv+iv][i]=(double)(lval);
1.238     brouard  12570:        strcpy(line,stra);
1.223     brouard  12571:       }/* end loop ntv */
1.225     brouard  12572:       
1.223     brouard  12573:       /* Statuses  at wave */
1.137     brouard  12574:       cutv(stra, strb, line, ' '); 
1.223     brouard  12575:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  12576:        lval=-1;
1.136     brouard  12577:       }else{
1.238     brouard  12578:        errno=0;
                   12579:        lval=strtol(strb,&endptr,10); 
                   12580:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
1.347     brouard  12581:        if( strb[0]=='\0' || (*endptr != '\0' )){
                   12582:          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);
                   12583:          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);
                   12584:          return 1;
                   12585:        }else if( lval==0 || lval > nlstate+ndeath){
1.348     brouard  12586:          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);
                   12587:          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  12588:          return 1;
                   12589:        }
1.136     brouard  12590:       }
1.225     brouard  12591:       
1.136     brouard  12592:       s[j][i]=lval;
1.225     brouard  12593:       
1.223     brouard  12594:       /* Date of Interview */
1.136     brouard  12595:       strcpy(line,stra);
                   12596:       cutv(stra, strb,line,' ');
1.169     brouard  12597:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  12598:       }
1.169     brouard  12599:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  12600:        month=99;
                   12601:        year=9999;
1.136     brouard  12602:       }else{
1.225     brouard  12603:        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);
                   12604:        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);
                   12605:        return 1;
1.136     brouard  12606:       }
                   12607:       anint[j][i]= (double) year; 
1.302     brouard  12608:       mint[j][i]= (double)month;
                   12609:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   12610:       /*       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]); */
                   12611:       /*       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]); */
                   12612:       /* } */
1.136     brouard  12613:       strcpy(line,stra);
1.223     brouard  12614:     } /* End loop on waves */
1.225     brouard  12615:     
1.223     brouard  12616:     /* Date of death */
1.136     brouard  12617:     cutv(stra, strb,line,' '); 
1.169     brouard  12618:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  12619:     }
1.169     brouard  12620:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  12621:       month=99;
                   12622:       year=9999;
                   12623:     }else{
1.141     brouard  12624:       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  12625:       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);
                   12626:       return 1;
1.136     brouard  12627:     }
                   12628:     andc[i]=(double) year; 
                   12629:     moisdc[i]=(double) month; 
                   12630:     strcpy(line,stra);
                   12631:     
1.223     brouard  12632:     /* Date of birth */
1.136     brouard  12633:     cutv(stra, strb,line,' '); 
1.169     brouard  12634:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  12635:     }
1.169     brouard  12636:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  12637:       month=99;
                   12638:       year=9999;
                   12639:     }else{
1.141     brouard  12640:       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);
                   12641:       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  12642:       return 1;
1.136     brouard  12643:     }
                   12644:     if (year==9999) {
1.141     brouard  12645:       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);
                   12646:       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  12647:       return 1;
                   12648:       
1.136     brouard  12649:     }
                   12650:     annais[i]=(double)(year);
1.302     brouard  12651:     moisnais[i]=(double)(month);
                   12652:     for (j=1;j<=maxwav;j++){
                   12653:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   12654:        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]);
                   12655:        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]);
                   12656:       }
                   12657:     }
                   12658: 
1.136     brouard  12659:     strcpy(line,stra);
1.225     brouard  12660:     
1.223     brouard  12661:     /* Sample weight */
1.136     brouard  12662:     cutv(stra, strb,line,' '); 
                   12663:     errno=0;
                   12664:     dval=strtod(strb,&endptr); 
                   12665:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  12666:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   12667:       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  12668:       fflush(ficlog);
                   12669:       return 1;
                   12670:     }
                   12671:     weight[i]=dval; 
                   12672:     strcpy(line,stra);
1.225     brouard  12673:     
1.223     brouard  12674:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   12675:       cutv(stra, strb, line, ' '); 
                   12676:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  12677:        lval=-1;
1.311     brouard  12678:        coqvar[iv][i]=NAN; 
                   12679:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  12680:       }else{
1.225     brouard  12681:        errno=0;
                   12682:        /* what_kind_of_number(strb); */
                   12683:        dval=strtod(strb,&endptr);
                   12684:        /* if(strb != endptr && *endptr == '\0') */
                   12685:        /*   dval=dlval; */
                   12686:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   12687:        if( strb[0]=='\0' || (*endptr != '\0')){
                   12688:          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);
                   12689:          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);
                   12690:          return 1;
                   12691:        }
                   12692:        coqvar[iv][i]=dval; 
1.226     brouard  12693:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  12694:       }
                   12695:       strcpy(line,stra);
                   12696:     }/* end loop nqv */
1.136     brouard  12697:     
1.223     brouard  12698:     /* Covariate values */
1.136     brouard  12699:     for (j=ncovcol;j>=1;j--){
                   12700:       cutv(stra, strb,line,' '); 
1.223     brouard  12701:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  12702:        lval=-1;
1.136     brouard  12703:       }else{
1.225     brouard  12704:        errno=0;
                   12705:        lval=strtol(strb,&endptr,10); 
                   12706:        if( strb[0]=='\0' || (*endptr != '\0')){
                   12707:          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);
                   12708:          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);
                   12709:          return 1;
                   12710:        }
1.136     brouard  12711:       }
                   12712:       if(lval <-1 || lval >1){
1.225     brouard  12713:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  12714:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   12715:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  12716:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   12717:  build V1=0 V2=0 for the reference value (1),\n                                \
                   12718:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  12719:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  12720:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  12721:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  12722:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  12723:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   12724:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  12725:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   12726:  build V1=0 V2=0 for the reference value (1),\n                                \
                   12727:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  12728:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  12729:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  12730:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  12731:        return 1;
1.136     brouard  12732:       }
                   12733:       covar[j][i]=(double)(lval);
                   12734:       strcpy(line,stra);
                   12735:     }  
                   12736:     lstra=strlen(stra);
1.225     brouard  12737:     
1.136     brouard  12738:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   12739:       stratrunc = &(stra[lstra-9]);
                   12740:       num[i]=atol(stratrunc);
                   12741:     }
                   12742:     else
                   12743:       num[i]=atol(stra);
                   12744:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   12745:       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;}*/
                   12746:     
                   12747:     i=i+1;
                   12748:   } /* End loop reading  data */
1.225     brouard  12749:   
1.136     brouard  12750:   *imax=i-1; /* Number of individuals */
                   12751:   fclose(fic);
1.225     brouard  12752:   
1.136     brouard  12753:   return (0);
1.164     brouard  12754:   /* endread: */
1.225     brouard  12755:   printf("Exiting readdata: ");
                   12756:   fclose(fic);
                   12757:   return (1);
1.223     brouard  12758: }
1.126     brouard  12759: 
1.234     brouard  12760: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  12761:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  12762:   while (*p2 == ' ')
1.234     brouard  12763:     p2++; 
                   12764:   /* while ((*p1++ = *p2++) !=0) */
                   12765:   /*   ; */
                   12766:   /* do */
                   12767:   /*   while (*p2 == ' ') */
                   12768:   /*     p2++; */
                   12769:   /* while (*p1++ == *p2++); */
                   12770:   *stri=p2; 
1.145     brouard  12771: }
                   12772: 
1.330     brouard  12773: int decoderesult( char resultline[], int nres)
1.230     brouard  12774: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   12775: {
1.235     brouard  12776:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  12777:   char resultsav[MAXLINE];
1.330     brouard  12778:   /* int resultmodel[MAXLINE]; */
1.334     brouard  12779:   /* int modelresult[MAXLINE]; */
1.230     brouard  12780:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   12781: 
1.234     brouard  12782:   removefirstspace(&resultline);
1.332     brouard  12783:   printf("decoderesult:%s\n",resultline);
1.230     brouard  12784: 
1.332     brouard  12785:   strcpy(resultsav,resultline);
1.342     brouard  12786:   /* printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline); */
1.230     brouard  12787:   if (strlen(resultsav) >1){
1.334     brouard  12788:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  12789:   }
1.353     brouard  12790:   if(j == 0 && cptcovs== 0){ /* Resultline but no =  and no covariate in the model */
1.253     brouard  12791:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   12792:     return (0);
                   12793:   }
1.234     brouard  12794:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.353     brouard  12795:     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);
                   12796:     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);
                   12797:     if(j==0)
                   12798:       return 1;
1.234     brouard  12799:   }
1.334     brouard  12800:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  12801:     if(nbocc(resultsav,'=') >1){
1.318     brouard  12802:       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  12803:       /* 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  12804:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  12805:       /* If a blank, then strc="V4=" and strd='\0' */
                   12806:       if(strc[0]=='\0'){
                   12807:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   12808:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   12809:        return 1;
                   12810:       }
1.234     brouard  12811:     }else
                   12812:       cutl(strc,strd,resultsav,'=');
1.318     brouard  12813:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  12814:     
1.230     brouard  12815:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  12816:     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  12817:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   12818:     /* cptcovsel++;     */
                   12819:     if (nbocc(stra,'=') >0)
                   12820:       strcpy(resultsav,stra); /* and analyzes it */
                   12821:   }
1.235     brouard  12822:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  12823:   /* 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  12824:   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  12825:     if(Typevar[k1]==0){ /* Single covariate in model */
                   12826:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  12827:       match=0;
1.318     brouard  12828:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   12829:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  12830:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  12831:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  12832:          break;
                   12833:        }
                   12834:       }
                   12835:       if(match == 0){
1.338     brouard  12836:        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]);
                   12837:        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  12838:        return 1;
1.234     brouard  12839:       }
1.332     brouard  12840:     }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*/
                   12841:       /* We feed resultmodel[k1]=k2; */
                   12842:       match=0;
                   12843:       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 */
                   12844:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  12845:          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  12846:          resultmodel[nres][k1]=k2; /* Added here */
1.342     brouard  12847:          /* printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]); */
1.332     brouard  12848:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   12849:          break;
                   12850:        }
                   12851:       }
                   12852:       if(match == 0){
1.338     brouard  12853:        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]);
                   12854:        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  12855:       return 1;
                   12856:       }
1.349     brouard  12857:     }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  12858:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   12859:       match=0;
1.342     brouard  12860:       /* 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  12861:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   12862:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   12863:          /* modelresult[k2]=k1; */
1.342     brouard  12864:          /* printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]); */
1.332     brouard  12865:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   12866:        }
                   12867:       }
                   12868:       if(match == 0){
1.349     brouard  12869:        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);
                   12870:        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  12871:        return 1;
                   12872:       }
                   12873:       match=0;
                   12874:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   12875:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   12876:          /* modelresult[k2]=k1;*/
1.342     brouard  12877:          /* printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]); */
1.332     brouard  12878:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   12879:          break;
                   12880:        }
                   12881:       }
                   12882:       if(match == 0){
1.349     brouard  12883:        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);
                   12884:        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  12885:        return 1;
                   12886:       }
                   12887:     }/* End of testing */
1.333     brouard  12888:   }/* End loop cptcovt */
1.235     brouard  12889:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  12890:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  12891:   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)
                   12892:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  12893:     match=0;
1.318     brouard  12894:     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  12895:       if(Typevar[k1]==0){ /* Single only */
1.349     brouard  12896:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4  What if a product?  */
1.330     brouard  12897:          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  12898:          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  12899:          ++match;
                   12900:        }
                   12901:       }
                   12902:     }
                   12903:     if(match == 0){
1.338     brouard  12904:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   12905:       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  12906:       return 1;
1.234     brouard  12907:     }else if(match > 1){
1.338     brouard  12908:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   12909:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
1.310     brouard  12910:       return 1;
1.234     brouard  12911:     }
                   12912:   }
1.334     brouard  12913:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  12914:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  12915:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  12916:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   12917:   /* 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*/
                   12918:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  12919:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   12920:   /*    1 0 0 0 */
                   12921:   /*    2 1 0 0 */
                   12922:   /*    3 0 1 0 */ 
1.330     brouard  12923:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  12924:   /*    5 0 0 1 */
1.330     brouard  12925:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  12926:   /*    7 0 1 1 */
                   12927:   /*    8 1 1 1 */
1.237     brouard  12928:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   12929:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   12930:   /* V5*age V5 known which value for nres?  */
                   12931:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  12932:   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.
                   12933:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  12934:     /* k counting number of combination of single dummies in the equation model */
                   12935:     /* k4 counting single dummies in the equation model */
                   12936:     /* k4q counting single quantitatives in the equation model */
1.344     brouard  12937:     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  12938:        /* 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  12939:       /* 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  12940:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  12941:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   12942:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   12943:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   12944:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   12945:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  12946:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  12947:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  12948:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  12949:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   12950:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   12951:       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  12952:       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  12953:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  12954:       /* Tinvresult[nres][4]=1 */
1.334     brouard  12955:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   12956:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   12957:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   12958:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  12959:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  12960:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.342     brouard  12961:       /* 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  12962:       k4++;;
1.331     brouard  12963:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  12964:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  12965:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  12966:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  12967:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   12968:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   12969:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  12970:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   12971:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   12972:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   12973:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   12974:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   12975:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  12976:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  12977:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  12978:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  12979:       /* 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  12980:       k4q++;;
1.350     brouard  12981:     }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"*/
                   12982:       /* Tvar[k1]; */ /* Age variable */ /* 17 age*V6*V2 ?*/
1.332     brouard  12983:       /* Wrong we want the value of variable name Tvar[k1] */
1.350     brouard  12984:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   12985:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   12986:       /* 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]]); */
                   12987:       }else{
                   12988:        k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   12989:        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)*/
                   12990:        TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
                   12991:        precov[nres][k1]=Tvalsel[k3];
                   12992:       }
1.342     brouard  12993:       /* 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  12994:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.350     brouard  12995:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   12996:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   12997:       /* 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]]); */
                   12998:       }else{
                   12999:        k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
                   13000:        k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
                   13001:        TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
                   13002:        precov[nres][k1]=Tvalsel[k3q];
                   13003:       }
1.342     brouard  13004:       /* 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  13005:     }else if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
1.332     brouard  13006:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
1.342     brouard  13007:       /* 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  13008:     }else{
1.332     brouard  13009:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   13010:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  13011:     }
                   13012:   }
1.234     brouard  13013:   
1.334     brouard  13014:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  13015:   return (0);
                   13016: }
1.235     brouard  13017: 
1.230     brouard  13018: int decodemodel( char model[], int lastobs)
                   13019:  /**< This routine decodes the model and returns:
1.224     brouard  13020:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   13021:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   13022:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   13023:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   13024:        * - cptcovage number of covariates with age*products =2
                   13025:        * - cptcovs number of simple covariates
1.339     brouard  13026:        * ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
1.224     brouard  13027:        * - 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  13028:        *     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
1.319     brouard  13029:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  13030:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   13031:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   13032:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   13033:        */
1.319     brouard  13034: /* 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  13035: {
1.359     brouard  13036:   int i, j, k, ks;/* , v;*/
1.349     brouard  13037:   int n,m;
                   13038:   int  j1, k1, k11, k12, k2, k3, k4;
                   13039:   char modelsav[300];
                   13040:   char stra[300], strb[300], strc[300], strd[300],stre[300],strf[300];
1.187     brouard  13041:   char *strpt;
1.349     brouard  13042:   int  **existcomb;
                   13043:   
                   13044:   existcomb=imatrix(1,NCOVMAX,1,NCOVMAX);
                   13045:   for(i=1;i<=NCOVMAX;i++)
                   13046:     for(j=1;j<=NCOVMAX;j++)
                   13047:       existcomb[i][j]=0;
                   13048:     
1.145     brouard  13049:   /*removespace(model);*/
1.136     brouard  13050:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.349     brouard  13051:     j=0, j1=0, k1=0, k12=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  13052:     if (strstr(model,"AGE") !=0){
1.192     brouard  13053:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   13054:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  13055:       return 1;
                   13056:     }
1.141     brouard  13057:     if (strstr(model,"v") !=0){
1.338     brouard  13058:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
                   13059:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
1.141     brouard  13060:       return 1;
                   13061:     }
1.187     brouard  13062:     strcpy(modelsav,model); 
                   13063:     if ((strpt=strstr(model,"age*age")) !=0){
1.338     brouard  13064:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
1.187     brouard  13065:       if(strpt != model){
1.338     brouard  13066:        printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  13067:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  13068:  corresponding column of parameters.\n",model);
1.338     brouard  13069:        fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  13070:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  13071:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  13072:        return 1;
1.225     brouard  13073:       }
1.187     brouard  13074:       nagesqr=1;
                   13075:       if (strstr(model,"+age*age") !=0)
1.234     brouard  13076:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  13077:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  13078:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  13079:       else 
1.234     brouard  13080:        substrchaine(modelsav, model, "age*age");
1.187     brouard  13081:     }else
                   13082:       nagesqr=0;
1.349     brouard  13083:     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  13084:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   13085:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.351     brouard  13086:       cptcovs=0; /**<  Number of simple covariates V1 +V1*age +V3 +V3*V4 +age*age => V1 + V3 =4+1-3=2  Wrong */
1.187     brouard  13087:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  13088:                     * cst, age and age*age 
                   13089:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   13090:       /* including age products which are counted in cptcovage.
                   13091:        * but the covariates which are products must be treated 
                   13092:        * separately: ncovn=4- 2=2 (V1+V3). */
1.349     brouard  13093:       cptcovprod=0; /**< Number of products  V1*V2 +v3*age = 2 */
                   13094:       cptcovdageprod=0; /* Number of doouble products with age age*Vn*VM or Vn*age*Vm or Vn*Vm*age */
1.187     brouard  13095:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.349     brouard  13096:       cptcovprodage=0;
                   13097:       /* cptcovprodage=nboccstr(modelsav,"age");*/
1.225     brouard  13098:       
1.187     brouard  13099:       /*   Design
                   13100:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   13101:        *  <          ncovcol=8                >
                   13102:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   13103:        *   k=  1    2      3       4     5       6      7        8
                   13104:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
1.345     brouard  13105:        *  covar[k,i], are for fixed covariates, value of kth covariate if not including age for individual i:
1.224     brouard  13106:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   13107:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  13108:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   13109:        *  Tage[++cptcovage]=k
1.345     brouard  13110:        *       if products, new covar are created after ncovcol + nqv (quanti fixed) with k1
1.187     brouard  13111:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   13112:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   13113:        *  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
                   13114:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   13115:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   13116:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
1.345     brouard  13117:        *  <          ncovcol=8  8 fixed covariate. Additional starts at 9 (V5*V6) and 10(V7*V8)              >
1.187     brouard  13118:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   13119:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
1.345     brouard  13120:        *     Tvard[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   13121:        * p Tvar[1]@12={2,   1,     3,      3,   9,     10,     8,       8}
1.187     brouard  13122:        * p Tprod[1]@2={                         6, 5}
                   13123:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   13124:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   13125:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  13126:        *How to reorganize? Tvars(orted)
1.187     brouard  13127:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   13128:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   13129:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   13130:        * Struct []
                   13131:        */
1.225     brouard  13132:       
1.187     brouard  13133:       /* This loop fills the array Tvar from the string 'model'.*/
                   13134:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   13135:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   13136:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   13137:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   13138:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   13139:       /*       k=1 Tvar[1]=2 (from V2) */
                   13140:       /*       k=5 Tvar[5] */
                   13141:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  13142:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  13143:       /*       } */
1.198     brouard  13144:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  13145:       /*
                   13146:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  13147:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   13148:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   13149:       }
1.187     brouard  13150:       cptcovage=0;
1.351     brouard  13151: 
                   13152:       /* First loop in order to calculate */
                   13153:       /* for age*VN*Vm
                   13154:        * Provides, Typevar[k], Tage[cptcovage], existcomb[n][m], FixedV[ncovcolt+k12]
                   13155:        * Tprod[k1]=k  Tposprod[k]=k1;    Tvard[k1][1] =m;
                   13156:       */
                   13157:       /* Needs  FixedV[Tvardk[k][1]] */
                   13158:       /* For others:
                   13159:        * Sets  Typevar[k];
                   13160:        * Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   13161:        *       Tposprod[k]=k11;
                   13162:        *       Tprod[k11]=k;
                   13163:        *       Tvardk[k][1] =m;
                   13164:        * Needs FixedV[Tvardk[k][1]] == 0
                   13165:       */
                   13166:       
1.319     brouard  13167:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   13168:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   13169:                                         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" */
                   13170:        if (nbocc(modelsav,'+')==0)
                   13171:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  13172:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   13173:        /*scanf("%d",i);*/
1.349     brouard  13174:        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 */
                   13175:          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  */
                   13176:          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   */
                   13177:            Typevar[k]=3;  /* 3 for age and double product age*Vn*Vm varying of fixed */
                   13178:             if(strstr(strc,"age")!=0) { /* It means that strc=V2*age or age*V2 and thus that strd=Vn */
                   13179:               cutl(stre,strf,strc,'*') ; /* strf=age or Vm, stre=Vm or age. If strc=V6*V2 then strf=V6 and stre=V2 */
                   13180:              strcpy(strc,strb); /* save strb(=age*Vn*Vm) into strc */
                   13181:              /* We want strb=Vn*Vm */
                   13182:               if(strcmp(strf,"age")==0){ /* strf is "age" so that stre=Vm =V2 . */
                   13183:                 strcpy(strb,strd);
                   13184:                 strcat(strb,"*");
                   13185:                 strcat(strb,stre);
                   13186:               }else{  /* strf=Vm  If strf=V6 then stre=V2 */
                   13187:                 strcpy(strb,strf);
                   13188:                 strcat(strb,"*");
                   13189:                 strcat(strb,stre);
                   13190:                 strcpy(strd,strb); /* in order for strd to not be "age"  for next test (will be Vn*Vm */
                   13191:               }
1.351     brouard  13192:              /* 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]]]); */
                   13193:              /* FixedV[Tvar[Tage[k]]]=0; /\* HERY not sure if V7*V4*age Fixed might not exist  yet*\/ */
1.349     brouard  13194:             }else{  /* strc=Vn*Vm (and strd=age) and should be strb=Vn*Vm but want to keep original strb double product  */
                   13195:              strcpy(stre,strb); /* save full b in stre */
                   13196:              strcpy(strb,strc); /* save short c in new short b for next block strb=Vn*Vm*/
                   13197:              strcpy(strf,strc); /* save short c in new short f */
                   13198:               cutl(strc,strd,strf,'*'); /* We get strd=Vn and strc=Vm for next block (strb=Vn*Vm)*/
                   13199:              /* strcpy(strc,stre);*/ /* save full e in c for future */
                   13200:             }
                   13201:             cptcovdageprod++; /* double product with age  Which product is it? */
                   13202:             /* 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 *\/ */
                   13203:             /* cutl(strc,strd,strb,'*'); /\* strd=  V6    or   V2     or    age and  strc=  V2 or    age or    V2 *\/ */
1.234     brouard  13204:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
1.349     brouard  13205:            n=atoi(stre);
1.234     brouard  13206:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.349     brouard  13207:            m=atoi(strc);
                   13208:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   13209:            Tage[cptcovage]=k; /* For age*V3*V2 gives the position in model of covariates associated with age Tage[1]=6 HERY too*/
                   13210:            if(existcomb[n][m] == 0){
                   13211:              /*  r /home/brouard/Documents/Recherches/REVES/Zachary/Zach-2022/Feinuo_Sun/Feinuo-threeway/femV12V15_3wayintNBe.imach */
                   13212:              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);
                   13213:              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);
                   13214:              fflush(ficlog);
                   13215:              k1++;  /* The combination Vn*Vm will be in the model so we create it at k1 */
                   13216:              k12++;
                   13217:              existcomb[n][m]=k1;
                   13218:              existcomb[m][n]=k1;
                   13219:              Tvar[k]=ncovcol+nqv+ntv+nqtv+k1;
                   13220:              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*/
                   13221:              Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 Gives the k1 double product  Vn*Vm or age*Vn*Vm at the k position */
                   13222:              Tvard[k1][1] =m; /* m 1 for V1*/
                   13223:              Tvardk[k][1] =m; /* m 1 for V1*/
                   13224:              Tvard[k1][2] =n; /* n 4 for V4*/
                   13225:              Tvardk[k][2] =n; /* n 4 for V4*/
1.351     brouard  13226: /*           Tvar[Tage[cptcovage]]=k1;*/ /* Tvar[6=age*V3*V2]=9 (new fixed covariate) */ /* We don't know about Fixed yet HERE */
1.349     brouard  13227:              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 */
                   13228:                for (i=1; i<=lastobs;i++){/* For fixed product */
                   13229:                  /* Computes the new covariate which is a product of
                   13230:                     covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   13231:                  covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   13232:                }
                   13233:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   13234:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   13235:                k12++;
                   13236:                FixedV[ncovcolt+k12]=0;
                   13237:              }else{ /*End of FixedV */
                   13238:                cptcovprodvage++; /* Counting the number of varying covariate with age */
                   13239:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   13240:                k12++;
                   13241:                FixedV[ncovcolt+k12]=1;
                   13242:              }
                   13243:            }else{  /* k1 Vn*Vm already exists */
                   13244:              k11=existcomb[n][m];
                   13245:              Tposprod[k]=k11; /* OK */
                   13246:              Tvar[k]=Tvar[Tprod[k11]]; /* HERY */
                   13247:              Tvardk[k][1]=m;
                   13248:              Tvardk[k][2]=n;
                   13249:              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 */
                   13250:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   13251:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   13252:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   13253:                Tvar[Tage[cptcovage]]=k1;
                   13254:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   13255:                k12++;
                   13256:                FixedV[ncovcolt+k12]=0;
                   13257:              }else{ /* Already exists but time varying (and age) */
                   13258:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   13259:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   13260:                /* Tvar[Tage[cptcovage]]=k1; */
                   13261:                cptcovprodvage++;
                   13262:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   13263:                k12++;
                   13264:                FixedV[ncovcolt+k12]=1;
                   13265:              }
                   13266:            }
                   13267:            /* Tage[cptcovage]=k;  /\*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   13268:            /* Tvar[k]=k11; /\* HERY *\/ */
                   13269:          } 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 */
                   13270:             cptcovprod++;
                   13271:             if (strcmp(strc,"age")==0) { /**< Model includes age: strb= Vn*age c=age d=Vn*/
                   13272:               /* covar is not filled and then is empty */
                   13273:               cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   13274:               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 */
                   13275:               Typevar[k]=1;  /* 1 for age product */
                   13276:               cptcovage++; /* Counts the number of covariates which include age as a product */
                   13277:               Tage[cptcovage]=k;  /*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   13278:              if( FixedV[Tvar[k]] == 0){
                   13279:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   13280:              }else{
                   13281:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
                   13282:              }
                   13283:               /*printf("stre=%s ", stre);*/
                   13284:             } else if (strcmp(strd,"age")==0) { /* strb= age*Vn c=Vn */
                   13285:               cutl(stre,strb,strc,'V');
                   13286:               Tvar[k]=atoi(stre);
                   13287:               Typevar[k]=1;  /* 1 for age product */
                   13288:               cptcovage++;
                   13289:               Tage[cptcovage]=k;
                   13290:              if( FixedV[Tvar[k]] == 0){
                   13291:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   13292:              }else{
                   13293:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
1.339     brouard  13294:              }
1.349     brouard  13295:             }else{ /*  for product Vn*Vm */
                   13296:              Typevar[k]=2;  /* 2 for product Vn*Vm */
                   13297:              cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   13298:              n=atoi(stre);
                   13299:              cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   13300:              m=atoi(strc);
                   13301:              k1++;
                   13302:              cptcovprodnoage++;
                   13303:              if(existcomb[n][m] != 0 || existcomb[m][n] != 0){
                   13304:                printf("Warning in model combination V%d*V%d already exists in the model in position k1=%d!\n",n,m,existcomb[n][m]);
                   13305:                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]);
                   13306:                fflush(ficlog);
                   13307:                k11=existcomb[n][m];
                   13308:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   13309:                Tposprod[k]=k11;
                   13310:                Tprod[k11]=k;
                   13311:                Tvardk[k][1] =m; /* m 1 for V1*/
                   13312:                /* Tvard[k11][1] =m; /\* n 4 for V4*\/ */
                   13313:                Tvardk[k][2] =n; /* n 4 for V4*/                
                   13314:                /* Tvard[k11][2] =n; /\* n 4 for V4*\/ */
                   13315:              }else{ /* combination Vn*Vm doesn't exist we create it (no age)*/
                   13316:                existcomb[n][m]=k1;
                   13317:                existcomb[m][n]=k1;
                   13318:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
                   13319:                                                    because this model-covariate is a construction we invent a new column
                   13320:                                                    which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   13321:                                                    If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
                   13322:                                                    thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
                   13323:                                                    Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
                   13324:                /* Please remark that the new variables are model dependent */
                   13325:                /* If we have 4 variable but the model uses only 3, like in
                   13326:                 * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   13327:                 *  k=     1     2      3   4     5        6        7       8
                   13328:                 * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   13329:                 * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   13330:                 * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   13331:                 */
                   13332:                /* We need to feed some variables like TvarVV, but later on next loop because of ncovv (k2) is not correct */
                   13333:                Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 +V6*V2*age  */
                   13334:                Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
                   13335:                Tvard[k1][1] =m; /* m 1 for V1*/
                   13336:                Tvardk[k][1] =m; /* m 1 for V1*/
                   13337:                Tvard[k1][2] =n; /* n 4 for V4*/
                   13338:                Tvardk[k][2] =n; /* n 4 for V4*/
                   13339:                k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   13340:                /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   13341:                /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
                   13342:                /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
                   13343:                /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   13344:                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 */
                   13345:                  for (i=1; i<=lastobs;i++){/* For fixed product */
                   13346:                    /* Computes the new covariate which is a product of
                   13347:                       covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   13348:                    covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   13349:                  }
                   13350:                  /* TvarVV[k2]=n; */
                   13351:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13352:                  /* TvarVV[k2+1]=m; */
                   13353:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13354:                }else{ /* not FixedV */
                   13355:                  /* TvarVV[k2]=n; */
                   13356:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13357:                  /* TvarVV[k2+1]=m; */
                   13358:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13359:                }                 
                   13360:              }  /* End of creation of Vn*Vm if not created by age*Vn*Vm earlier  */
                   13361:            } /*  End of product Vn*Vm */
                   13362:           } /* End of age*double product or simple product */
                   13363:        }else { /* not a product */
1.234     brouard  13364:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   13365:          /*  scanf("%d",i);*/
                   13366:          cutl(strd,strc,strb,'V');
                   13367:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   13368:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   13369:          Tvar[k]=atoi(strd);
                   13370:          Typevar[k]=0;  /* 0 for simple covariates */
                   13371:        }
                   13372:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  13373:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  13374:                                  scanf("%d",i);*/
1.187     brouard  13375:       } /* end of loop + on total covariates */
1.351     brouard  13376: 
                   13377:       
1.187     brouard  13378:     } /* end if strlen(modelsave == 0) age*age might exist */
                   13379:   } /* end if strlen(model == 0) */
1.349     brouard  13380:   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  */
                   13381: 
1.136     brouard  13382:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   13383:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  13384:   
1.136     brouard  13385:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  13386:      printf("cptcovprod=%d ", cptcovprod);
                   13387:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   13388:      scanf("%d ",i);*/
                   13389: 
                   13390: 
1.230     brouard  13391: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   13392:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  13393: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   13394:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   13395:    k =           1    2   3     4       5       6      7      8        9
                   13396:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  13397:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  13398:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   13399:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   13400:          Tmodelind[combination of covar]=k;
1.225     brouard  13401: */  
                   13402: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  13403:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  13404:   /* 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  13405:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  13406:   printf("Model=1+age+%s\n\
1.349     brouard  13407: 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  13408: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   13409: 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  13410:   fprintf(ficlog,"Model=1+age+%s\n\
1.349     brouard  13411: 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  13412: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   13413: 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  13414:   for(k=-1;k<=NCOVMAX; k++){ Fixed[k]=0; Dummy[k]=0;}
                   13415:   for(k=1;k<=NCOVMAX; k++){TvarFind[k]=0; TvarVind[k]=0;}
1.351     brouard  13416: 
                   13417: 
                   13418:   /* Second loop for calculating  Fixed[k], Dummy[k]*/
                   13419: 
                   13420:   
1.349     brouard  13421:   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  13422:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  13423:       Fixed[k]= 0;
                   13424:       Dummy[k]= 0;
1.225     brouard  13425:       ncoveff++;
1.232     brouard  13426:       ncovf++;
1.234     brouard  13427:       nsd++;
                   13428:       modell[k].maintype= FTYPE;
                   13429:       TvarsD[nsd]=Tvar[k];
                   13430:       TvarsDind[nsd]=k;
1.330     brouard  13431:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  13432:       TvarF[ncovf]=Tvar[k];
                   13433:       TvarFind[ncovf]=k;
                   13434:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   13435:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.339     brouard  13436:     /* }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  13437:     }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  13438:       Fixed[k]= 0;
                   13439:       Dummy[k]= 1;
1.230     brouard  13440:       nqfveff++;
1.234     brouard  13441:       modell[k].maintype= FTYPE;
                   13442:       modell[k].subtype= FQ;
                   13443:       nsq++;
1.334     brouard  13444:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   13445:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  13446:       ncovf++;
1.234     brouard  13447:       TvarF[ncovf]=Tvar[k];
                   13448:       TvarFind[ncovf]=k;
1.231     brouard  13449:       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  13450:       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  13451:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.339     brouard  13452:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   13453:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   13454:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   13455:       ncovvt++;
                   13456:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   13457:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
                   13458: 
1.227     brouard  13459:       Fixed[k]= 1;
                   13460:       Dummy[k]= 0;
1.225     brouard  13461:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  13462:       modell[k].maintype= VTYPE;
                   13463:       modell[k].subtype= VD;
                   13464:       nsd++;
                   13465:       TvarsD[nsd]=Tvar[k];
                   13466:       TvarsDind[nsd]=k;
1.330     brouard  13467:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  13468:       ncovv++; /* Only simple time varying variables */
                   13469:       TvarV[ncovv]=Tvar[k];
1.242     brouard  13470:       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  13471:       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 */
                   13472:       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  13473:       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);
                   13474:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  13475:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.339     brouard  13476:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   13477:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   13478:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   13479:       ncovvt++;
                   13480:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   13481:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   13482:       
1.234     brouard  13483:       Fixed[k]= 1;
                   13484:       Dummy[k]= 1;
                   13485:       nqtveff++;
                   13486:       modell[k].maintype= VTYPE;
                   13487:       modell[k].subtype= VQ;
                   13488:       ncovv++; /* Only simple time varying variables */
                   13489:       nsq++;
1.334     brouard  13490:       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) */
                   13491:       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  13492:       TvarV[ncovv]=Tvar[k];
1.242     brouard  13493:       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  13494:       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 */
                   13495:       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  13496:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   13497:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
1.349     brouard  13498:       /* 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  13499:       /* printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv); */
1.227     brouard  13500:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  13501:       ncova++;
                   13502:       TvarA[ncova]=Tvar[k];
                   13503:       TvarAind[ncova]=k;
1.349     brouard  13504:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   13505:       /** 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  13506:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  13507:        Fixed[k]= 2;
                   13508:        Dummy[k]= 2;
                   13509:        modell[k].maintype= ATYPE;
                   13510:        modell[k].subtype= APFD;
1.349     brouard  13511:        ncovta++;
                   13512:        TvarAVVA[ncovta]=Tvar[k]; /*  (2)age*V3 */
                   13513:        TvarAVVAind[ncovta]=k;
1.240     brouard  13514:        /* ncoveff++; */
1.227     brouard  13515:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  13516:        Fixed[k]= 2;
                   13517:        Dummy[k]= 3;
                   13518:        modell[k].maintype= ATYPE;
                   13519:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
1.349     brouard  13520:        ncovta++;
                   13521:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   13522:        TvarAVVAind[ncovta]=k;
1.240     brouard  13523:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  13524:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  13525:        Fixed[k]= 3;
                   13526:        Dummy[k]= 2;
                   13527:        modell[k].maintype= ATYPE;
                   13528:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
1.349     brouard  13529:        ncovva++;
                   13530:        TvarVVA[ncovva]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   13531:        TvarVVAind[ncovva]=k;
                   13532:        ncovta++;
                   13533:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   13534:        TvarAVVAind[ncovta]=k;
1.240     brouard  13535:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  13536:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  13537:        Fixed[k]= 3;
                   13538:        Dummy[k]= 3;
                   13539:        modell[k].maintype= ATYPE;
                   13540:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
1.349     brouard  13541:        ncovva++;
                   13542:        TvarVVA[ncovva]=Tvar[k]; /*   */
                   13543:        TvarVVAind[ncovva]=k;
                   13544:        ncovta++;
                   13545:        TvarAVVA[ncovta]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   13546:        TvarAVVAind[ncovta]=k;
1.240     brouard  13547:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  13548:       }
1.349     brouard  13549:     }else if( Tposprod[k]>0  &&  Typevar[k]==2){  /* Detects if fixed product no age Vm*Vn */
                   13550:       printf("MEMORY ERRORR k=%d  Tposprod[k]=%d, Typevar[k]=%d\n ",k, Tposprod[k], Typevar[k]);
                   13551:       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 */
                   13552:       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]]);
                   13553:        Fixed[k]= 0;
                   13554:        Dummy[k]= 0;
                   13555:        ncoveff++;
                   13556:        ncovf++;
                   13557:        /* ncovv++; */
                   13558:        /* TvarVV[ncovv]=Tvardk[k][1]; */
                   13559:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13560:        /* ncovv++; */
                   13561:        /* TvarVV[ncovv]=Tvardk[k][2]; */
                   13562:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13563:        modell[k].maintype= FTYPE;
                   13564:        TvarF[ncovf]=Tvar[k];
                   13565:        /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
                   13566:        TvarFind[ncovf]=k;
                   13567:        TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   13568:        TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   13569:       }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  */
                   13570:        /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   13571:        /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   13572:        /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   13573:        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 */
                   13574:        ncovvt++;
                   13575:        TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   13576:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   13577:        ncovvt++;
                   13578:        TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   13579:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   13580:        
                   13581:        /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   13582:        /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   13583:        
                   13584:        if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   13585:          if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
                   13586:            Fixed[k]= 1;
                   13587:            Dummy[k]= 0;
                   13588:            modell[k].maintype= FTYPE;
                   13589:            modell[k].subtype= FPDD;            /*      Product fixed dummy * fixed dummy */
                   13590:            ncovf++; /* Fixed variables without age */
                   13591:            TvarF[ncovf]=Tvar[k];
                   13592:            TvarFind[ncovf]=k;
                   13593:          }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
                   13594:            Fixed[k]= 0;  /* Fixed product */
                   13595:            Dummy[k]= 1;
                   13596:            modell[k].maintype= FTYPE;
                   13597:            modell[k].subtype= FPDQ;            /*      Product fixed dummy * fixed quantitative */
                   13598:            ncovf++; /* Varying variables without age */
                   13599:            TvarF[ncovf]=Tvar[k];
                   13600:            TvarFind[ncovf]=k;
                   13601:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
                   13602:            Fixed[k]= 1;
                   13603:            Dummy[k]= 0;
                   13604:            modell[k].maintype= VTYPE;
                   13605:            modell[k].subtype= VPDD;            /*      Product fixed dummy * varying dummy */
                   13606:            ncovv++; /* Varying variables without age */
                   13607:            TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   13608:            TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
                   13609:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
                   13610:            Fixed[k]= 1;
                   13611:            Dummy[k]= 1;
                   13612:            modell[k].maintype= VTYPE;
                   13613:            modell[k].subtype= VPDQ;            /*      Product fixed dummy * varying quantitative */
                   13614:            ncovv++; /* Varying variables without age */
                   13615:            TvarV[ncovv]=Tvar[k];
                   13616:            TvarVind[ncovv]=k;
                   13617:          }
                   13618:        }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   13619:          if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
                   13620:            Fixed[k]= 0;  /*  Fixed product */
                   13621:            Dummy[k]= 1;
                   13622:            modell[k].maintype= FTYPE;
                   13623:            modell[k].subtype= FPDQ;            /*      Product fixed quantitative * fixed dummy */
                   13624:            ncovf++; /* Fixed variables without age */
                   13625:            TvarF[ncovf]=Tvar[k];
                   13626:            TvarFind[ncovf]=k;
                   13627:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
                   13628:            Fixed[k]= 1;
                   13629:            Dummy[k]= 1;
                   13630:            modell[k].maintype= VTYPE;
                   13631:            modell[k].subtype= VPDQ;            /*      Product fixed quantitative * varying dummy */
                   13632:            ncovv++; /* Varying variables without age */
                   13633:            TvarV[ncovv]=Tvar[k];
                   13634:            TvarVind[ncovv]=k;
                   13635:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
                   13636:            Fixed[k]= 1;
                   13637:            Dummy[k]= 1;
                   13638:            modell[k].maintype= VTYPE;
                   13639:            modell[k].subtype= VPQQ;            /*      Product fixed quantitative * varying quantitative */
                   13640:            ncovv++; /* Varying variables without age */
                   13641:            TvarV[ncovv]=Tvar[k];
                   13642:            TvarVind[ncovv]=k;
                   13643:            ncovv++; /* Varying variables without age */
                   13644:            TvarV[ncovv]=Tvar[k];
                   13645:            TvarVind[ncovv]=k;
                   13646:          }
                   13647:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
                   13648:          if(Tvard[k1][2] <=ncovcol){
                   13649:            Fixed[k]= 1;
                   13650:            Dummy[k]= 1;
                   13651:            modell[k].maintype= VTYPE;
                   13652:            modell[k].subtype= VPDD;            /*      Product time varying dummy * fixed dummy */
                   13653:            ncovv++; /* Varying variables without age */
                   13654:            TvarV[ncovv]=Tvar[k];
                   13655:            TvarVind[ncovv]=k;
                   13656:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   13657:            Fixed[k]= 1;
                   13658:            Dummy[k]= 1;
                   13659:            modell[k].maintype= VTYPE;
                   13660:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * fixed quantitative */
                   13661:            ncovv++; /* Varying variables without age */
                   13662:            TvarV[ncovv]=Tvar[k];
                   13663:            TvarVind[ncovv]=k;
                   13664:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   13665:            Fixed[k]= 1;
                   13666:            Dummy[k]= 0;
                   13667:            modell[k].maintype= VTYPE;
                   13668:            modell[k].subtype= VPDD;            /*      Product time varying dummy * time varying dummy */
                   13669:            ncovv++; /* Varying variables without age */
                   13670:            TvarV[ncovv]=Tvar[k];
                   13671:            TvarVind[ncovv]=k;
                   13672:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   13673:            Fixed[k]= 1;
                   13674:            Dummy[k]= 1;
                   13675:            modell[k].maintype= VTYPE;
                   13676:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * time varying quantitative */
                   13677:            ncovv++; /* Varying variables without age */
                   13678:            TvarV[ncovv]=Tvar[k];
                   13679:            TvarVind[ncovv]=k;
                   13680:          }
                   13681:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
                   13682:          if(Tvard[k1][2] <=ncovcol){
                   13683:            Fixed[k]= 1;
                   13684:            Dummy[k]= 1;
                   13685:            modell[k].maintype= VTYPE;
                   13686:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * fixed dummy */
                   13687:            ncovv++; /* Varying variables without age */
                   13688:            TvarV[ncovv]=Tvar[k];
                   13689:            TvarVind[ncovv]=k;
                   13690:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   13691:            Fixed[k]= 1;
                   13692:            Dummy[k]= 1;
                   13693:            modell[k].maintype= VTYPE;
                   13694:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * fixed quantitative */
                   13695:            ncovv++; /* Varying variables without age */
                   13696:            TvarV[ncovv]=Tvar[k];
                   13697:            TvarVind[ncovv]=k;
                   13698:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   13699:            Fixed[k]= 1;
                   13700:            Dummy[k]= 1;
                   13701:            modell[k].maintype= VTYPE;
                   13702:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * time varying dummy */
                   13703:            ncovv++; /* Varying variables without age */
                   13704:            TvarV[ncovv]=Tvar[k];
                   13705:            TvarVind[ncovv]=k;
                   13706:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   13707:            Fixed[k]= 1;
                   13708:            Dummy[k]= 1;
                   13709:            modell[k].maintype= VTYPE;
                   13710:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * time varying quantitative */
                   13711:            ncovv++; /* Varying variables without age */
                   13712:            TvarV[ncovv]=Tvar[k];
                   13713:            TvarVind[ncovv]=k;
                   13714:          }
                   13715:        }else{
                   13716:          printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   13717:          fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   13718:        } /*end k1*/
                   13719:       }
                   13720:     }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  13721:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  13722:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   13723:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   13724:       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 */
                   13725:       ncova++;
                   13726:       TvarA[ncova]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   13727:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   13728:       ncova++;
                   13729:       TvarA[ncova]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   13730:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
1.339     brouard  13731: 
1.349     brouard  13732:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   13733:       /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   13734:       if( FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){
                   13735:        ncovta++;
                   13736:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   13737:        TvarAVVAind[ncovta]=k;
                   13738:        ncovta++;
                   13739:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   13740:        TvarAVVAind[ncovta]=k;
                   13741:       }else{
                   13742:        ncovva++;  /* HERY  reached */
                   13743:        TvarVVA[ncovva]=Tvard[k1][1]; /*  age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4  */
                   13744:        TvarVVAind[ncovva]=k;
                   13745:        ncovva++;
                   13746:        TvarVVA[ncovva]=Tvard[k1][2]; /*   */
                   13747:        TvarVVAind[ncovva]=k;
                   13748:        ncovta++;
                   13749:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   13750:        TvarAVVAind[ncovta]=k;
                   13751:        ncovta++;
                   13752:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   13753:        TvarAVVAind[ncovta]=k;
                   13754:       }
1.339     brouard  13755:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   13756:        if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
1.349     brouard  13757:          Fixed[k]= 2;
                   13758:          Dummy[k]= 2;
1.240     brouard  13759:          modell[k].maintype= FTYPE;
                   13760:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
1.349     brouard  13761:          /* TvarF[ncova]=Tvar[k];   /\* Problem to solve *\/ */
                   13762:          /* TvarFind[ncova]=k; */
1.339     brouard  13763:        }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
1.349     brouard  13764:          Fixed[k]= 2;  /* Fixed product */
                   13765:          Dummy[k]= 3;
1.240     brouard  13766:          modell[k].maintype= FTYPE;
                   13767:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
1.349     brouard  13768:          /* TvarF[ncova]=Tvar[k]; */
                   13769:          /* TvarFind[ncova]=k; */
1.339     brouard  13770:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
1.349     brouard  13771:          Fixed[k]= 3;
                   13772:          Dummy[k]= 2;
1.240     brouard  13773:          modell[k].maintype= VTYPE;
                   13774:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
1.349     brouard  13775:          TvarV[ncova]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   13776:          TvarVind[ncova]=k;/* TvarVind[1]=5 */ 
1.339     brouard  13777:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
1.349     brouard  13778:          Fixed[k]= 3;
                   13779:          Dummy[k]= 3;
1.240     brouard  13780:          modell[k].maintype= VTYPE;
                   13781:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
1.349     brouard  13782:          /* ncovv++; /\* Varying variables without age *\/ */
                   13783:          /* TvarV[ncovv]=Tvar[k]; */
                   13784:          /* TvarVind[ncovv]=k; */
1.240     brouard  13785:        }
1.339     brouard  13786:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   13787:        if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
1.349     brouard  13788:          Fixed[k]= 2;  /*  Fixed product */
                   13789:          Dummy[k]= 2;
1.240     brouard  13790:          modell[k].maintype= FTYPE;
                   13791:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
1.349     brouard  13792:          /* ncova++; /\* Fixed variables with age *\/ */
                   13793:          /* TvarF[ncovf]=Tvar[k]; */
                   13794:          /* TvarFind[ncovf]=k; */
1.339     brouard  13795:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
1.349     brouard  13796:          Fixed[k]= 2;
                   13797:          Dummy[k]= 3;
1.240     brouard  13798:          modell[k].maintype= VTYPE;
                   13799:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
1.349     brouard  13800:          /* ncova++; /\* Varying variables with age *\/ */
                   13801:          /* TvarV[ncova]=Tvar[k]; */
                   13802:          /* TvarVind[ncova]=k; */
1.339     brouard  13803:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
1.349     brouard  13804:          Fixed[k]= 3;
                   13805:          Dummy[k]= 2;
1.240     brouard  13806:          modell[k].maintype= VTYPE;
                   13807:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
1.349     brouard  13808:          ncova++; /* Varying variables without age */
                   13809:          TvarV[ncova]=Tvar[k];
                   13810:          TvarVind[ncova]=k;
                   13811:          /* ncova++; /\* Varying variables without age *\/ */
                   13812:          /* TvarV[ncova]=Tvar[k]; */
                   13813:          /* TvarVind[ncova]=k; */
1.240     brouard  13814:        }
1.339     brouard  13815:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
1.240     brouard  13816:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  13817:          Fixed[k]= 2;
                   13818:          Dummy[k]= 2;
1.240     brouard  13819:          modell[k].maintype= VTYPE;
                   13820:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
1.349     brouard  13821:          /* ncova++; /\* Varying variables with age *\/ */
                   13822:          /* TvarV[ncova]=Tvar[k]; */
                   13823:          /* TvarVind[ncova]=k; */
1.240     brouard  13824:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  13825:          Fixed[k]= 2;
                   13826:          Dummy[k]= 3;
1.240     brouard  13827:          modell[k].maintype= VTYPE;
                   13828:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
1.349     brouard  13829:          /* ncova++; /\* Varying variables with age *\/ */
                   13830:          /* TvarV[ncova]=Tvar[k]; */
                   13831:          /* TvarVind[ncova]=k; */
1.240     brouard  13832:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349     brouard  13833:          Fixed[k]= 3;
                   13834:          Dummy[k]= 2;
1.240     brouard  13835:          modell[k].maintype= VTYPE;
                   13836:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
1.349     brouard  13837:          /* ncova++; /\* Varying variables with age *\/ */
                   13838:          /* TvarV[ncova]=Tvar[k]; */
                   13839:          /* TvarVind[ncova]=k; */
1.240     brouard  13840:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  13841:          Fixed[k]= 3;
                   13842:          Dummy[k]= 3;
1.240     brouard  13843:          modell[k].maintype= VTYPE;
                   13844:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
1.349     brouard  13845:          /* ncova++; /\* Varying variables with age *\/ */
                   13846:          /* TvarV[ncova]=Tvar[k]; */
                   13847:          /* TvarVind[ncova]=k; */
1.240     brouard  13848:        }
1.339     brouard  13849:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
1.240     brouard  13850:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  13851:          Fixed[k]= 2;
                   13852:          Dummy[k]= 2;
1.240     brouard  13853:          modell[k].maintype= VTYPE;
                   13854:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
1.349     brouard  13855:          /* ncova++; /\* Varying variables with age *\/ */
                   13856:          /* TvarV[ncova]=Tvar[k]; */
                   13857:          /* TvarVind[ncova]=k; */
1.240     brouard  13858:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  13859:          Fixed[k]= 2;
                   13860:          Dummy[k]= 3;
1.240     brouard  13861:          modell[k].maintype= VTYPE;
                   13862:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
1.349     brouard  13863:          /* ncova++; /\* Varying variables with age *\/ */
                   13864:          /* TvarV[ncova]=Tvar[k]; */
                   13865:          /* TvarVind[ncova]=k; */
1.240     brouard  13866:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349     brouard  13867:          Fixed[k]= 3;
                   13868:          Dummy[k]= 2;
1.240     brouard  13869:          modell[k].maintype= VTYPE;
                   13870:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
1.349     brouard  13871:          /* ncova++; /\* Varying variables with age *\/ */
                   13872:          /* TvarV[ncova]=Tvar[k]; */
                   13873:          /* TvarVind[ncova]=k; */
1.240     brouard  13874:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  13875:          Fixed[k]= 3;
                   13876:          Dummy[k]= 3;
1.240     brouard  13877:          modell[k].maintype= VTYPE;
                   13878:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
1.349     brouard  13879:          /* ncova++; /\* Varying variables with age *\/ */
                   13880:          /* TvarV[ncova]=Tvar[k]; */
                   13881:          /* TvarVind[ncova]=k; */
1.240     brouard  13882:        }
1.227     brouard  13883:       }else{
1.240     brouard  13884:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   13885:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   13886:       } /*end k1*/
1.349     brouard  13887:     } else{
1.226     brouard  13888:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   13889:       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  13890:     }
1.342     brouard  13891:     /* 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]); */
                   13892:     /* printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype); */
1.227     brouard  13893:     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]);
                   13894:   }
1.349     brouard  13895:   ncovvta=ncovva;
1.227     brouard  13896:   /* Searching for doublons in the model */
                   13897:   for(k1=1; k1<= cptcovt;k1++){
                   13898:     for(k2=1; k2 <k1;k2++){
1.285     brouard  13899:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   13900:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  13901:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   13902:          if(Tvar[k1]==Tvar[k2]){
1.338     brouard  13903:            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]);
                   13904:            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  13905:            return(1);
                   13906:          }
                   13907:        }else if (Typevar[k1] ==2){
                   13908:          k3=Tposprod[k1];
                   13909:          k4=Tposprod[k2];
                   13910:          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  13911:            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]]);
                   13912:            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  13913:            return(1);
                   13914:          }
                   13915:        }
1.227     brouard  13916:       }
                   13917:     }
1.225     brouard  13918:   }
                   13919:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   13920:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  13921:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   13922:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.349     brouard  13923: 
                   13924:   free_imatrix(existcomb,1,NCOVMAX,1,NCOVMAX);
1.137     brouard  13925:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  13926:   /*endread:*/
1.225     brouard  13927:   printf("Exiting decodemodel: ");
                   13928:   return (1);
1.136     brouard  13929: }
                   13930: 
1.169     brouard  13931: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  13932: {/* Check ages at death */
1.136     brouard  13933:   int i, m;
1.218     brouard  13934:   int firstone=0;
                   13935:   
1.136     brouard  13936:   for (i=1; i<=imx; i++) {
                   13937:     for(m=2; (m<= maxwav); m++) {
                   13938:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   13939:        anint[m][i]=9999;
1.216     brouard  13940:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   13941:          s[m][i]=-1;
1.136     brouard  13942:       }
                   13943:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  13944:        *nberr = *nberr + 1;
1.218     brouard  13945:        if(firstone == 0){
                   13946:          firstone=1;
1.260     brouard  13947:        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  13948:        }
1.262     brouard  13949:        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  13950:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  13951:       }
                   13952:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  13953:        (*nberr)++;
1.259     brouard  13954:        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  13955:        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  13956:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  13957:       }
                   13958:     }
                   13959:   }
                   13960: 
                   13961:   for (i=1; i<=imx; i++)  {
                   13962:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   13963:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  13964:       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  13965:        if (s[m][i] >= nlstate+1) {
1.169     brouard  13966:          if(agedc[i]>0){
                   13967:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  13968:              agev[m][i]=agedc[i];
1.214     brouard  13969:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  13970:            }else {
1.136     brouard  13971:              if ((int)andc[i]!=9999){
                   13972:                nbwarn++;
                   13973:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   13974:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   13975:                agev[m][i]=-1;
                   13976:              }
                   13977:            }
1.169     brouard  13978:          } /* agedc > 0 */
1.214     brouard  13979:        } /* end if */
1.136     brouard  13980:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   13981:                                 years but with the precision of a month */
                   13982:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   13983:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   13984:            agev[m][i]=1;
                   13985:          else if(agev[m][i] < *agemin){ 
                   13986:            *agemin=agev[m][i];
                   13987:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   13988:          }
                   13989:          else if(agev[m][i] >*agemax){
                   13990:            *agemax=agev[m][i];
1.156     brouard  13991:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  13992:          }
                   13993:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   13994:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  13995:        } /* en if 9*/
1.136     brouard  13996:        else { /* =9 */
1.214     brouard  13997:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  13998:          agev[m][i]=1;
                   13999:          s[m][i]=-1;
                   14000:        }
                   14001:       }
1.214     brouard  14002:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  14003:        agev[m][i]=1;
1.214     brouard  14004:       else{
                   14005:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   14006:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   14007:        agev[m][i]=0;
                   14008:       }
                   14009:     } /* End for lastpass */
                   14010:   }
1.136     brouard  14011:     
                   14012:   for (i=1; i<=imx; i++)  {
                   14013:     for(m=firstpass; (m<=lastpass); m++){
                   14014:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  14015:        (*nberr)++;
1.136     brouard  14016:        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);     
                   14017:        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);     
                   14018:        return 1;
                   14019:       }
                   14020:     }
                   14021:   }
                   14022: 
                   14023:   /*for (i=1; i<=imx; i++){
                   14024:   for (m=firstpass; (m<lastpass); m++){
                   14025:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   14026: }
                   14027: 
                   14028: }*/
                   14029: 
                   14030: 
1.139     brouard  14031:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   14032:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  14033: 
                   14034:   return (0);
1.164     brouard  14035:  /* endread:*/
1.136     brouard  14036:     printf("Exiting calandcheckages: ");
                   14037:     return (1);
                   14038: }
                   14039: 
1.172     brouard  14040: #if defined(_MSC_VER)
                   14041: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   14042: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   14043: //#include "stdafx.h"
                   14044: //#include <stdio.h>
                   14045: //#include <tchar.h>
                   14046: //#include <windows.h>
                   14047: //#include <iostream>
                   14048: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   14049: 
                   14050: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   14051: 
                   14052: BOOL IsWow64()
                   14053: {
                   14054:        BOOL bIsWow64 = FALSE;
                   14055: 
                   14056:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   14057:        //  (HANDLE, PBOOL);
                   14058: 
                   14059:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   14060: 
                   14061:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   14062:        const char funcName[] = "IsWow64Process";
                   14063:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   14064:                GetProcAddress(module, funcName);
                   14065: 
                   14066:        if (NULL != fnIsWow64Process)
                   14067:        {
                   14068:                if (!fnIsWow64Process(GetCurrentProcess(),
                   14069:                        &bIsWow64))
                   14070:                        //throw std::exception("Unknown error");
                   14071:                        printf("Unknown error\n");
                   14072:        }
                   14073:        return bIsWow64 != FALSE;
                   14074: }
                   14075: #endif
1.177     brouard  14076: 
1.191     brouard  14077: void syscompilerinfo(int logged)
1.292     brouard  14078: {
                   14079: #include <stdint.h>
                   14080: 
                   14081:   /* #include "syscompilerinfo.h"*/
1.185     brouard  14082:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   14083:    /* /GS /W3 /Gy
                   14084:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   14085:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   14086:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  14087:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   14088:    */ 
                   14089:    /* 64 bits */
1.185     brouard  14090:    /*
                   14091:      /GS /W3 /Gy
                   14092:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   14093:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   14094:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   14095:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   14096:    /* Optimization are useless and O3 is slower than O2 */
                   14097:    /*
                   14098:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   14099:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   14100:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   14101:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   14102:    */
1.186     brouard  14103:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  14104:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   14105:       /PDB:"visual studio
                   14106:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   14107:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   14108:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   14109:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   14110:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   14111:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   14112:       uiAccess='false'"
                   14113:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   14114:       /NOLOGO /TLBID:1
                   14115:    */
1.292     brouard  14116: 
                   14117: 
1.177     brouard  14118: #if defined __INTEL_COMPILER
1.178     brouard  14119: #if defined(__GNUC__)
                   14120:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   14121: #endif
1.177     brouard  14122: #elif defined(__GNUC__) 
1.179     brouard  14123: #ifndef  __APPLE__
1.174     brouard  14124: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  14125: #endif
1.177     brouard  14126:    struct utsname sysInfo;
1.178     brouard  14127:    int cross = CROSS;
                   14128:    if (cross){
                   14129:           printf("Cross-");
1.191     brouard  14130:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  14131:    }
1.174     brouard  14132: #endif
                   14133: 
1.191     brouard  14134:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  14135: #if defined(__clang__)
1.191     brouard  14136:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  14137: #endif
                   14138: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  14139:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  14140: #endif
                   14141: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  14142:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  14143: #endif
                   14144: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  14145:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  14146: #endif
                   14147: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  14148:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  14149: #endif
                   14150: #if defined(_MSC_VER)
1.191     brouard  14151:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  14152: #endif
                   14153: #if defined(__PGI)
1.191     brouard  14154:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  14155: #endif
                   14156: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  14157:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  14158: #endif
1.191     brouard  14159:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  14160:    
1.167     brouard  14161: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   14162: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   14163:     // Windows (x64 and x86)
1.191     brouard  14164:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  14165: #elif __unix__ // all unices, not all compilers
                   14166:     // Unix
1.191     brouard  14167:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  14168: #elif __linux__
                   14169:     // linux
1.191     brouard  14170:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  14171: #elif __APPLE__
1.174     brouard  14172:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  14173:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  14174: #endif
                   14175: 
                   14176: /*  __MINGW32__          */
                   14177: /*  __CYGWIN__  */
                   14178: /* __MINGW64__  */
                   14179: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   14180: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   14181: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   14182: /* _WIN64  // Defined for applications for Win64. */
                   14183: /* _M_X64 // Defined for compilations that target x64 processors. */
                   14184: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  14185: 
1.167     brouard  14186: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  14187:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  14188: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  14189:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  14190: #else
1.191     brouard  14191:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  14192: #endif
                   14193: 
1.169     brouard  14194: #if defined(__GNUC__)
                   14195: # if defined(__GNUC_PATCHLEVEL__)
                   14196: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   14197:                             + __GNUC_MINOR__ * 100 \
                   14198:                             + __GNUC_PATCHLEVEL__)
                   14199: # else
                   14200: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   14201:                             + __GNUC_MINOR__ * 100)
                   14202: # endif
1.174     brouard  14203:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  14204:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  14205: 
                   14206:    if (uname(&sysInfo) != -1) {
                   14207:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  14208:         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  14209:    }
                   14210:    else
                   14211:       perror("uname() error");
1.179     brouard  14212:    //#ifndef __INTEL_COMPILER 
                   14213: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  14214:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  14215:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  14216: #endif
1.169     brouard  14217: #endif
1.172     brouard  14218: 
1.286     brouard  14219:    //   void main ()
1.172     brouard  14220:    //   {
1.169     brouard  14221: #if defined(_MSC_VER)
1.174     brouard  14222:    if (IsWow64()){
1.191     brouard  14223:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   14224:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  14225:    }
                   14226:    else{
1.191     brouard  14227:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   14228:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  14229:    }
1.172     brouard  14230:    //     printf("\nPress Enter to continue...");
                   14231:    //     getchar();
                   14232:    //   }
                   14233: 
1.169     brouard  14234: #endif
                   14235:    
1.167     brouard  14236: 
1.219     brouard  14237: }
1.136     brouard  14238: 
1.219     brouard  14239: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  14240:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  14241:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  14242:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  14243:   /* double ftolpl = 1.e-10; */
1.180     brouard  14244:   double age, agebase, agelim;
1.203     brouard  14245:   double tot;
1.180     brouard  14246: 
1.202     brouard  14247:   strcpy(filerespl,"PL_");
                   14248:   strcat(filerespl,fileresu);
                   14249:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  14250:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   14251:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  14252:   }
1.288     brouard  14253:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   14254:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  14255:   pstamp(ficrespl);
1.288     brouard  14256:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  14257:   fprintf(ficrespl,"#Age ");
                   14258:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   14259:   fprintf(ficrespl,"\n");
1.180     brouard  14260:   
1.219     brouard  14261:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  14262: 
1.219     brouard  14263:   agebase=ageminpar;
                   14264:   agelim=agemaxpar;
1.180     brouard  14265: 
1.227     brouard  14266:   /* i1=pow(2,ncoveff); */
1.234     brouard  14267:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  14268:   if (cptcovn < 1){i1=1;}
1.180     brouard  14269: 
1.337     brouard  14270:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
1.238     brouard  14271:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  14272:       k=TKresult[nres];
1.338     brouard  14273:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  14274:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
                   14275:       /*       continue; */
1.235     brouard  14276: 
1.238     brouard  14277:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   14278:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   14279:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   14280:       /* k=k+1; */
                   14281:       /* to clean */
1.332     brouard  14282:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  14283:       fprintf(ficrespl,"#******");
                   14284:       printf("#******");
                   14285:       fprintf(ficlog,"#******");
1.337     brouard  14286:       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  14287:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
1.337     brouard  14288:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14289:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14290:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14291:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14292:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14293:       }
                   14294:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   14295:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14296:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14297:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14298:       /* } */
1.238     brouard  14299:       fprintf(ficrespl,"******\n");
                   14300:       printf("******\n");
                   14301:       fprintf(ficlog,"******\n");
                   14302:       if(invalidvarcomb[k]){
                   14303:        printf("\nCombination (%d) ignored because no case \n",k); 
                   14304:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   14305:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   14306:        continue;
                   14307:       }
1.219     brouard  14308: 
1.238     brouard  14309:       fprintf(ficrespl,"#Age ");
1.337     brouard  14310:       /* for(j=1;j<=cptcoveff;j++) { */
                   14311:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14312:       /* } */
                   14313:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
                   14314:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14315:       }
                   14316:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   14317:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  14318:     
1.238     brouard  14319:       for (age=agebase; age<=agelim; age++){
                   14320:        /* for (age=agebase; age<=agebase; age++){ */
1.337     brouard  14321:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
                   14322:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
1.238     brouard  14323:        fprintf(ficrespl,"%.0f ",age );
1.337     brouard  14324:        /* for(j=1;j<=cptcoveff;j++) */
                   14325:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14326:        for(j=1;j<=cptcovs;j++)
                   14327:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14328:        tot=0.;
                   14329:        for(i=1; i<=nlstate;i++){
                   14330:          tot +=  prlim[i][i];
                   14331:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   14332:        }
                   14333:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   14334:       } /* Age */
                   14335:       /* was end of cptcod */
1.337     brouard  14336:     } /* nres */
                   14337:   /* } /\* for each combination *\/ */
1.219     brouard  14338:   return 0;
1.180     brouard  14339: }
                   14340: 
1.218     brouard  14341: 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  14342:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  14343:        
                   14344:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   14345:    * at any age between ageminpar and agemaxpar
                   14346:         */
1.235     brouard  14347:   int i, j, k, i1, nres=0 ;
1.217     brouard  14348:   /* double ftolpl = 1.e-10; */
                   14349:   double age, agebase, agelim;
                   14350:   double tot;
1.218     brouard  14351:   /* double ***mobaverage; */
                   14352:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  14353: 
                   14354:   strcpy(fileresplb,"PLB_");
                   14355:   strcat(fileresplb,fileresu);
                   14356:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  14357:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   14358:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  14359:   }
1.288     brouard  14360:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   14361:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  14362:   pstamp(ficresplb);
1.288     brouard  14363:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  14364:   fprintf(ficresplb,"#Age ");
                   14365:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   14366:   fprintf(ficresplb,"\n");
                   14367:   
1.218     brouard  14368:   
                   14369:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   14370:   
                   14371:   agebase=ageminpar;
                   14372:   agelim=agemaxpar;
                   14373:   
                   14374:   
1.227     brouard  14375:   i1=pow(2,cptcoveff);
1.218     brouard  14376:   if (cptcovn < 1){i1=1;}
1.227     brouard  14377:   
1.238     brouard  14378:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.338     brouard  14379:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   14380:       k=TKresult[nres];
                   14381:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   14382:      /* if(i1 != 1 && TKresult[nres]!= k) */
                   14383:      /*        continue; */
                   14384:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
1.238     brouard  14385:       fprintf(ficresplb,"#******");
                   14386:       printf("#******");
                   14387:       fprintf(ficlog,"#******");
1.338     brouard  14388:       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) */
                   14389:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14390:        fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14391:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14392:       }
1.338     brouard  14393:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
                   14394:       /*       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14395:       /*       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14396:       /*       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14397:       /* } */
                   14398:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   14399:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14400:       /*       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14401:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14402:       /* } */
1.238     brouard  14403:       fprintf(ficresplb,"******\n");
                   14404:       printf("******\n");
                   14405:       fprintf(ficlog,"******\n");
                   14406:       if(invalidvarcomb[k]){
                   14407:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   14408:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   14409:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   14410:        continue;
                   14411:       }
1.218     brouard  14412:     
1.238     brouard  14413:       fprintf(ficresplb,"#Age ");
1.338     brouard  14414:       for(j=1;j<=cptcovs;j++) {
                   14415:        fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14416:       }
                   14417:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   14418:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  14419:     
                   14420:     
1.238     brouard  14421:       for (age=agebase; age<=agelim; age++){
                   14422:        /* for (age=agebase; age<=agebase; age++){ */
                   14423:        if(mobilavproj > 0){
                   14424:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   14425:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  14426:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  14427:        }else if (mobilavproj == 0){
                   14428:          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);
                   14429:          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);
                   14430:          exit(1);
                   14431:        }else{
                   14432:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  14433:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  14434:          /* printf("TOTOT\n"); */
                   14435:           /* exit(1); */
1.238     brouard  14436:        }
                   14437:        fprintf(ficresplb,"%.0f ",age );
1.338     brouard  14438:        for(j=1;j<=cptcovs;j++)
                   14439:          fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14440:        tot=0.;
                   14441:        for(i=1; i<=nlstate;i++){
                   14442:          tot +=  bprlim[i][i];
                   14443:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   14444:        }
                   14445:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   14446:       } /* Age */
                   14447:       /* was end of cptcod */
1.255     brouard  14448:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.338     brouard  14449:     /* } /\* end of any combination *\/ */
1.238     brouard  14450:   } /* end of nres */  
1.218     brouard  14451:   /* hBijx(p, bage, fage); */
                   14452:   /* fclose(ficrespijb); */
                   14453:   
                   14454:   return 0;
1.217     brouard  14455: }
1.218     brouard  14456:  
1.180     brouard  14457: int hPijx(double *p, int bage, int fage){
                   14458:     /*------------- h Pij x at various ages ------------*/
1.336     brouard  14459:   /* to be optimized with precov */
1.180     brouard  14460:   int stepsize;
                   14461:   int agelim;
                   14462:   int hstepm;
                   14463:   int nhstepm;
1.359     brouard  14464:   int h, i, i1, j, k, nres=0;
1.180     brouard  14465: 
                   14466:   double agedeb;
                   14467:   double ***p3mat;
                   14468: 
1.337     brouard  14469:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   14470:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   14471:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   14472:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   14473:   }
                   14474:   printf("Computing pij: result on file '%s' \n", filerespij);
                   14475:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   14476:   
                   14477:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   14478:   /*if (stepm<=24) stepsize=2;*/
                   14479:   
                   14480:   agelim=AGESUP;
                   14481:   hstepm=stepsize*YEARM; /* Every year of age */
                   14482:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   14483:   
                   14484:   /* hstepm=1;   aff par mois*/
                   14485:   pstamp(ficrespij);
                   14486:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   14487:   i1= pow(2,cptcoveff);
                   14488:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   14489:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   14490:   /*   k=k+1;  */
                   14491:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   14492:     k=TKresult[nres];
1.338     brouard  14493:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  14494:     /* for(k=1; k<=i1;k++){ */
                   14495:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   14496:     /*         continue; */
                   14497:     fprintf(ficrespij,"\n#****** ");
                   14498:     for(j=1;j<=cptcovs;j++){
                   14499:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14500:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14501:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   14502:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14503:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14504:     }
                   14505:     fprintf(ficrespij,"******\n");
                   14506:     
                   14507:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   14508:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   14509:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   14510:       
                   14511:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   14512:       
                   14513:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   14514:       oldm=oldms;savm=savms;
                   14515:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
                   14516:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   14517:       for(i=1; i<=nlstate;i++)
                   14518:        for(j=1; j<=nlstate+ndeath;j++)
                   14519:          fprintf(ficrespij," %1d-%1d",i,j);
                   14520:       fprintf(ficrespij,"\n");
                   14521:       for (h=0; h<=nhstepm; h++){
                   14522:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   14523:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.183     brouard  14524:        for(i=1; i<=nlstate;i++)
                   14525:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  14526:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.183     brouard  14527:        fprintf(ficrespij,"\n");
                   14528:       }
1.337     brouard  14529:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   14530:       fprintf(ficrespij,"\n");
1.180     brouard  14531:     }
1.337     brouard  14532:   }
                   14533:   /*}*/
                   14534:   return 0;
1.180     brouard  14535: }
1.218     brouard  14536:  
                   14537:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  14538:     /*------------- h Bij x at various ages ------------*/
1.336     brouard  14539:     /* To be optimized with precov */
1.217     brouard  14540:   int stepsize;
1.218     brouard  14541:   /* int agelim; */
                   14542:        int ageminl;
1.217     brouard  14543:   int hstepm;
                   14544:   int nhstepm;
1.238     brouard  14545:   int h, i, i1, j, k, nres;
1.218     brouard  14546:        
1.217     brouard  14547:   double agedeb;
                   14548:   double ***p3mat;
1.218     brouard  14549:        
                   14550:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   14551:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   14552:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   14553:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   14554:   }
                   14555:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   14556:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   14557:   
                   14558:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   14559:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  14560:   
1.218     brouard  14561:   /* agelim=AGESUP; */
1.289     brouard  14562:   ageminl=AGEINF; /* was 30 */
1.218     brouard  14563:   hstepm=stepsize*YEARM; /* Every year of age */
                   14564:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   14565:   
                   14566:   /* hstepm=1;   aff par mois*/
                   14567:   pstamp(ficrespijb);
1.255     brouard  14568:   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  14569:   i1= pow(2,cptcoveff);
1.218     brouard  14570:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   14571:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   14572:   /*   k=k+1;  */
1.238     brouard  14573:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  14574:     k=TKresult[nres];
1.338     brouard  14575:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  14576:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   14577:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   14578:     /*         continue; */
                   14579:     fprintf(ficrespijb,"\n#****** ");
                   14580:     for(j=1;j<=cptcovs;j++){
1.338     brouard  14581:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.337     brouard  14582:       /* for(j=1;j<=cptcoveff;j++) */
                   14583:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14584:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   14585:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14586:     }
                   14587:     fprintf(ficrespijb,"******\n");
                   14588:     if(invalidvarcomb[k]){  /* Is it necessary here? */
                   14589:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   14590:       continue;
                   14591:     }
                   14592:     
                   14593:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   14594:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   14595:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   14596:       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 */
                   14597:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
                   14598:       
                   14599:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   14600:       
                   14601:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   14602:       /* and memory limitations if stepm is small */
                   14603:       
                   14604:       /* oldm=oldms;savm=savms; */
                   14605:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   14606:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
                   14607:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   14608:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
                   14609:       for(i=1; i<=nlstate;i++)
                   14610:        for(j=1; j<=nlstate+ndeath;j++)
                   14611:          fprintf(ficrespijb," %1d-%1d",i,j);
                   14612:       fprintf(ficrespijb,"\n");
                   14613:       for (h=0; h<=nhstepm; h++){
                   14614:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   14615:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   14616:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  14617:        for(i=1; i<=nlstate;i++)
                   14618:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  14619:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.217     brouard  14620:        fprintf(ficrespijb,"\n");
1.337     brouard  14621:       }
                   14622:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   14623:       fprintf(ficrespijb,"\n");
                   14624:     } /* end age deb */
                   14625:     /* } /\* end combination *\/ */
1.238     brouard  14626:   } /* end nres */
1.218     brouard  14627:   return 0;
                   14628:  } /*  hBijx */
1.217     brouard  14629: 
1.180     brouard  14630: 
1.136     brouard  14631: /***********************************************/
                   14632: /**************** Main Program *****************/
                   14633: /***********************************************/
                   14634: 
                   14635: int main(int argc, char *argv[])
                   14636: {
                   14637: #ifdef GSL
                   14638:   const gsl_multimin_fminimizer_type *T;
                   14639:   size_t iteri = 0, it;
                   14640:   int rval = GSL_CONTINUE;
                   14641:   int status = GSL_SUCCESS;
                   14642:   double ssval;
                   14643: #endif
                   14644:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  14645:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   14646:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  14647:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  14648:   int jj, ll, li, lj, lk;
1.136     brouard  14649:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  14650:   int num_filled;
1.136     brouard  14651:   int itimes;
                   14652:   int NDIM=2;
                   14653:   int vpopbased=0;
1.235     brouard  14654:   int nres=0;
1.258     brouard  14655:   int endishere=0;
1.277     brouard  14656:   int noffset=0;
1.274     brouard  14657:   int ncurrv=0; /* Temporary variable */
                   14658:   
1.164     brouard  14659:   char ca[32], cb[32];
1.136     brouard  14660:   /*  FILE *fichtm; *//* Html File */
                   14661:   /* FILE *ficgp;*/ /*Gnuplot File */
                   14662:   struct stat info;
1.191     brouard  14663:   double agedeb=0.;
1.194     brouard  14664: 
                   14665:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  14666:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  14667: 
1.361     brouard  14668:   double stdpercent; /* for computing the std error of percent e.i: e.i/e.. */
1.165     brouard  14669:   double fret;
1.191     brouard  14670:   double dum=0.; /* Dummy variable */
1.359     brouard  14671:   /* double*** p3mat;*/
1.218     brouard  14672:   /* double ***mobaverage; */
1.319     brouard  14673:   double wald;
1.164     brouard  14674: 
1.351     brouard  14675:   char line[MAXLINE], linetmp[MAXLINE];
1.197     brouard  14676:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   14677: 
1.234     brouard  14678:   char  modeltemp[MAXLINE];
1.332     brouard  14679:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  14680:   
1.136     brouard  14681:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  14682:   char *tok, *val; /* pathtot */
1.334     brouard  14683:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.359     brouard  14684:   int c, h; /* c2; */
1.191     brouard  14685:   int jl=0;
                   14686:   int i1, j1, jk, stepsize=0;
1.194     brouard  14687:   int count=0;
                   14688: 
1.164     brouard  14689:   int *tab; 
1.136     brouard  14690:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  14691:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   14692:   /* double anprojf, mprojf, jprojf; */
                   14693:   /* double jintmean,mintmean,aintmean;   */
                   14694:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   14695:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   14696:   double yrfproj= 10.0; /* Number of years of forward projections */
                   14697:   double yrbproj= 10.0; /* Number of years of backward projections */
                   14698:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  14699:   int mobilav=0,popforecast=0;
1.191     brouard  14700:   int hstepm=0, nhstepm=0;
1.136     brouard  14701:   int agemortsup;
                   14702:   float  sumlpop=0.;
                   14703:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   14704:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   14705: 
1.191     brouard  14706:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  14707:   double ftolpl=FTOL;
                   14708:   double **prlim;
1.217     brouard  14709:   double **bprlim;
1.317     brouard  14710:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   14711:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  14712:   double ***paramstart; /* Matrix of starting parameter values */
                   14713:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  14714:   double **matcov; /* Matrix of covariance */
1.203     brouard  14715:   double **hess; /* Hessian matrix */
1.136     brouard  14716:   double ***delti3; /* Scale */
                   14717:   double *delti; /* Scale */
                   14718:   double ***eij, ***vareij;
1.359     brouard  14719:   //double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  14720: 
1.136     brouard  14721:   double *epj, vepp;
1.164     brouard  14722: 
1.273     brouard  14723:   double dateprev1, dateprev2;
1.296     brouard  14724:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   14725:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   14726: 
1.217     brouard  14727: 
1.136     brouard  14728:   double **ximort;
1.145     brouard  14729:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  14730:   int *dcwave;
                   14731: 
1.164     brouard  14732:   char z[1]="c";
1.136     brouard  14733: 
                   14734:   /*char  *strt;*/
                   14735:   char strtend[80];
1.126     brouard  14736: 
1.164     brouard  14737: 
1.126     brouard  14738: /*   setlocale (LC_ALL, ""); */
                   14739: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   14740: /*   textdomain (PACKAGE); */
                   14741: /*   setlocale (LC_CTYPE, ""); */
                   14742: /*   setlocale (LC_MESSAGES, ""); */
                   14743: 
                   14744:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  14745:   rstart_time = time(NULL);  
                   14746:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   14747:   start_time = *localtime(&rstart_time);
1.126     brouard  14748:   curr_time=start_time;
1.157     brouard  14749:   /*tml = *localtime(&start_time.tm_sec);*/
                   14750:   /* strcpy(strstart,asctime(&tml)); */
                   14751:   strcpy(strstart,asctime(&start_time));
1.126     brouard  14752: 
                   14753: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  14754: /*  tp.tm_sec = tp.tm_sec +86400; */
                   14755: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  14756: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   14757: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   14758: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  14759: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  14760: /*   strt=asctime(&tmg); */
                   14761: /*   printf("Time(after) =%s",strstart);  */
                   14762: /*  (void) time (&time_value);
                   14763: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   14764: *  tm = *localtime(&time_value);
                   14765: *  strstart=asctime(&tm);
                   14766: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   14767: */
                   14768: 
                   14769:   nberr=0; /* Number of errors and warnings */
                   14770:   nbwarn=0;
1.184     brouard  14771: #ifdef WIN32
                   14772:   _getcwd(pathcd, size);
                   14773: #else
1.126     brouard  14774:   getcwd(pathcd, size);
1.184     brouard  14775: #endif
1.191     brouard  14776:   syscompilerinfo(0);
1.359     brouard  14777:   printf("\nIMaCh prax version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  14778:   if(argc <=1){
                   14779:     printf("\nEnter the parameter file name: ");
1.205     brouard  14780:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   14781:       printf("ERROR Empty parameter file name\n");
                   14782:       goto end;
                   14783:     }
1.126     brouard  14784:     i=strlen(pathr);
                   14785:     if(pathr[i-1]=='\n')
                   14786:       pathr[i-1]='\0';
1.156     brouard  14787:     i=strlen(pathr);
1.205     brouard  14788:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  14789:       pathr[i-1]='\0';
1.205     brouard  14790:     }
                   14791:     i=strlen(pathr);
                   14792:     if( i==0 ){
                   14793:       printf("ERROR Empty parameter file name\n");
                   14794:       goto end;
                   14795:     }
                   14796:     for (tok = pathr; tok != NULL; ){
1.126     brouard  14797:       printf("Pathr |%s|\n",pathr);
                   14798:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   14799:       printf("val= |%s| pathr=%s\n",val,pathr);
                   14800:       strcpy (pathtot, val);
                   14801:       if(pathr[0] == '\0') break; /* Dirty */
                   14802:     }
                   14803:   }
1.281     brouard  14804:   else if (argc<=2){
                   14805:     strcpy(pathtot,argv[1]);
                   14806:   }
1.126     brouard  14807:   else{
                   14808:     strcpy(pathtot,argv[1]);
1.281     brouard  14809:     strcpy(z,argv[2]);
                   14810:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  14811:   }
                   14812:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   14813:   /*cygwin_split_path(pathtot,path,optionfile);
                   14814:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   14815:   /* cutv(path,optionfile,pathtot,'\\');*/
                   14816: 
                   14817:   /* Split argv[0], imach program to get pathimach */
                   14818:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   14819:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   14820:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   14821:  /*   strcpy(pathimach,argv[0]); */
                   14822:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   14823:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   14824:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  14825: #ifdef WIN32
                   14826:   _chdir(path); /* Can be a relative path */
                   14827:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   14828: #else
1.126     brouard  14829:   chdir(path); /* Can be a relative path */
1.184     brouard  14830:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   14831: #endif
                   14832:   printf("Current directory %s!\n",pathcd);
1.126     brouard  14833:   strcpy(command,"mkdir ");
                   14834:   strcat(command,optionfilefiname);
                   14835:   if((outcmd=system(command)) != 0){
1.169     brouard  14836:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  14837:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   14838:     /* fclose(ficlog); */
                   14839: /*     exit(1); */
                   14840:   }
                   14841: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   14842: /*     perror("mkdir"); */
                   14843: /*   } */
                   14844: 
                   14845:   /*-------- arguments in the command line --------*/
                   14846: 
1.186     brouard  14847:   /* Main Log file */
1.126     brouard  14848:   strcat(filelog, optionfilefiname);
                   14849:   strcat(filelog,".log");    /* */
                   14850:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   14851:     printf("Problem with logfile %s\n",filelog);
                   14852:     goto end;
                   14853:   }
                   14854:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  14855:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  14856:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   14857:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   14858:  path=%s \n\
                   14859:  optionfile=%s\n\
                   14860:  optionfilext=%s\n\
1.156     brouard  14861:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  14862: 
1.197     brouard  14863:   syscompilerinfo(1);
1.167     brouard  14864: 
1.126     brouard  14865:   printf("Local time (at start):%s",strstart);
                   14866:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   14867:   fflush(ficlog);
                   14868: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  14869: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  14870: 
                   14871:   /* */
                   14872:   strcpy(fileres,"r");
                   14873:   strcat(fileres, optionfilefiname);
1.201     brouard  14874:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  14875:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  14876:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  14877: 
1.186     brouard  14878:   /* Main ---------arguments file --------*/
1.126     brouard  14879: 
                   14880:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  14881:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   14882:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  14883:     fflush(ficlog);
1.149     brouard  14884:     /* goto end; */
                   14885:     exit(70); 
1.126     brouard  14886:   }
                   14887: 
                   14888:   strcpy(filereso,"o");
1.201     brouard  14889:   strcat(filereso,fileresu);
1.126     brouard  14890:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   14891:     printf("Problem with Output resultfile: %s\n", filereso);
                   14892:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   14893:     fflush(ficlog);
                   14894:     goto end;
                   14895:   }
1.278     brouard  14896:       /*-------- Rewriting parameter file ----------*/
                   14897:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   14898:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   14899:   strcat(rfileres,".");    /* */
                   14900:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   14901:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   14902:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   14903:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   14904:     fflush(ficlog);
                   14905:     goto end;
                   14906:   }
                   14907:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  14908: 
1.278     brouard  14909:                                      
1.126     brouard  14910:   /* Reads comments: lines beginning with '#' */
                   14911:   numlinepar=0;
1.277     brouard  14912:   /* Is it a BOM UTF-8 Windows file? */
                   14913:   /* First parameter line */
1.197     brouard  14914:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  14915:     noffset=0;
                   14916:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   14917:     {
                   14918:       noffset=noffset+3;
                   14919:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   14920:     }
1.302     brouard  14921: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   14922:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  14923:     {
                   14924:       noffset=noffset+2;
                   14925:       printf("# File is an UTF16BE BOM file\n");
                   14926:     }
                   14927:     else if( line[0] == 0 && line[1] == 0)
                   14928:     {
                   14929:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   14930:        noffset=noffset+4;
                   14931:        printf("# File is an UTF16BE BOM file\n");
                   14932:       }
                   14933:     } else{
                   14934:       ;/*printf(" Not a BOM file\n");*/
                   14935:     }
                   14936:   
1.197     brouard  14937:     /* If line starts with a # it is a comment */
1.277     brouard  14938:     if (line[noffset] == '#') {
1.197     brouard  14939:       numlinepar++;
                   14940:       fputs(line,stdout);
                   14941:       fputs(line,ficparo);
1.278     brouard  14942:       fputs(line,ficres);
1.197     brouard  14943:       fputs(line,ficlog);
                   14944:       continue;
                   14945:     }else
                   14946:       break;
                   14947:   }
                   14948:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   14949:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   14950:     if (num_filled != 5) {
                   14951:       printf("Should be 5 parameters\n");
1.283     brouard  14952:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  14953:     }
1.126     brouard  14954:     numlinepar++;
1.197     brouard  14955:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  14956:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   14957:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   14958:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  14959:   }
                   14960:   /* Second parameter line */
                   14961:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  14962:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   14963:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  14964:     if (line[0] == '#') {
                   14965:       numlinepar++;
1.283     brouard  14966:       printf("%s",line);
                   14967:       fprintf(ficres,"%s",line);
                   14968:       fprintf(ficparo,"%s",line);
                   14969:       fprintf(ficlog,"%s",line);
1.197     brouard  14970:       continue;
                   14971:     }else
                   14972:       break;
                   14973:   }
1.223     brouard  14974:   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", \
                   14975:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   14976:     if (num_filled != 11) {
                   14977:       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  14978:       printf("but line=%s\n",line);
1.283     brouard  14979:       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");
                   14980:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  14981:     }
1.286     brouard  14982:     if( lastpass > maxwav){
                   14983:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   14984:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   14985:       fflush(ficlog);
                   14986:       goto end;
                   14987:     }
                   14988:       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  14989:     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  14990:     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  14991:     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  14992:   }
1.203     brouard  14993:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  14994:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  14995:   /* Third parameter line */
                   14996:   while(fgets(line, MAXLINE, ficpar)) {
                   14997:     /* If line starts with a # it is a comment */
                   14998:     if (line[0] == '#') {
                   14999:       numlinepar++;
1.283     brouard  15000:       printf("%s",line);
                   15001:       fprintf(ficres,"%s",line);
                   15002:       fprintf(ficparo,"%s",line);
                   15003:       fprintf(ficlog,"%s",line);
1.197     brouard  15004:       continue;
                   15005:     }else
                   15006:       break;
                   15007:   }
1.351     brouard  15008:   if((num_filled=sscanf(line,"model=%[^.\n]", model)) !=EOF){ /* Every character after model but dot and  return */
                   15009:     if (num_filled != 1){
                   15010:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   15011:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   15012:       model[0]='\0';
                   15013:       goto end;
                   15014:     }else{
                   15015:       trimbtab(linetmp,line); /* Trims multiple blanks in line */
                   15016:       strcpy(line, linetmp);
                   15017:     }
                   15018:   }
                   15019:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){ /* Every character after 1+age but dot and  return */
1.279     brouard  15020:     if (num_filled != 1){
1.302     brouard  15021:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   15022:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  15023:       model[0]='\0';
                   15024:       goto end;
                   15025:     }
                   15026:     else{
                   15027:       if (model[0]=='+'){
                   15028:        for(i=1; i<=strlen(model);i++)
                   15029:          modeltemp[i-1]=model[i];
1.201     brouard  15030:        strcpy(model,modeltemp); 
1.197     brouard  15031:       }
                   15032:     }
1.338     brouard  15033:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  15034:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  15035:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   15036:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   15037:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  15038:   }
                   15039:   /* 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); */
                   15040:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   15041:   /* 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  15042:   /* 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); */
                   15043:   /* 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  15044:   fflush(ficlog);
1.190     brouard  15045:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   15046:   if(model[0]=='#'){
1.279     brouard  15047:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   15048:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   15049:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  15050:     if(mle != -1){
1.279     brouard  15051:       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  15052:       exit(1);
                   15053:     }
                   15054:   }
1.126     brouard  15055:   while((c=getc(ficpar))=='#' && c!= EOF){
                   15056:     ungetc(c,ficpar);
                   15057:     fgets(line, MAXLINE, ficpar);
                   15058:     numlinepar++;
1.195     brouard  15059:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   15060:       z[0]=line[1];
1.342     brouard  15061:     }else if(line[1]=='d'){ /* For debugging individual values of covariates in ficresilk */
1.343     brouard  15062:       debugILK=1;printf("DebugILK\n");
1.195     brouard  15063:     }
                   15064:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  15065:     fputs(line, stdout);
                   15066:     //puts(line);
1.126     brouard  15067:     fputs(line,ficparo);
                   15068:     fputs(line,ficlog);
                   15069:   }
                   15070:   ungetc(c,ficpar);
                   15071: 
                   15072:    
1.290     brouard  15073:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   15074:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   15075:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
1.341     brouard  15076:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /\**< Time varying covariate (dummy and quantitative)*\/ */
                   15077:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /**< Might be better */
1.136     brouard  15078:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   15079:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   15080:      v1+v2*age+v2*v3 makes cptcovn = 3
                   15081:   */
                   15082:   if (strlen(model)>1) 
1.187     brouard  15083:     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  15084:   else
1.187     brouard  15085:     ncovmodel=2; /* Constant and age */
1.133     brouard  15086:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   15087:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  15088:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   15089:     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);
                   15090:     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);
                   15091:     fflush(stdout);
                   15092:     fclose (ficlog);
                   15093:     goto end;
                   15094:   }
1.126     brouard  15095:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   15096:   delti=delti3[1][1];
                   15097:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   15098:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  15099: /* We could also provide initial parameters values giving by simple logistic regression 
                   15100:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   15101:       /* for(i=1;i<nlstate;i++){ */
                   15102:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   15103:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   15104:       /* } */
1.126     brouard  15105:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  15106:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   15107:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  15108:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   15109:     fclose (ficparo);
                   15110:     fclose (ficlog);
                   15111:     goto end;
                   15112:     exit(0);
1.220     brouard  15113:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  15114:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  15115:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   15116:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  15117:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   15118:     matcov=matrix(1,npar,1,npar);
1.203     brouard  15119:     hess=matrix(1,npar,1,npar);
1.220     brouard  15120:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  15121:     /* Read guessed parameters */
1.126     brouard  15122:     /* Reads comments: lines beginning with '#' */
                   15123:     while((c=getc(ficpar))=='#' && c!= EOF){
                   15124:       ungetc(c,ficpar);
                   15125:       fgets(line, MAXLINE, ficpar);
                   15126:       numlinepar++;
1.141     brouard  15127:       fputs(line,stdout);
1.126     brouard  15128:       fputs(line,ficparo);
                   15129:       fputs(line,ficlog);
                   15130:     }
                   15131:     ungetc(c,ficpar);
                   15132:     
                   15133:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  15134:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  15135:     for(i=1; i <=nlstate; i++){
1.234     brouard  15136:       j=0;
1.126     brouard  15137:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  15138:        if(jj==i) continue;
                   15139:        j++;
1.292     brouard  15140:        while((c=getc(ficpar))=='#' && c!= EOF){
                   15141:          ungetc(c,ficpar);
                   15142:          fgets(line, MAXLINE, ficpar);
                   15143:          numlinepar++;
                   15144:          fputs(line,stdout);
                   15145:          fputs(line,ficparo);
                   15146:          fputs(line,ficlog);
                   15147:        }
                   15148:        ungetc(c,ficpar);
1.234     brouard  15149:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   15150:        if ((i1 != i) || (j1 != jj)){
                   15151:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  15152: It might be a problem of design; if ncovcol and the model are correct\n \
                   15153: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  15154:          exit(1);
                   15155:        }
                   15156:        fprintf(ficparo,"%1d%1d",i1,j1);
                   15157:        if(mle==1)
                   15158:          printf("%1d%1d",i,jj);
                   15159:        fprintf(ficlog,"%1d%1d",i,jj);
                   15160:        for(k=1; k<=ncovmodel;k++){
                   15161:          fscanf(ficpar," %lf",&param[i][j][k]);
                   15162:          if(mle==1){
                   15163:            printf(" %lf",param[i][j][k]);
                   15164:            fprintf(ficlog," %lf",param[i][j][k]);
                   15165:          }
                   15166:          else
                   15167:            fprintf(ficlog," %lf",param[i][j][k]);
                   15168:          fprintf(ficparo," %lf",param[i][j][k]);
                   15169:        }
                   15170:        fscanf(ficpar,"\n");
                   15171:        numlinepar++;
                   15172:        if(mle==1)
                   15173:          printf("\n");
                   15174:        fprintf(ficlog,"\n");
                   15175:        fprintf(ficparo,"\n");
1.126     brouard  15176:       }
                   15177:     }  
                   15178:     fflush(ficlog);
1.234     brouard  15179:     
1.251     brouard  15180:     /* Reads parameters values */
1.126     brouard  15181:     p=param[1][1];
1.251     brouard  15182:     pstart=paramstart[1][1];
1.126     brouard  15183:     
                   15184:     /* Reads comments: lines beginning with '#' */
                   15185:     while((c=getc(ficpar))=='#' && c!= EOF){
                   15186:       ungetc(c,ficpar);
                   15187:       fgets(line, MAXLINE, ficpar);
                   15188:       numlinepar++;
1.141     brouard  15189:       fputs(line,stdout);
1.126     brouard  15190:       fputs(line,ficparo);
                   15191:       fputs(line,ficlog);
                   15192:     }
                   15193:     ungetc(c,ficpar);
                   15194: 
                   15195:     for(i=1; i <=nlstate; i++){
                   15196:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  15197:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   15198:        if ( (i1-i) * (j1-j) != 0){
                   15199:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   15200:          exit(1);
                   15201:        }
                   15202:        printf("%1d%1d",i,j);
                   15203:        fprintf(ficparo,"%1d%1d",i1,j1);
                   15204:        fprintf(ficlog,"%1d%1d",i1,j1);
                   15205:        for(k=1; k<=ncovmodel;k++){
                   15206:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   15207:          printf(" %le",delti3[i][j][k]);
                   15208:          fprintf(ficparo," %le",delti3[i][j][k]);
                   15209:          fprintf(ficlog," %le",delti3[i][j][k]);
                   15210:        }
                   15211:        fscanf(ficpar,"\n");
                   15212:        numlinepar++;
                   15213:        printf("\n");
                   15214:        fprintf(ficparo,"\n");
                   15215:        fprintf(ficlog,"\n");
1.126     brouard  15216:       }
                   15217:     }
                   15218:     fflush(ficlog);
1.234     brouard  15219:     
1.145     brouard  15220:     /* Reads covariance matrix */
1.126     brouard  15221:     delti=delti3[1][1];
1.220     brouard  15222:                
                   15223:                
1.126     brouard  15224:     /* 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  15225:                
1.126     brouard  15226:     /* Reads comments: lines beginning with '#' */
                   15227:     while((c=getc(ficpar))=='#' && c!= EOF){
                   15228:       ungetc(c,ficpar);
                   15229:       fgets(line, MAXLINE, ficpar);
                   15230:       numlinepar++;
1.141     brouard  15231:       fputs(line,stdout);
1.126     brouard  15232:       fputs(line,ficparo);
                   15233:       fputs(line,ficlog);
                   15234:     }
                   15235:     ungetc(c,ficpar);
1.220     brouard  15236:                
1.126     brouard  15237:     matcov=matrix(1,npar,1,npar);
1.203     brouard  15238:     hess=matrix(1,npar,1,npar);
1.131     brouard  15239:     for(i=1; i <=npar; i++)
                   15240:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  15241:                
1.194     brouard  15242:     /* Scans npar lines */
1.126     brouard  15243:     for(i=1; i <=npar; i++){
1.226     brouard  15244:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  15245:       if(count != 3){
1.226     brouard  15246:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  15247: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   15248: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  15249:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  15250: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   15251: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  15252:        exit(1);
1.220     brouard  15253:       }else{
1.226     brouard  15254:        if(mle==1)
                   15255:          printf("%1d%1d%d",i1,j1,jk);
                   15256:       }
                   15257:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   15258:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  15259:       for(j=1; j <=i; j++){
1.226     brouard  15260:        fscanf(ficpar," %le",&matcov[i][j]);
                   15261:        if(mle==1){
                   15262:          printf(" %.5le",matcov[i][j]);
                   15263:        }
                   15264:        fprintf(ficlog," %.5le",matcov[i][j]);
                   15265:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  15266:       }
                   15267:       fscanf(ficpar,"\n");
                   15268:       numlinepar++;
                   15269:       if(mle==1)
1.220     brouard  15270:                                printf("\n");
1.126     brouard  15271:       fprintf(ficlog,"\n");
                   15272:       fprintf(ficparo,"\n");
                   15273:     }
1.194     brouard  15274:     /* End of read covariance matrix npar lines */
1.126     brouard  15275:     for(i=1; i <=npar; i++)
                   15276:       for(j=i+1;j<=npar;j++)
1.226     brouard  15277:        matcov[i][j]=matcov[j][i];
1.126     brouard  15278:     
                   15279:     if(mle==1)
                   15280:       printf("\n");
                   15281:     fprintf(ficlog,"\n");
                   15282:     
                   15283:     fflush(ficlog);
                   15284:     
                   15285:   }    /* End of mle != -3 */
1.218     brouard  15286:   
1.186     brouard  15287:   /*  Main data
                   15288:    */
1.290     brouard  15289:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   15290:   /* num=lvector(1,n); */
                   15291:   /* moisnais=vector(1,n); */
                   15292:   /* annais=vector(1,n); */
                   15293:   /* moisdc=vector(1,n); */
                   15294:   /* andc=vector(1,n); */
                   15295:   /* weight=vector(1,n); */
                   15296:   /* agedc=vector(1,n); */
                   15297:   /* cod=ivector(1,n); */
                   15298:   /* for(i=1;i<=n;i++){ */
                   15299:   num=lvector(firstobs,lastobs);
                   15300:   moisnais=vector(firstobs,lastobs);
                   15301:   annais=vector(firstobs,lastobs);
                   15302:   moisdc=vector(firstobs,lastobs);
                   15303:   andc=vector(firstobs,lastobs);
                   15304:   weight=vector(firstobs,lastobs);
                   15305:   agedc=vector(firstobs,lastobs);
                   15306:   cod=ivector(firstobs,lastobs);
                   15307:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  15308:     num[i]=0;
                   15309:     moisnais[i]=0;
                   15310:     annais[i]=0;
                   15311:     moisdc[i]=0;
                   15312:     andc[i]=0;
                   15313:     agedc[i]=0;
                   15314:     cod[i]=0;
                   15315:     weight[i]=1.0; /* Equal weights, 1 by default */
                   15316:   }
1.290     brouard  15317:   mint=matrix(1,maxwav,firstobs,lastobs);
                   15318:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  15319:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
1.336     brouard  15320:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
1.126     brouard  15321:   tab=ivector(1,NCOVMAX);
1.144     brouard  15322:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  15323:   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  15324: 
1.136     brouard  15325:   /* Reads data from file datafile */
                   15326:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   15327:     goto end;
                   15328: 
                   15329:   /* Calculation of the number of parameters from char model */
1.234     brouard  15330:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  15331:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   15332:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   15333:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   15334:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  15335:   */
                   15336:   
                   15337:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   15338:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  15339:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335     brouard  15340:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  15341:   TvarsD=ivector(1,NCOVMAX); /*  */
                   15342:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   15343:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  15344:   TvarF=ivector(1,NCOVMAX); /*  */
                   15345:   TvarFind=ivector(1,NCOVMAX); /*  */
                   15346:   TvarV=ivector(1,NCOVMAX); /*  */
                   15347:   TvarVind=ivector(1,NCOVMAX); /*  */
                   15348:   TvarA=ivector(1,NCOVMAX); /*  */
                   15349:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  15350:   TvarFD=ivector(1,NCOVMAX); /*  */
                   15351:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   15352:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   15353:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   15354:   TvarVD=ivector(1,NCOVMAX); /*  */
                   15355:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   15356:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   15357:   TvarVQind=ivector(1,NCOVMAX); /*  */
1.339     brouard  15358:   TvarVV=ivector(1,NCOVMAX); /*  */
                   15359:   TvarVVind=ivector(1,NCOVMAX); /*  */
1.349     brouard  15360:   TvarVVA=ivector(1,NCOVMAX); /*  */
                   15361:   TvarVVAind=ivector(1,NCOVMAX); /*  */
                   15362:   TvarAVVA=ivector(1,NCOVMAX); /*  */
                   15363:   TvarAVVAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  15364: 
1.230     brouard  15365:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  15366:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  15367:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   15368:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   15369:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.349     brouard  15370:   DummyV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   15371:   FixedV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   15372: 
1.137     brouard  15373:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   15374:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   15375:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   15376:   */
                   15377:   /* For model-covariate k tells which data-covariate to use but
                   15378:     because this model-covariate is a construction we invent a new column
                   15379:     ncovcol + k1
                   15380:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   15381:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  15382:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   15383:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  15384:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   15385:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  15386:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  15387:   */
1.145     brouard  15388:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   15389:   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  15390:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   15391:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.351     brouard  15392:   Tvardk=imatrix(0,NCOVMAX,1,2);
1.145     brouard  15393:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  15394:                         4 covariates (3 plus signs)
                   15395:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  15396:                           */  
                   15397:   for(i=1;i<NCOVMAX;i++)
                   15398:     Tage[i]=0;
1.230     brouard  15399:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  15400:                                * individual dummy, fixed or varying:
                   15401:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   15402:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  15403:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   15404:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   15405:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   15406:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   15407:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  15408:                                * individual quantitative, fixed or varying:
                   15409:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   15410:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   15411:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.349     brouard  15412: 
                   15413: /* Probably useless zeroes */
                   15414:   for(i=1;i<NCOVMAX;i++){
                   15415:     DummyV[i]=0;
                   15416:     FixedV[i]=0;
                   15417:   }
                   15418: 
                   15419:   for(i=1; i <=ncovcol;i++){
                   15420:     DummyV[i]=0;
                   15421:     FixedV[i]=0;
                   15422:   }
                   15423:   for(i=ncovcol+1; i <=ncovcol+nqv;i++){
                   15424:     DummyV[i]=1;
                   15425:     FixedV[i]=0;
                   15426:   }
                   15427:   for(i=ncovcol+nqv+1; i <=ncovcol+nqv+ntv;i++){
                   15428:     DummyV[i]=0;
                   15429:     FixedV[i]=1;
                   15430:   }
                   15431:   for(i=ncovcol+nqv+ntv+1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   15432:     DummyV[i]=1;
                   15433:     FixedV[i]=1;
                   15434:   }
                   15435:   for(i=1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   15436:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",i,i,DummyV[i],i,FixedV[i]);
                   15437:     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]);
                   15438:   }
                   15439: 
                   15440: 
                   15441: 
1.186     brouard  15442: /* Main decodemodel */
                   15443: 
1.187     brouard  15444: 
1.223     brouard  15445:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  15446:     goto end;
                   15447: 
1.137     brouard  15448:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   15449:     nbwarn++;
                   15450:     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); 
                   15451:     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); 
                   15452:   }
1.136     brouard  15453:     /*  if(mle==1){*/
1.137     brouard  15454:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   15455:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  15456:   }
                   15457: 
                   15458:     /*-calculation of age at interview from date of interview and age at death -*/
                   15459:   agev=matrix(1,maxwav,1,imx);
                   15460: 
                   15461:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   15462:     goto end;
                   15463: 
1.126     brouard  15464: 
1.136     brouard  15465:   agegomp=(int)agemin;
1.290     brouard  15466:   free_vector(moisnais,firstobs,lastobs);
                   15467:   free_vector(annais,firstobs,lastobs);
1.126     brouard  15468:   /* free_matrix(mint,1,maxwav,1,n);
                   15469:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  15470:   /* free_vector(moisdc,1,n); */
                   15471:   /* free_vector(andc,1,n); */
1.145     brouard  15472:   /* */
                   15473:   
1.126     brouard  15474:   wav=ivector(1,imx);
1.214     brouard  15475:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   15476:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   15477:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   15478:   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.*/
                   15479:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   15480:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  15481:    
                   15482:   /* Concatenates waves */
1.214     brouard  15483:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   15484:      Death is a valid wave (if date is known).
                   15485:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   15486:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   15487:      and mw[mi+1][i]. dh depends on stepm.
                   15488:   */
                   15489: 
1.126     brouard  15490:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  15491:   /* Concatenates waves */
1.145     brouard  15492:  
1.290     brouard  15493:   free_vector(moisdc,firstobs,lastobs);
                   15494:   free_vector(andc,firstobs,lastobs);
1.215     brouard  15495: 
1.126     brouard  15496:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   15497:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   15498:   ncodemax[1]=1;
1.145     brouard  15499:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  15500:   cptcoveff=0;
1.220     brouard  15501:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335     brouard  15502:     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  15503:   }
                   15504:   
                   15505:   ncovcombmax=pow(2,cptcoveff);
1.338     brouard  15506:   invalidvarcomb=ivector(0, ncovcombmax); 
                   15507:   for(i=0;i<ncovcombmax;i++)
1.227     brouard  15508:     invalidvarcomb[i]=0;
                   15509:   
1.211     brouard  15510:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  15511:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  15512:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  15513:   
1.200     brouard  15514:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  15515:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  15516:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  15517:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   15518:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   15519:    * (currently 0 or 1) in the data.
                   15520:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   15521:    * corresponding modality (h,j).
                   15522:    */
                   15523: 
1.145     brouard  15524:   h=0;
                   15525:   /*if (cptcovn > 0) */
1.126     brouard  15526:   m=pow(2,cptcoveff);
                   15527:  
1.144     brouard  15528:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  15529:           * For k=4 covariates, h goes from 1 to m=2**k
                   15530:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   15531:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  15532:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   15533:           *______________________________   *______________________
                   15534:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   15535:           *     2     2     1     1     1   *     1     0  0  0  1 
                   15536:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   15537:           *     4     2     2     1     1   *     3     0  0  1  1 
                   15538:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   15539:           *     6     2     1     2     1   *     5     0  1  0  1 
                   15540:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   15541:           *     8     2     2     2     1   *     7     0  1  1  1 
                   15542:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   15543:           *    10     2     1     1     2   *     9     1  0  0  1 
                   15544:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   15545:           *    12     2     2     1     2   *    11     1  0  1  1 
                   15546:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   15547:           *    14     2     1     2     2   *    13     1  1  0  1 
                   15548:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   15549:           *    16     2     2     2     2   *    15     1  1  1  1          
                   15550:           */                                     
1.212     brouard  15551:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  15552:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   15553:      * and the value of each covariate?
                   15554:      * V1=1, V2=1, V3=2, V4=1 ?
                   15555:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   15556:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   15557:      * In order to get the real value in the data, we use nbcode
                   15558:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   15559:      * We are keeping this crazy system in order to be able (in the future?) 
                   15560:      * to have more than 2 values (0 or 1) for a covariate.
                   15561:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   15562:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   15563:      *              bbbbbbbb
                   15564:      *              76543210     
                   15565:      *   h-1        00000101 (6-1=5)
1.219     brouard  15566:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  15567:      *           &
                   15568:      *     1        00000001 (1)
1.219     brouard  15569:      *              00000000        = 1 & ((h-1) >> (k-1))
                   15570:      *          +1= 00000001 =1 
1.211     brouard  15571:      *
                   15572:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   15573:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   15574:      *    >>k'            11
                   15575:      *          &   00000001
                   15576:      *            = 00000001
                   15577:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   15578:      * Reverse h=6 and m=16?
                   15579:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   15580:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   15581:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   15582:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   15583:      * V3=decodtabm(14,3,2**4)=2
                   15584:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   15585:      *(h-1) >> (j-1)    0011 =13 >> 2
                   15586:      *          &1 000000001
                   15587:      *           = 000000001
                   15588:      *         +1= 000000010 =2
                   15589:      *                  2211
                   15590:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   15591:      *                  V3=2
1.220     brouard  15592:                 * codtabm and decodtabm are identical
1.211     brouard  15593:      */
                   15594: 
1.145     brouard  15595: 
                   15596:  free_ivector(Ndum,-1,NCOVMAX);
                   15597: 
                   15598: 
1.126     brouard  15599:     
1.186     brouard  15600:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  15601:   strcpy(optionfilegnuplot,optionfilefiname);
                   15602:   if(mle==-3)
1.201     brouard  15603:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  15604:   strcat(optionfilegnuplot,".gp");
                   15605: 
                   15606:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   15607:     printf("Problem with file %s",optionfilegnuplot);
                   15608:   }
                   15609:   else{
1.204     brouard  15610:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  15611:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  15612:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   15613:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  15614:   }
                   15615:   /*  fclose(ficgp);*/
1.186     brouard  15616: 
                   15617: 
                   15618:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  15619: 
                   15620:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   15621:   if(mle==-3)
1.201     brouard  15622:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  15623:   strcat(optionfilehtm,".htm");
                   15624:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  15625:     printf("Problem with %s \n",optionfilehtm);
                   15626:     exit(0);
1.126     brouard  15627:   }
                   15628: 
                   15629:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   15630:   strcat(optionfilehtmcov,"-cov.htm");
                   15631:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   15632:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   15633:   }
                   15634:   else{
                   15635:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   15636: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  15637: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  15638:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   15639:   }
                   15640: 
1.335     brouard  15641:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   15642: <title>IMaCh %s</title></head>\n\
                   15643:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   15644: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   15645: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   15646: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   15647: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   15648:   
                   15649:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  15650: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  15651: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.337     brouard  15652: 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  15653: \n\
                   15654: <hr  size=\"2\" color=\"#EC5E5E\">\
                   15655:  <ul><li><h4>Parameter files</h4>\n\
                   15656:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   15657:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   15658:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   15659:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   15660:  - Date and time at start: %s</ul>\n",\
1.335     brouard  15661:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  15662:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   15663:          fileres,fileres,\
                   15664:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   15665:   fflush(fichtm);
                   15666: 
                   15667:   strcpy(pathr,path);
                   15668:   strcat(pathr,optionfilefiname);
1.184     brouard  15669: #ifdef WIN32
                   15670:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   15671: #else
1.126     brouard  15672:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  15673: #endif
                   15674:          
1.126     brouard  15675:   
1.220     brouard  15676:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   15677:                 and for any valid combination of covariates
1.126     brouard  15678:      and prints on file fileres'p'. */
1.359     brouard  15679:   freqsummary(fileres, p, pstart, (double)agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  15680:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  15681: 
                   15682:   fprintf(fichtm,"\n");
1.286     brouard  15683:   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  15684:          ftol, stepm);
                   15685:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   15686:   ncurrv=1;
                   15687:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   15688:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   15689:   ncurrv=i;
                   15690:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  15691:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  15692:   ncurrv=i;
                   15693:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  15694:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  15695:   ncurrv=i;
                   15696:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   15697:   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", \
                   15698:           nlstate, ndeath, maxwav, mle, weightopt);
                   15699: 
                   15700:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   15701: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   15702: 
                   15703:   
1.317     brouard  15704:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  15705: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   15706: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  15707:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  15708:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  15709:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   15710:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   15711:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   15712:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  15713: 
1.126     brouard  15714:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   15715:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   15716:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   15717: 
                   15718:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  15719:   /* For mortality only */
1.126     brouard  15720:   if (mle==-3){
1.136     brouard  15721:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  15722:     for(i=1;i<=NDIM;i++)
                   15723:       for(j=1;j<=NDIM;j++)
                   15724:        ximort[i][j]=0.;
1.186     brouard  15725:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  15726:     cens=ivector(firstobs,lastobs);
                   15727:     ageexmed=vector(firstobs,lastobs);
                   15728:     agecens=vector(firstobs,lastobs);
                   15729:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  15730:                
1.126     brouard  15731:     for (i=1; i<=imx; i++){
                   15732:       dcwave[i]=-1;
                   15733:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  15734:        if (s[m][i]>nlstate) {
                   15735:          dcwave[i]=m;
                   15736:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   15737:          break;
                   15738:        }
1.126     brouard  15739:     }
1.226     brouard  15740:     
1.126     brouard  15741:     for (i=1; i<=imx; i++) {
                   15742:       if (wav[i]>0){
1.226     brouard  15743:        ageexmed[i]=agev[mw[1][i]][i];
                   15744:        j=wav[i];
                   15745:        agecens[i]=1.; 
                   15746:        
                   15747:        if (ageexmed[i]> 1 && wav[i] > 0){
                   15748:          agecens[i]=agev[mw[j][i]][i];
                   15749:          cens[i]= 1;
                   15750:        }else if (ageexmed[i]< 1) 
                   15751:          cens[i]= -1;
                   15752:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   15753:          cens[i]=0 ;
1.126     brouard  15754:       }
                   15755:       else cens[i]=-1;
                   15756:     }
                   15757:     
                   15758:     for (i=1;i<=NDIM;i++) {
                   15759:       for (j=1;j<=NDIM;j++)
1.226     brouard  15760:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  15761:     }
                   15762:     
1.302     brouard  15763:     p[1]=0.0268; p[NDIM]=0.083;
                   15764:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  15765:     
                   15766:     
1.136     brouard  15767: #ifdef GSL
                   15768:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  15769: #else
1.359     brouard  15770:     printf("Powell-mort\n");  fprintf(ficlog,"Powell-mort\n");
1.136     brouard  15771: #endif
1.201     brouard  15772:     strcpy(filerespow,"POW-MORT_"); 
                   15773:     strcat(filerespow,fileresu);
1.126     brouard  15774:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   15775:       printf("Problem with resultfile: %s\n", filerespow);
                   15776:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   15777:     }
1.136     brouard  15778: #ifdef GSL
                   15779:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  15780: #else
1.126     brouard  15781:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  15782: #endif
1.126     brouard  15783:     /*  for (i=1;i<=nlstate;i++)
                   15784:        for(j=1;j<=nlstate+ndeath;j++)
                   15785:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   15786:     */
                   15787:     fprintf(ficrespow,"\n");
1.136     brouard  15788: #ifdef GSL
                   15789:     /* gsl starts here */ 
                   15790:     T = gsl_multimin_fminimizer_nmsimplex;
                   15791:     gsl_multimin_fminimizer *sfm = NULL;
                   15792:     gsl_vector *ss, *x;
                   15793:     gsl_multimin_function minex_func;
                   15794: 
                   15795:     /* Initial vertex size vector */
                   15796:     ss = gsl_vector_alloc (NDIM);
                   15797:     
                   15798:     if (ss == NULL){
                   15799:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   15800:     }
                   15801:     /* Set all step sizes to 1 */
                   15802:     gsl_vector_set_all (ss, 0.001);
                   15803: 
                   15804:     /* Starting point */
1.126     brouard  15805:     
1.136     brouard  15806:     x = gsl_vector_alloc (NDIM);
                   15807:     
                   15808:     if (x == NULL){
                   15809:       gsl_vector_free(ss);
                   15810:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   15811:     }
                   15812:   
                   15813:     /* Initialize method and iterate */
                   15814:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  15815:     /*     gsl_vector_set(x, 0, 0.0268); */
                   15816:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  15817:     gsl_vector_set(x, 0, p[1]);
                   15818:     gsl_vector_set(x, 1, p[2]);
                   15819: 
                   15820:     minex_func.f = &gompertz_f;
                   15821:     minex_func.n = NDIM;
                   15822:     minex_func.params = (void *)&p; /* ??? */
                   15823:     
                   15824:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   15825:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   15826:     
                   15827:     printf("Iterations beginning .....\n\n");
                   15828:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   15829: 
                   15830:     iteri=0;
                   15831:     while (rval == GSL_CONTINUE){
                   15832:       iteri++;
                   15833:       status = gsl_multimin_fminimizer_iterate(sfm);
                   15834:       
                   15835:       if (status) printf("error: %s\n", gsl_strerror (status));
                   15836:       fflush(0);
                   15837:       
                   15838:       if (status) 
                   15839:         break;
                   15840:       
                   15841:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   15842:       ssval = gsl_multimin_fminimizer_size (sfm);
                   15843:       
                   15844:       if (rval == GSL_SUCCESS)
                   15845:         printf ("converged to a local maximum at\n");
                   15846:       
                   15847:       printf("%5d ", iteri);
                   15848:       for (it = 0; it < NDIM; it++){
                   15849:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   15850:       }
                   15851:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   15852:     }
                   15853:     
                   15854:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   15855:     
                   15856:     gsl_vector_free(x); /* initial values */
                   15857:     gsl_vector_free(ss); /* inital step size */
                   15858:     for (it=0; it<NDIM; it++){
                   15859:       p[it+1]=gsl_vector_get(sfm->x,it);
                   15860:       fprintf(ficrespow," %.12lf", p[it]);
                   15861:     }
                   15862:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   15863: #endif
                   15864: #ifdef POWELL
1.361     brouard  15865: #ifdef LINMINORIGINAL
                   15866: #else /* LINMINORIGINAL */
                   15867:   
                   15868:   flatdir=ivector(1,npar); 
                   15869:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   15870: #endif /*LINMINORIGINAL */
1.362     brouard  15871:     /* powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz); */
                   15872:   /* double h0=0.25; */
                   15873:   macheps=pow(16.0,-13.0);
                   15874:   printf("Praxis Gegenfurtner mle=%d\n",mle);
                   15875:   fprintf(ficlog, "Praxis  Gegenfurtner mle=%d\n", mle);fflush(ficlog);
                   15876:    /* ffmin = praxis(ftol,macheps, h0, npar, prin, p, gompertz); */
                   15877:   /* For the Gompertz we use only two parameters */
                   15878:   int _npar=2;
                   15879:    ffmin = praxis(ftol,macheps, h0, _npar, 4, p, gompertz);
                   15880:   printf("End Praxis\n");
1.126     brouard  15881:     fclose(ficrespow);
1.361     brouard  15882: #ifdef LINMINORIGINAL
                   15883: #else
                   15884:       free_ivector(flatdir,1,npar); 
                   15885: #endif  /* LINMINORIGINAL*/
1.364   ! brouard  15886: #endif /* POWELL */   
1.203     brouard  15887:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  15888: 
                   15889:     for(i=1; i <=NDIM; i++)
                   15890:       for(j=i+1;j<=NDIM;j++)
1.359     brouard  15891:        matcov[i][j]=matcov[j][i];
1.126     brouard  15892:     
                   15893:     printf("\nCovariance matrix\n ");
1.203     brouard  15894:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  15895:     for(i=1; i <=NDIM; i++) {
                   15896:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  15897:                                printf("%f ",matcov[i][j]);
                   15898:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  15899:       }
1.203     brouard  15900:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  15901:     }
                   15902:     
                   15903:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  15904:     for (i=1;i<=NDIM;i++) {
1.126     brouard  15905:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  15906:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   15907:     }
1.302     brouard  15908:     lsurv=vector(agegomp,AGESUP);
                   15909:     lpop=vector(agegomp,AGESUP);
                   15910:     tpop=vector(agegomp,AGESUP);
1.126     brouard  15911:     lsurv[agegomp]=100000;
                   15912:     
                   15913:     for (k=agegomp;k<=AGESUP;k++) {
                   15914:       agemortsup=k;
                   15915:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   15916:     }
                   15917:     
                   15918:     for (k=agegomp;k<agemortsup;k++)
                   15919:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   15920:     
                   15921:     for (k=agegomp;k<agemortsup;k++){
                   15922:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   15923:       sumlpop=sumlpop+lpop[k];
                   15924:     }
                   15925:     
                   15926:     tpop[agegomp]=sumlpop;
                   15927:     for (k=agegomp;k<(agemortsup-3);k++){
                   15928:       /*  tpop[k+1]=2;*/
                   15929:       tpop[k+1]=tpop[k]-lpop[k];
                   15930:     }
                   15931:     
                   15932:     
                   15933:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   15934:     for (k=agegomp;k<(agemortsup-2);k++) 
                   15935:       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]);
                   15936:     
                   15937:     
                   15938:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  15939:                ageminpar=50;
                   15940:                agemaxpar=100;
1.194     brouard  15941:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   15942:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   15943: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   15944: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   15945:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   15946: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   15947: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  15948:     }else{
                   15949:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   15950:                        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  15951:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  15952:                }
1.201     brouard  15953:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  15954:                     stepm, weightopt,\
                   15955:                     model,imx,p,matcov,agemortsup);
                   15956:     
1.302     brouard  15957:     free_vector(lsurv,agegomp,AGESUP);
                   15958:     free_vector(lpop,agegomp,AGESUP);
                   15959:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  15960:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  15961:     free_ivector(dcwave,firstobs,lastobs);
                   15962:     free_vector(agecens,firstobs,lastobs);
                   15963:     free_vector(ageexmed,firstobs,lastobs);
                   15964:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  15965: #ifdef GSL
1.136     brouard  15966: #endif
1.186     brouard  15967:   } /* Endof if mle==-3 mortality only */
1.205     brouard  15968:   /* Standard  */
                   15969:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   15970:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   15971:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  15972:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  15973:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   15974:     for (k=1; k<=npar;k++)
                   15975:       printf(" %d %8.5f",k,p[k]);
                   15976:     printf("\n");
1.205     brouard  15977:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   15978:       /* mlikeli uses func not funcone */
1.247     brouard  15979:       /* for(i=1;i<nlstate;i++){ */
                   15980:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   15981:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   15982:       /* } */
1.205     brouard  15983:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   15984:     }
                   15985:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   15986:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   15987:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   15988:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   15989:     }
                   15990:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  15991:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   15992:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335     brouard  15993:           /* exit(0); */
1.126     brouard  15994:     for (k=1; k<=npar;k++)
                   15995:       printf(" %d %8.5f",k,p[k]);
                   15996:     printf("\n");
                   15997:     
                   15998:     /*--------- results files --------------*/
1.283     brouard  15999:     /* 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  16000:     
                   16001:     
                   16002:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  16003:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  16004:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  16005: 
                   16006:     printf("#model=  1      +     age ");
                   16007:     fprintf(ficres,"#model=  1      +     age ");
                   16008:     fprintf(ficlog,"#model=  1      +     age ");
                   16009:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   16010: </ul>", model);
                   16011: 
                   16012:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   16013:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   16014:     if(nagesqr==1){
                   16015:       printf("  + age*age  ");
                   16016:       fprintf(ficres,"  + age*age  ");
                   16017:       fprintf(ficlog,"  + age*age  ");
                   16018:       fprintf(fichtm, "<th>+ age*age</th>");
                   16019:     }
1.362     brouard  16020:     for(j=1;j <=ncovmodel-2-nagesqr;j++){
1.319     brouard  16021:       if(Typevar[j]==0) {
                   16022:        printf("  +      V%d  ",Tvar[j]);
                   16023:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   16024:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   16025:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   16026:       }else if(Typevar[j]==1) {
                   16027:        printf("  +    V%d*age ",Tvar[j]);
                   16028:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   16029:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   16030:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   16031:       }else if(Typevar[j]==2) {
                   16032:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   16033:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   16034:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   16035:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  16036:       }else if(Typevar[j]==3) { /* TO VERIFY */
                   16037:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   16038:        fprintf(ficres,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   16039:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   16040:        fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  16041:       }
                   16042:     }
                   16043:     printf("\n");
                   16044:     fprintf(ficres,"\n");
                   16045:     fprintf(ficlog,"\n");
                   16046:     fprintf(fichtm, "</tr>");
                   16047:     fprintf(fichtm, "\n");
                   16048:     
                   16049:     
1.126     brouard  16050:     for(i=1,jk=1; i <=nlstate; i++){
                   16051:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  16052:        if (k != i) {
1.319     brouard  16053:          fprintf(fichtm, "<tr>");
1.225     brouard  16054:          printf("%d%d ",i,k);
                   16055:          fprintf(ficlog,"%d%d ",i,k);
                   16056:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  16057:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  16058:          for(j=1; j <=ncovmodel; j++){
                   16059:            printf("%12.7f ",p[jk]);
                   16060:            fprintf(ficlog,"%12.7f ",p[jk]);
                   16061:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  16062:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  16063:            jk++; 
                   16064:          }
                   16065:          printf("\n");
                   16066:          fprintf(ficlog,"\n");
                   16067:          fprintf(ficres,"\n");
1.319     brouard  16068:          fprintf(fichtm, "</tr>\n");
1.225     brouard  16069:        }
1.126     brouard  16070:       }
                   16071:     }
1.319     brouard  16072:     /* fprintf(fichtm,"</tr>\n"); */
                   16073:     fprintf(fichtm,"</table>\n");
                   16074:     fprintf(fichtm, "\n");
                   16075: 
1.203     brouard  16076:     if(mle != 0){
                   16077:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  16078:       ftolhess=ftol; /* Usually correct */
1.203     brouard  16079:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   16080:       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");
                   16081:       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  16082:       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  16083:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   16084:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   16085:       if(nagesqr==1){
                   16086:        printf("  + age*age  ");
                   16087:        fprintf(ficres,"  + age*age  ");
                   16088:        fprintf(ficlog,"  + age*age  ");
                   16089:        fprintf(fichtm, "<th>+ age*age</th>");
                   16090:       }
1.362     brouard  16091:       for(j=1;j <=ncovmodel-2-nagesqr;j++){
1.319     brouard  16092:        if(Typevar[j]==0) {
                   16093:          printf("  +      V%d  ",Tvar[j]);
                   16094:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   16095:        }else if(Typevar[j]==1) {
                   16096:          printf("  +    V%d*age ",Tvar[j]);
                   16097:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   16098:        }else if(Typevar[j]==2) {
                   16099:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  16100:        }else if(Typevar[j]==3) { /* TO VERIFY */
                   16101:          fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  16102:        }
                   16103:       }
                   16104:       fprintf(fichtm, "</tr>\n");
                   16105:  
1.203     brouard  16106:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  16107:        for(k=1; k <=(nlstate+ndeath); k++){
                   16108:          if (k != i) {
1.319     brouard  16109:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  16110:            printf("%d%d ",i,k);
                   16111:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  16112:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  16113:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  16114:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  16115:              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]));
                   16116:              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  16117:              if(fabs(wald) > 1.96){
1.321     brouard  16118:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  16119:              }else{
                   16120:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   16121:              }
1.324     brouard  16122:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  16123:              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  16124:              jk++; 
                   16125:            }
                   16126:            printf("\n");
                   16127:            fprintf(ficlog,"\n");
1.319     brouard  16128:            fprintf(fichtm, "</tr>\n");
1.225     brouard  16129:          }
                   16130:        }
1.193     brouard  16131:       }
1.203     brouard  16132:     } /* end of hesscov and Wald tests */
1.319     brouard  16133:     fprintf(fichtm,"</table>\n");
1.225     brouard  16134:     
1.203     brouard  16135:     /*  */
1.126     brouard  16136:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   16137:     printf("# Scales (for hessian or gradient estimation)\n");
                   16138:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   16139:     for(i=1,jk=1; i <=nlstate; i++){
                   16140:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  16141:        if (j!=i) {
                   16142:          fprintf(ficres,"%1d%1d",i,j);
                   16143:          printf("%1d%1d",i,j);
                   16144:          fprintf(ficlog,"%1d%1d",i,j);
                   16145:          for(k=1; k<=ncovmodel;k++){
                   16146:            printf(" %.5e",delti[jk]);
                   16147:            fprintf(ficlog," %.5e",delti[jk]);
                   16148:            fprintf(ficres," %.5e",delti[jk]);
                   16149:            jk++;
                   16150:          }
                   16151:          printf("\n");
                   16152:          fprintf(ficlog,"\n");
                   16153:          fprintf(ficres,"\n");
                   16154:        }
1.126     brouard  16155:       }
                   16156:     }
                   16157:     
                   16158:     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  16159:     if(mle >= 1) /* Too big for the screen */
1.126     brouard  16160:       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");
                   16161:     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");
                   16162:     /* # 121 Var(a12)\n\ */
                   16163:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   16164:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   16165:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   16166:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   16167:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   16168:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   16169:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   16170:     
                   16171:     
                   16172:     /* Just to have a covariance matrix which will be more understandable
                   16173:        even is we still don't want to manage dictionary of variables
                   16174:     */
                   16175:     for(itimes=1;itimes<=2;itimes++){
                   16176:       jj=0;
                   16177:       for(i=1; i <=nlstate; i++){
1.225     brouard  16178:        for(j=1; j <=nlstate+ndeath; j++){
                   16179:          if(j==i) continue;
                   16180:          for(k=1; k<=ncovmodel;k++){
                   16181:            jj++;
                   16182:            ca[0]= k+'a'-1;ca[1]='\0';
                   16183:            if(itimes==1){
                   16184:              if(mle>=1)
                   16185:                printf("#%1d%1d%d",i,j,k);
                   16186:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   16187:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   16188:            }else{
                   16189:              if(mle>=1)
                   16190:                printf("%1d%1d%d",i,j,k);
                   16191:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   16192:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   16193:            }
                   16194:            ll=0;
                   16195:            for(li=1;li <=nlstate; li++){
                   16196:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   16197:                if(lj==li) continue;
                   16198:                for(lk=1;lk<=ncovmodel;lk++){
                   16199:                  ll++;
                   16200:                  if(ll<=jj){
                   16201:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   16202:                    if(ll<jj){
                   16203:                      if(itimes==1){
                   16204:                        if(mle>=1)
                   16205:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   16206:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   16207:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   16208:                      }else{
                   16209:                        if(mle>=1)
                   16210:                          printf(" %.5e",matcov[jj][ll]); 
                   16211:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   16212:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   16213:                      }
                   16214:                    }else{
                   16215:                      if(itimes==1){
                   16216:                        if(mle>=1)
                   16217:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   16218:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   16219:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   16220:                      }else{
                   16221:                        if(mle>=1)
                   16222:                          printf(" %.7e",matcov[jj][ll]); 
                   16223:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   16224:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   16225:                      }
                   16226:                    }
                   16227:                  }
                   16228:                } /* end lk */
                   16229:              } /* end lj */
                   16230:            } /* end li */
                   16231:            if(mle>=1)
                   16232:              printf("\n");
                   16233:            fprintf(ficlog,"\n");
                   16234:            fprintf(ficres,"\n");
                   16235:            numlinepar++;
                   16236:          } /* end k*/
                   16237:        } /*end j */
1.126     brouard  16238:       } /* end i */
                   16239:     } /* end itimes */
                   16240:     
                   16241:     fflush(ficlog);
                   16242:     fflush(ficres);
1.225     brouard  16243:     while(fgets(line, MAXLINE, ficpar)) {
                   16244:       /* If line starts with a # it is a comment */
                   16245:       if (line[0] == '#') {
                   16246:        numlinepar++;
                   16247:        fputs(line,stdout);
                   16248:        fputs(line,ficparo);
                   16249:        fputs(line,ficlog);
1.299     brouard  16250:        fputs(line,ficres);
1.225     brouard  16251:        continue;
                   16252:       }else
                   16253:        break;
                   16254:     }
                   16255:     
1.209     brouard  16256:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   16257:     /*   ungetc(c,ficpar); */
                   16258:     /*   fgets(line, MAXLINE, ficpar); */
                   16259:     /*   fputs(line,stdout); */
                   16260:     /*   fputs(line,ficparo); */
                   16261:     /* } */
                   16262:     /* ungetc(c,ficpar); */
1.126     brouard  16263:     
                   16264:     estepm=0;
1.209     brouard  16265:     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  16266:       
                   16267:       if (num_filled != 6) {
                   16268:        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);
                   16269:        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);
                   16270:        goto end;
                   16271:       }
                   16272:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   16273:     }
                   16274:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   16275:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   16276:     
1.209     brouard  16277:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  16278:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   16279:     if (fage <= 2) {
                   16280:       bage = ageminpar;
                   16281:       fage = agemaxpar;
                   16282:     }
                   16283:     
                   16284:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  16285:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   16286:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  16287:                
1.186     brouard  16288:     /* Other stuffs, more or less useful */    
1.254     brouard  16289:     while(fgets(line, MAXLINE, ficpar)) {
                   16290:       /* If line starts with a # it is a comment */
                   16291:       if (line[0] == '#') {
                   16292:        numlinepar++;
                   16293:        fputs(line,stdout);
                   16294:        fputs(line,ficparo);
                   16295:        fputs(line,ficlog);
1.299     brouard  16296:        fputs(line,ficres);
1.254     brouard  16297:        continue;
                   16298:       }else
                   16299:        break;
                   16300:     }
                   16301: 
                   16302:     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){
                   16303:       
                   16304:       if (num_filled != 7) {
                   16305:        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);
                   16306:        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);
                   16307:        goto end;
                   16308:       }
                   16309:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   16310:       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);
                   16311:       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);
                   16312:       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  16313:     }
1.254     brouard  16314: 
                   16315:     while(fgets(line, MAXLINE, ficpar)) {
                   16316:       /* If line starts with a # it is a comment */
                   16317:       if (line[0] == '#') {
                   16318:        numlinepar++;
                   16319:        fputs(line,stdout);
                   16320:        fputs(line,ficparo);
                   16321:        fputs(line,ficlog);
1.299     brouard  16322:        fputs(line,ficres);
1.254     brouard  16323:        continue;
                   16324:       }else
                   16325:        break;
1.126     brouard  16326:     }
                   16327:     
                   16328:     
                   16329:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   16330:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   16331:     
1.254     brouard  16332:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   16333:       if (num_filled != 1) {
                   16334:        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);
                   16335:        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);
                   16336:        goto end;
                   16337:       }
                   16338:       printf("pop_based=%d\n",popbased);
                   16339:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   16340:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   16341:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   16342:     }
                   16343:      
1.258     brouard  16344:     /* Results */
1.359     brouard  16345:     /* Value of covariate in each resultine will be computed (if product) and sorted according to model rank */
1.332     brouard  16346:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   16347:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  16348:     endishere=0;
1.258     brouard  16349:     nresult=0;
1.308     brouard  16350:     parameterline=0;
1.258     brouard  16351:     do{
                   16352:       if(!fgets(line, MAXLINE, ficpar)){
                   16353:        endishere=1;
1.308     brouard  16354:        parameterline=15;
1.258     brouard  16355:       }else if (line[0] == '#') {
                   16356:        /* If line starts with a # it is a comment */
1.254     brouard  16357:        numlinepar++;
                   16358:        fputs(line,stdout);
                   16359:        fputs(line,ficparo);
                   16360:        fputs(line,ficlog);
1.299     brouard  16361:        fputs(line,ficres);
1.254     brouard  16362:        continue;
1.258     brouard  16363:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   16364:        parameterline=11;
1.296     brouard  16365:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  16366:        parameterline=12;
1.307     brouard  16367:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  16368:        parameterline=13;
1.307     brouard  16369:       }
1.258     brouard  16370:       else{
                   16371:        parameterline=14;
1.254     brouard  16372:       }
1.308     brouard  16373:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  16374:       case 11:
1.296     brouard  16375:        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)){
                   16376:                  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  16377:          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);
                   16378:          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);
                   16379:          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);
                   16380:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  16381:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   16382:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  16383:           prvforecast = 1;
                   16384:        } 
                   16385:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  16386:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   16387:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   16388:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  16389:           prvforecast = 2;
                   16390:        }
                   16391:        else {
                   16392:          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);
                   16393:          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);
                   16394:          goto end;
1.258     brouard  16395:        }
1.254     brouard  16396:        break;
1.258     brouard  16397:       case 12:
1.296     brouard  16398:        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)){
                   16399:           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);
                   16400:          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);
                   16401:          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);
                   16402:          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);
                   16403:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  16404:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   16405:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  16406:           prvbackcast = 1;
                   16407:        } 
                   16408:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  16409:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   16410:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   16411:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  16412:           prvbackcast = 2;
                   16413:        }
                   16414:        else {
                   16415:          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);
                   16416:          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);
                   16417:          goto end;
1.258     brouard  16418:        }
1.230     brouard  16419:        break;
1.258     brouard  16420:       case 13:
1.332     brouard  16421:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  16422:        nresult++; /* Sum of resultlines */
1.342     brouard  16423:        /* printf("Result %d: result:%s\n",nresult, resultlineori); */
1.332     brouard  16424:        /* removefirstspace(&resultlineori); */
                   16425:        
                   16426:        if(strstr(resultlineori,"v") !=0){
                   16427:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   16428:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   16429:          return 1;
                   16430:        }
                   16431:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
1.342     brouard  16432:        /* printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori); */
1.318     brouard  16433:        if(nresult > MAXRESULTLINESPONE-1){
                   16434:          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);
                   16435:          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  16436:          goto end;
                   16437:        }
1.332     brouard  16438:        
1.310     brouard  16439:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  16440:          fprintf(ficparo,"result: %s\n",resultline);
                   16441:          fprintf(ficres,"result: %s\n",resultline);
                   16442:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  16443:        } else
                   16444:          goto end;
1.307     brouard  16445:        break;
                   16446:       case 14:
                   16447:        printf("Error: Unknown command '%s'\n",line);
                   16448:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  16449:        if(line[0] == ' ' || line[0] == '\n'){
                   16450:          printf("It should not be an empty line '%s'\n",line);
                   16451:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   16452:        }         
1.307     brouard  16453:        if(ncovmodel >=2 && nresult==0 ){
                   16454:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   16455:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  16456:        }
1.307     brouard  16457:        /* goto end; */
                   16458:        break;
1.308     brouard  16459:       case 15:
                   16460:        printf("End of resultlines.\n");
                   16461:        fprintf(ficlog,"End of resultlines.\n");
                   16462:        break;
                   16463:       default: /* parameterline =0 */
1.307     brouard  16464:        nresult=1;
                   16465:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  16466:       } /* End switch parameterline */
                   16467:     }while(endishere==0); /* End do */
1.126     brouard  16468:     
1.230     brouard  16469:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  16470:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  16471:     
                   16472:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  16473:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  16474:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  16475: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   16476: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  16477:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  16478: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   16479: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  16480:     }else{
1.270     brouard  16481:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  16482:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   16483:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   16484:       if(prvforecast==1){
                   16485:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   16486:         jprojd=jproj1;
                   16487:         mprojd=mproj1;
                   16488:         anprojd=anproj1;
                   16489:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   16490:         jprojf=jproj2;
                   16491:         mprojf=mproj2;
                   16492:         anprojf=anproj2;
                   16493:       } else if(prvforecast == 2){
                   16494:         dateprojd=dateintmean;
                   16495:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   16496:         dateprojf=dateintmean+yrfproj;
                   16497:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   16498:       }
                   16499:       if(prvbackcast==1){
                   16500:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   16501:         jbackd=jback1;
                   16502:         mbackd=mback1;
                   16503:         anbackd=anback1;
                   16504:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   16505:         jbackf=jback2;
                   16506:         mbackf=mback2;
                   16507:         anbackf=anback2;
                   16508:       } else if(prvbackcast == 2){
                   16509:         datebackd=dateintmean;
                   16510:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   16511:         datebackf=dateintmean-yrbproj;
                   16512:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   16513:       }
                   16514:       
1.350     brouard  16515:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);/* HERE valgrind Tvard*/
1.220     brouard  16516:     }
                   16517:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  16518:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   16519:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  16520:                
1.225     brouard  16521:     /*------------ free_vector  -------------*/
                   16522:     /*  chdir(path); */
1.220     brouard  16523:                
1.215     brouard  16524:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   16525:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   16526:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   16527:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  16528:     free_lvector(num,firstobs,lastobs);
                   16529:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  16530:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   16531:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   16532:     fclose(ficparo);
                   16533:     fclose(ficres);
1.220     brouard  16534:                
                   16535:                
1.186     brouard  16536:     /* Other results (useful)*/
1.220     brouard  16537:                
                   16538:                
1.126     brouard  16539:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  16540:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   16541:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  16542:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  16543:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  16544:     fclose(ficrespl);
                   16545: 
                   16546:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  16547:     /*#include "hpijx.h"*/
1.332     brouard  16548:     /** 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?*/
                   16549:     /* calls hpxij with combination k */
1.180     brouard  16550:     hPijx(p, bage, fage);
1.145     brouard  16551:     fclose(ficrespij);
1.227     brouard  16552:     
1.220     brouard  16553:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  16554:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  16555:     k=1;
1.126     brouard  16556:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  16557:     
1.269     brouard  16558:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   16559:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   16560:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  16561:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  16562:        for(k=1;k<=ncovcombmax;k++)
                   16563:          probs[i][j][k]=0.;
1.269     brouard  16564:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   16565:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  16566:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  16567:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   16568:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  16569:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  16570:          for(k=1;k<=ncovcombmax;k++)
                   16571:            mobaverages[i][j][k]=0.;
1.219     brouard  16572:       mobaverage=mobaverages;
                   16573:       if (mobilav!=0) {
1.235     brouard  16574:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  16575:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  16576:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   16577:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   16578:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   16579:        }
1.269     brouard  16580:       } else if (mobilavproj !=0) {
1.235     brouard  16581:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  16582:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  16583:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   16584:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   16585:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   16586:        }
1.269     brouard  16587:       }else{
                   16588:        printf("Internal error moving average\n");
                   16589:        fflush(stdout);
                   16590:        exit(1);
1.219     brouard  16591:       }
                   16592:     }/* end if moving average */
1.227     brouard  16593:     
1.126     brouard  16594:     /*---------- Forecasting ------------------*/
1.296     brouard  16595:     if(prevfcast==1){ 
                   16596:       /*   /\*    if(stepm ==1){*\/ */
                   16597:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   16598:       /*This done previously after freqsummary.*/
                   16599:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   16600:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   16601:       
                   16602:       /* } else if (prvforecast==2){ */
                   16603:       /*   /\*    if(stepm ==1){*\/ */
                   16604:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   16605:       /* } */
                   16606:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   16607:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  16608:     }
1.269     brouard  16609: 
1.296     brouard  16610:     /* Prevbcasting */
                   16611:     if(prevbcast==1){
1.219     brouard  16612:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   16613:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   16614:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   16615: 
                   16616:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   16617: 
                   16618:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  16619: 
1.219     brouard  16620:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   16621:       fclose(ficresplb);
                   16622: 
1.222     brouard  16623:       hBijx(p, bage, fage, mobaverage);
                   16624:       fclose(ficrespijb);
1.219     brouard  16625: 
1.296     brouard  16626:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   16627:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   16628:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   16629:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   16630:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   16631:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   16632: 
                   16633:       
1.269     brouard  16634:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  16635: 
                   16636:       
1.269     brouard  16637:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  16638:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   16639:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   16640:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  16641:     }    /* end  Prevbcasting */
1.268     brouard  16642:  
1.186     brouard  16643:  
                   16644:     /* ------ Other prevalence ratios------------ */
1.126     brouard  16645: 
1.215     brouard  16646:     free_ivector(wav,1,imx);
                   16647:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   16648:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   16649:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  16650:                
                   16651:                
1.127     brouard  16652:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  16653:                
1.201     brouard  16654:     strcpy(filerese,"E_");
                   16655:     strcat(filerese,fileresu);
1.126     brouard  16656:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   16657:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   16658:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   16659:     }
1.208     brouard  16660:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   16661:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  16662: 
                   16663:     pstamp(ficreseij);
1.219     brouard  16664:                
1.351     brouard  16665:     /* i1=pow(2,cptcoveff); /\* Number of combination of dummy covariates *\/ */
                   16666:     /* if (cptcovn < 1){i1=1;} */
1.235     brouard  16667:     
1.351     brouard  16668:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   16669:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   16670:       /* if(i1 != 1 && TKresult[nres]!= k) */
                   16671:       /*       continue; */
1.219     brouard  16672:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  16673:       printf("\n#****** ");
1.351     brouard  16674:       for(j=1;j<=cptcovs;j++){
                   16675:       /* for(j=1;j<=cptcoveff;j++) { */
                   16676:        /* fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16677:        fprintf(ficreseij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   16678:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   16679:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.235     brouard  16680:       }
                   16681:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.337     brouard  16682:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   16683:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  16684:       }
                   16685:       fprintf(ficreseij,"******\n");
1.235     brouard  16686:       printf("******\n");
1.219     brouard  16687:       
                   16688:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   16689:       oldm=oldms;savm=savms;
1.330     brouard  16690:       /* 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  16691:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  16692:       
1.219     brouard  16693:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  16694:     }
                   16695:     fclose(ficreseij);
1.208     brouard  16696:     printf("done evsij\n");fflush(stdout);
                   16697:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  16698: 
1.218     brouard  16699:                
1.227     brouard  16700:     /*---------- State-specific expectancies and variances ------------*/
1.336     brouard  16701:     /* Should be moved in a function */                
1.201     brouard  16702:     strcpy(filerest,"T_");
                   16703:     strcat(filerest,fileresu);
1.127     brouard  16704:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   16705:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   16706:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   16707:     }
1.208     brouard  16708:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   16709:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  16710:     strcpy(fileresstde,"STDE_");
                   16711:     strcat(fileresstde,fileresu);
1.126     brouard  16712:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  16713:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   16714:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  16715:     }
1.227     brouard  16716:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   16717:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  16718: 
1.201     brouard  16719:     strcpy(filerescve,"CVE_");
                   16720:     strcat(filerescve,fileresu);
1.126     brouard  16721:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  16722:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   16723:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  16724:     }
1.227     brouard  16725:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   16726:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  16727: 
1.201     brouard  16728:     strcpy(fileresv,"V_");
                   16729:     strcat(fileresv,fileresu);
1.126     brouard  16730:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   16731:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   16732:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   16733:     }
1.227     brouard  16734:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   16735:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  16736: 
1.235     brouard  16737:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   16738:     if (cptcovn < 1){i1=1;}
                   16739:     
1.334     brouard  16740:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   16741:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   16742:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   16743:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   16744:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   16745:       /* */
                   16746:       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  16747:        continue;
1.359     brouard  16748:       printf("\n# model=1+age+%s \n#****** Result for:", model);  /* HERE model is empty */
                   16749:       fprintf(ficrest,"\n# model=1+age+%s \n#****** Result for:", model);
                   16750:       fprintf(ficlog,"\n# model=1+age+%s \n#****** Result for:", model);
1.334     brouard  16751:       /* It might not be a good idea to mix dummies and quantitative */
                   16752:       /* 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 *\/ */
                   16753:       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 */
                   16754:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   16755:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   16756:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   16757:         * (V5 is quanti) V4 and V3 are dummies
                   16758:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   16759:         *                                                              l=1 l=2
                   16760:         *                                                           k=1  1   1   0   0
                   16761:         *                                                           k=2  2   1   1   0
                   16762:         *                                                           k=3 [1] [2]  0   1
                   16763:         *                                                           k=4  2   2   1   1
                   16764:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   16765:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   16766:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   16767:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   16768:         */
                   16769:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   16770:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   16771: /* We give up with the combinations!! */
1.342     brouard  16772:        /* if(debugILK) */
                   16773:        /*   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  16774: 
                   16775:        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  16776:          /* 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] */
                   16777:          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  */
                   16778:          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  */
                   16779:          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  16780:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   16781:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   16782:          }else{
                   16783:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   16784:          }
                   16785:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16786:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16787:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   16788:          /* For each selected (single) quantitative value */
1.337     brouard  16789:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   16790:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   16791:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
1.334     brouard  16792:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   16793:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   16794:          }else{
                   16795:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   16796:          }
                   16797:        }else{
                   16798:          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 */
                   16799:          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 */
                   16800:          exit(1);
                   16801:        }
1.335     brouard  16802:       } /* End loop for each variable in the resultline */
1.334     brouard  16803:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   16804:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   16805:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   16806:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   16807:       /* }      */
1.208     brouard  16808:       fprintf(ficrest,"******\n");
1.227     brouard  16809:       fprintf(ficlog,"******\n");
                   16810:       printf("******\n");
1.208     brouard  16811:       
                   16812:       fprintf(ficresstdeij,"\n#****** ");
                   16813:       fprintf(ficrescveij,"\n#****** ");
1.337     brouard  16814:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
                   16815:       /* But it won't be sorted and depends on how the resultline is ordered */
1.225     brouard  16816:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  16817:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   16818:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16819:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16820:       }
                   16821:       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  16822:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   16823:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  16824:       }        
1.208     brouard  16825:       fprintf(ficresstdeij,"******\n");
                   16826:       fprintf(ficrescveij,"******\n");
                   16827:       
                   16828:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  16829:       /* pstamp(ficresvij); */
1.225     brouard  16830:       for(j=1;j<=cptcoveff;j++) 
1.335     brouard  16831:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   16832:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  16833:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  16834:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
1.337     brouard  16835:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  16836:       }        
1.208     brouard  16837:       fprintf(ficresvij,"******\n");
                   16838:       
                   16839:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   16840:       oldm=oldms;savm=savms;
1.235     brouard  16841:       printf(" cvevsij ");
                   16842:       fprintf(ficlog, " cvevsij ");
                   16843:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  16844:       printf(" end cvevsij \n ");
                   16845:       fprintf(ficlog, " end cvevsij \n ");
                   16846:       
                   16847:       /*
                   16848:        */
                   16849:       /* goto endfree; */
                   16850:       
                   16851:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   16852:       pstamp(ficrest);
                   16853:       
1.269     brouard  16854:       epj=vector(1,nlstate+1);
1.208     brouard  16855:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  16856:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   16857:        cptcod= 0; /* To be deleted */
1.360     brouard  16858:        printf("varevsij vpopbased=%d popbased=%d \n",vpopbased,popbased);
                   16859:        fprintf(ficlog, "varevsij vpopbased=%d popbased=%d \n",vpopbased,popbased);
1.361     brouard  16860:        /* 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 */
                   16861:        /* Depending of popbased which changes the prevalences, either cross-sectional or period */
1.235     brouard  16862:        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  16863:        fprintf(ficrest,"# Total life expectancy with std error and decomposition into time to be expected in each state\n\
                   16864: #  (these are weighted average of eij where weights are ");
1.227     brouard  16865:        if(vpopbased==1)
1.360     brouard  16866:          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  16867:        else
1.360     brouard  16868:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each state) \n");
                   16869:        fprintf(ficrest,"# with proportions of time spent in each state with standard error (on the right of the table.\n ");
1.335     brouard  16870:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  16871:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
1.360     brouard  16872:        for (i=1;i<=nlstate;i++) fprintf(ficrest," %% e.%d/e.. (std) ",i);
1.227     brouard  16873:        fprintf(ficrest,"\n");
                   16874:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  16875:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   16876:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  16877:        for(age=bage; age <=fage ;age++){
1.235     brouard  16878:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  16879:          if (vpopbased==1) {
                   16880:            if(mobilav ==0){
                   16881:              for(i=1; i<=nlstate;i++)
                   16882:                prlim[i][i]=probs[(int)age][i][k];
                   16883:            }else{ /* mobilav */ 
                   16884:              for(i=1; i<=nlstate;i++)
                   16885:                prlim[i][i]=mobaverage[(int)age][i][k];
                   16886:            }
                   16887:          }
1.219     brouard  16888:          
1.227     brouard  16889:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   16890:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   16891:          /* printf(" age %4.0f ",age); */
                   16892:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   16893:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   16894:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   16895:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   16896:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   16897:            }
1.361     brouard  16898:            epj[nlstate+1] +=epj[j]; /* epp=sum_j epj = sum_j sum_i w_i e_ij */
1.227     brouard  16899:          }
                   16900:          /* printf(" age %4.0f \n",age); */
1.219     brouard  16901:          
1.361     brouard  16902:          for(i=1, vepp=0.;i <=nlstate;i++)  /* Variance of total life expectancy e.. */
1.227     brouard  16903:            for(j=1;j <=nlstate;j++)
1.361     brouard  16904:              vepp += vareij[i][j][(int)age]; /* sum_i sum_j cov(e.i, e.j) = var(e..) */
1.227     brouard  16905:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
1.361     brouard  16906:          /* vareij[i][j] is the covariance  cov(e.i, e.j) and vareij[j][j] is the variance  of e.j  */
1.227     brouard  16907:          for(j=1;j <=nlstate;j++){
                   16908:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   16909:          }
1.360     brouard  16910:          /* And proportion of time spent in state j */
                   16911:          /* $$ 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  16912:           /* \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}) */
                   16913:          /* \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})*/
                   16914:          /*\mu_x = epj[j], \sigma^2_x = vareij[j][j][(int)age] and \mu_y=epj[nlstate+1], \sigma^2_y=vepp \sigmaxy= */
                   16915:          /* vareij[j][j][(int)age]/epj[nlstate+1]^2 + vepp/epj[nlstate+1]^4 */
1.360     brouard  16916:          for(j=1;j <=nlstate;j++){
                   16917:            /* 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  16918:            /* 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] )); */
                   16919:            
                   16920:            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) */
                   16921:              stdpercent += vareij[i][j][(int)age];
                   16922:            }
                   16923:            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]);
                   16924:            /* 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 */
                   16925:            /* 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] )); */
                   16926:            fprintf(ficrest," %7.3f (%7.3f)", epj[j]/epj[nlstate+1], sqrt(stdpercent));
1.360     brouard  16927:          }
1.227     brouard  16928:          fprintf(ficrest,"\n");
                   16929:        }
1.208     brouard  16930:       } /* End vpopbased */
1.269     brouard  16931:       free_vector(epj,1,nlstate+1);
1.208     brouard  16932:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   16933:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  16934:       printf("done selection\n");fflush(stdout);
                   16935:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  16936:       
1.335     brouard  16937:     } /* End k selection or end covariate selection for nres */
1.227     brouard  16938: 
                   16939:     printf("done State-specific expectancies\n");fflush(stdout);
                   16940:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   16941: 
1.335     brouard  16942:     /* variance-covariance of forward period prevalence */
1.269     brouard  16943:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  16944: 
1.227     brouard  16945:     
1.290     brouard  16946:     free_vector(weight,firstobs,lastobs);
1.351     brouard  16947:     free_imatrix(Tvardk,0,NCOVMAX,1,2);
1.227     brouard  16948:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  16949:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   16950:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   16951:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   16952:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  16953:     free_ivector(tab,1,NCOVMAX);
                   16954:     fclose(ficresstdeij);
                   16955:     fclose(ficrescveij);
                   16956:     fclose(ficresvij);
                   16957:     fclose(ficrest);
                   16958:     fclose(ficpar);
                   16959:     
                   16960:     
1.126     brouard  16961:     /*---------- End : free ----------------*/
1.219     brouard  16962:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  16963:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   16964:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  16965:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   16966:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  16967:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  16968:   /* endfree:*/
1.359     brouard  16969:   if(mle!=-3) free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
1.227     brouard  16970:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   16971:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   16972:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.341     brouard  16973:   /* if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs); */
                   16974:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);
1.290     brouard  16975:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   16976:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   16977:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  16978:   free_matrix(matcov,1,npar,1,npar);
                   16979:   free_matrix(hess,1,npar,1,npar);
                   16980:   /*free_vector(delti,1,npar);*/
                   16981:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   16982:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  16983:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  16984:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   16985:   
                   16986:   free_ivector(ncodemax,1,NCOVMAX);
                   16987:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   16988:   free_ivector(Dummy,-1,NCOVMAX);
                   16989:   free_ivector(Fixed,-1,NCOVMAX);
1.349     brouard  16990:   free_ivector(DummyV,-1,NCOVMAX);
                   16991:   free_ivector(FixedV,-1,NCOVMAX);
1.227     brouard  16992:   free_ivector(Typevar,-1,NCOVMAX);
                   16993:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  16994:   free_ivector(TvarsQ,1,NCOVMAX);
                   16995:   free_ivector(TvarsQind,1,NCOVMAX);
                   16996:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  16997:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  16998:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  16999:   free_ivector(TvarFD,1,NCOVMAX);
                   17000:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  17001:   free_ivector(TvarF,1,NCOVMAX);
                   17002:   free_ivector(TvarFind,1,NCOVMAX);
                   17003:   free_ivector(TvarV,1,NCOVMAX);
                   17004:   free_ivector(TvarVind,1,NCOVMAX);
                   17005:   free_ivector(TvarA,1,NCOVMAX);
                   17006:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  17007:   free_ivector(TvarFQ,1,NCOVMAX);
                   17008:   free_ivector(TvarFQind,1,NCOVMAX);
                   17009:   free_ivector(TvarVD,1,NCOVMAX);
                   17010:   free_ivector(TvarVDind,1,NCOVMAX);
                   17011:   free_ivector(TvarVQ,1,NCOVMAX);
                   17012:   free_ivector(TvarVQind,1,NCOVMAX);
1.349     brouard  17013:   free_ivector(TvarAVVA,1,NCOVMAX);
                   17014:   free_ivector(TvarAVVAind,1,NCOVMAX);
                   17015:   free_ivector(TvarVVA,1,NCOVMAX);
                   17016:   free_ivector(TvarVVAind,1,NCOVMAX);
1.339     brouard  17017:   free_ivector(TvarVV,1,NCOVMAX);
                   17018:   free_ivector(TvarVVind,1,NCOVMAX);
                   17019:   
1.230     brouard  17020:   free_ivector(Tvarsel,1,NCOVMAX);
                   17021:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  17022:   free_ivector(Tposprod,1,NCOVMAX);
                   17023:   free_ivector(Tprod,1,NCOVMAX);
                   17024:   free_ivector(Tvaraff,1,NCOVMAX);
1.338     brouard  17025:   free_ivector(invalidvarcomb,0,ncovcombmax);
1.227     brouard  17026:   free_ivector(Tage,1,NCOVMAX);
                   17027:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  17028:   free_ivector(TmodelInvind,1,NCOVMAX);
                   17029:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  17030: 
1.359     brouard  17031:   /* free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /\* Could be elsewhere ?*\/ */
1.332     brouard  17032: 
1.227     brouard  17033:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   17034:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  17035:   fflush(fichtm);
                   17036:   fflush(ficgp);
                   17037:   
1.227     brouard  17038:   
1.126     brouard  17039:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  17040:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   17041:     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  17042:   }else{
                   17043:     printf("End of Imach\n");
                   17044:     fprintf(ficlog,"End of Imach\n");
                   17045:   }
                   17046:   printf("See log file on %s\n",filelog);
                   17047:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  17048:   /*(void) gettimeofday(&end_time,&tzp);*/
                   17049:   rend_time = time(NULL);  
                   17050:   end_time = *localtime(&rend_time);
                   17051:   /* tml = *localtime(&end_time.tm_sec); */
                   17052:   strcpy(strtend,asctime(&end_time));
1.126     brouard  17053:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   17054:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  17055:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  17056:   
1.157     brouard  17057:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   17058:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   17059:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  17060:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   17061: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   17062:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   17063:   fclose(fichtm);
                   17064:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   17065:   fclose(fichtmcov);
                   17066:   fclose(ficgp);
                   17067:   fclose(ficlog);
                   17068:   /*------ End -----------*/
1.227     brouard  17069:   
1.281     brouard  17070: 
                   17071: /* Executes gnuplot */
1.227     brouard  17072:   
                   17073:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  17074: #ifdef WIN32
1.227     brouard  17075:   if (_chdir(pathcd) != 0)
                   17076:     printf("Can't move to directory %s!\n",path);
                   17077:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  17078: #else
1.227     brouard  17079:     if(chdir(pathcd) != 0)
                   17080:       printf("Can't move to directory %s!\n", path);
                   17081:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  17082: #endif 
1.126     brouard  17083:     printf("Current directory %s!\n",pathcd);
                   17084:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   17085:   sprintf(plotcmd,"gnuplot");
1.157     brouard  17086: #ifdef _WIN32
1.126     brouard  17087:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   17088: #endif
                   17089:   if(!stat(plotcmd,&info)){
1.158     brouard  17090:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  17091:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  17092:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  17093:     }else
                   17094:       strcpy(pplotcmd,plotcmd);
1.157     brouard  17095: #ifdef __unix
1.126     brouard  17096:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   17097:     if(!stat(plotcmd,&info)){
1.158     brouard  17098:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  17099:     }else
                   17100:       strcpy(pplotcmd,plotcmd);
                   17101: #endif
                   17102:   }else
                   17103:     strcpy(pplotcmd,plotcmd);
                   17104:   
                   17105:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  17106:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  17107:   strcpy(pplotcmd,plotcmd);
1.227     brouard  17108:   
1.126     brouard  17109:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  17110:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  17111:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  17112:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  17113:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  17114:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  17115:       strcpy(plotcmd,pplotcmd);
                   17116:     }
1.126     brouard  17117:   }
1.158     brouard  17118:   printf(" Successful, please wait...");
1.126     brouard  17119:   while (z[0] != 'q') {
                   17120:     /* chdir(path); */
1.154     brouard  17121:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  17122:     scanf("%s",z);
                   17123: /*     if (z[0] == 'c') system("./imach"); */
                   17124:     if (z[0] == 'e') {
1.158     brouard  17125: #ifdef __APPLE__
1.152     brouard  17126:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  17127: #elif __linux
                   17128:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  17129: #else
1.152     brouard  17130:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  17131: #endif
                   17132:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   17133:       system(pplotcmd);
1.126     brouard  17134:     }
                   17135:     else if (z[0] == 'g') system(plotcmd);
                   17136:     else if (z[0] == 'q') exit(0);
                   17137:   }
1.227     brouard  17138: end:
1.126     brouard  17139:   while (z[0] != 'q') {
1.195     brouard  17140:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  17141:     scanf("%s",z);
                   17142:   }
1.283     brouard  17143:   printf("End\n");
1.282     brouard  17144:   exit(0);
1.126     brouard  17145: }

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