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

1.367   ! brouard     1: /* $Id: imach.c,v 1.366 2024/07/02 09:42:10 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.360     brouard     3:   $Log: imach.c,v $
1.367   ! brouard     4:   Revision 1.366  2024/07/02 09:42:10  brouard
        !             5:   Summary: trying clang on Linux
        !             6: 
1.366     brouard     7:   Revision 1.365  2024/06/28 13:53:38  brouard
                      8:   * imach.c (Module): fixing some bugs in gnuplot and quantitative variables, but not completely solved
                      9: 
1.365     brouard    10:   Revision 1.364  2024/06/28 12:27:05  brouard
                     11:   * imach.c (Module): fixing some bugs in gnuplot and quantitative variables, but not completely solved
                     12: 
1.364     brouard    13:   Revision 1.363  2024/06/28 09:31:55  brouard
                     14:   Summary: Adding log lines too
                     15: 
1.363     brouard    16:   Revision 1.362  2024/06/28 08:00:31  brouard
                     17:   Summary: 0.99s6
                     18: 
                     19:   * imach.c (Module): s6 errors with age*age (harmless).
                     20: 
1.362     brouard    21:   Revision 1.361  2024/05/12 20:29:32  brouard
                     22:   Summary: Version 0.99s5
                     23: 
                     24:   * src/imach.c Version 0.99s5 In fact, the covariance of total life
                     25:   expectancy e.. with a partial life expectancy e.j is high,
                     26:   therefore the complete matrix of variance covariance has to be
                     27:   included in the formula of the standard error of the proportion of
                     28:   total life expectancy spent in a specific state:
                     29:   var(X/Y)=mu_x^2/mu_y^2*(sigma_x^2/mu_x^2 -2
                     30:   sigma_xy/mu_x/mu_y+sigma^2/mu_y^2).  Also an error with mle=-3
                     31:   made the program core dump. It is fixed in this version.
                     32: 
1.361     brouard    33:   Revision 1.360  2024/04/30 10:59:22  brouard
                     34:   Summary: Version 0.99s4 and estimation of std of e.j/e..
                     35: 
1.360     brouard    36:   Revision 1.359  2024/04/24 21:21:17  brouard
                     37:   Summary: First IMaCh version using Brent Praxis software based on Buckhardt and Gegenfürtner C codes
                     38: 
1.359     brouard    39:   Revision 1.6  2024/04/24 21:10:29  brouard
                     40:   Summary: First IMaCh version using Brent Praxis software based on Buckhardt and Gegenfürtner C codes
1.358     brouard    41: 
1.359     brouard    42:   Revision 1.5  2023/10/09 09:10:01  brouard
                     43:   Summary: trying to reconsider
1.357     brouard    44: 
1.359     brouard    45:   Revision 1.4  2023/06/22 12:50:51  brouard
                     46:   Summary: stil on going
1.357     brouard    47: 
1.359     brouard    48:   Revision 1.3  2023/06/22 11:28:07  brouard
                     49:   *** empty log message ***
1.356     brouard    50: 
1.359     brouard    51:   Revision 1.2  2023/06/22 11:22:40  brouard
                     52:   Summary: with svd but not working yet
1.355     brouard    53: 
1.354     brouard    54:   Revision 1.353  2023/05/08 18:48:22  brouard
                     55:   *** empty log message ***
                     56: 
1.353     brouard    57:   Revision 1.352  2023/04/29 10:46:21  brouard
                     58:   *** empty log message ***
                     59: 
1.352     brouard    60:   Revision 1.351  2023/04/29 10:43:47  brouard
                     61:   Summary: 099r45
                     62: 
1.351     brouard    63:   Revision 1.350  2023/04/24 11:38:06  brouard
                     64:   *** empty log message ***
                     65: 
1.350     brouard    66:   Revision 1.349  2023/01/31 09:19:37  brouard
                     67:   Summary: Improvements in models with age*Vn*Vm
                     68: 
1.348     brouard    69:   Revision 1.347  2022/09/18 14:36:44  brouard
                     70:   Summary: version 0.99r42
                     71: 
1.347     brouard    72:   Revision 1.346  2022/09/16 13:52:36  brouard
                     73:   * src/imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     74: 
1.346     brouard    75:   Revision 1.345  2022/09/16 13:40:11  brouard
                     76:   Summary: Version 0.99r41
                     77: 
                     78:   * imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     79: 
1.345     brouard    80:   Revision 1.344  2022/09/14 19:33:30  brouard
                     81:   Summary: version 0.99r40
                     82: 
                     83:   * imach.c (Module): Fixing names of variables in T_ (thanks to Feinuo)
                     84: 
1.344     brouard    85:   Revision 1.343  2022/09/14 14:22:16  brouard
                     86:   Summary: version 0.99r39
                     87: 
                     88:   * imach.c (Module): Version 0.99r39 with colored dummy covariates
                     89:   (fixed or time varying), using new last columns of
                     90:   ILK_parameter.txt file.
                     91: 
1.343     brouard    92:   Revision 1.342  2022/09/11 19:54:09  brouard
                     93:   Summary: 0.99r38
                     94: 
                     95:   * imach.c (Module): Adding timevarying products of any kinds,
                     96:   should work before shifting cotvar from ncovcol+nqv columns in
                     97:   order to have a correspondance between the column of cotvar and
                     98:   the id of column.
                     99:   (Module): Some cleaning and adding covariates in ILK.txt
                    100: 
1.342     brouard   101:   Revision 1.341  2022/09/11 07:58:42  brouard
                    102:   Summary: Version 0.99r38
                    103: 
                    104:   After adding change in cotvar.
                    105: 
1.341     brouard   106:   Revision 1.340  2022/09/11 07:53:11  brouard
                    107:   Summary: Version imach 0.99r37
                    108: 
                    109:   * imach.c (Module): Adding timevarying products of any kinds,
                    110:   should work before shifting cotvar from ncovcol+nqv columns in
                    111:   order to have a correspondance between the column of cotvar and
                    112:   the id of column.
                    113: 
1.340     brouard   114:   Revision 1.339  2022/09/09 17:55:22  brouard
                    115:   Summary: version 0.99r37
                    116: 
                    117:   * imach.c (Module): Many improvements for fixing products of fixed
                    118:   timevarying as well as fixed * fixed, and test with quantitative
                    119:   covariate.
                    120: 
1.339     brouard   121:   Revision 1.338  2022/09/04 17:40:33  brouard
                    122:   Summary: 0.99r36
                    123: 
                    124:   * imach.c (Module): Now the easy runs i.e. without result or
                    125:   model=1+age only did not work. The defautl combination should be 1
                    126:   and not 0 because everything hasn't been tranformed yet.
                    127: 
1.338     brouard   128:   Revision 1.337  2022/09/02 14:26:02  brouard
                    129:   Summary: version 0.99r35
                    130: 
                    131:   * src/imach.c: Version 0.99r35 because it outputs same results with
                    132:   1+age+V1+V1*age for females and 1+age for females only
                    133:   (education=1 noweight)
                    134: 
1.337     brouard   135:   Revision 1.336  2022/08/31 09:52:36  brouard
                    136:   *** empty log message ***
                    137: 
1.336     brouard   138:   Revision 1.335  2022/08/31 08:23:16  brouard
                    139:   Summary: improvements...
                    140: 
1.335     brouard   141:   Revision 1.334  2022/08/25 09:08:41  brouard
                    142:   Summary: In progress for quantitative
                    143: 
1.334     brouard   144:   Revision 1.333  2022/08/21 09:10:30  brouard
                    145:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                    146:   reassigning covariates: my first idea was that people will always
                    147:   use the first covariate V1 into the model but in fact they are
                    148:   producing data with many covariates and can use an equation model
                    149:   with some of the covariate; it means that in a model V2+V3 instead
                    150:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    151:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    152:   the equation model is restricted to two variables only (V2, V3)
                    153:   and the combination for V2 should be codtabm(k,1) instead of
                    154:   (codtabm(k,2), and the code should be
                    155:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    156:   made. All of these should be simplified once a day like we did in
                    157:   hpxij() for example by using precov[nres] which is computed in
                    158:   decoderesult for each nres of each resultline. Loop should be done
                    159:   on the equation model globally by distinguishing only product with
                    160:   age (which are changing with age) and no more on type of
                    161:   covariates, single dummies, single covariates.
                    162: 
1.333     brouard   163:   Revision 1.332  2022/08/21 09:06:25  brouard
                    164:   Summary: Version 0.99r33
                    165: 
                    166:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                    167:   reassigning covariates: my first idea was that people will always
                    168:   use the first covariate V1 into the model but in fact they are
                    169:   producing data with many covariates and can use an equation model
                    170:   with some of the covariate; it means that in a model V2+V3 instead
                    171:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    172:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    173:   the equation model is restricted to two variables only (V2, V3)
                    174:   and the combination for V2 should be codtabm(k,1) instead of
                    175:   (codtabm(k,2), and the code should be
                    176:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    177:   made. All of these should be simplified once a day like we did in
                    178:   hpxij() for example by using precov[nres] which is computed in
                    179:   decoderesult for each nres of each resultline. Loop should be done
                    180:   on the equation model globally by distinguishing only product with
                    181:   age (which are changing with age) and no more on type of
                    182:   covariates, single dummies, single covariates.
                    183: 
1.332     brouard   184:   Revision 1.331  2022/08/07 05:40:09  brouard
                    185:   *** empty log message ***
                    186: 
1.331     brouard   187:   Revision 1.330  2022/08/06 07:18:25  brouard
                    188:   Summary: last 0.99r31
                    189: 
                    190:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                    191: 
1.330     brouard   192:   Revision 1.329  2022/08/03 17:29:54  brouard
                    193:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                    194: 
1.329     brouard   195:   Revision 1.328  2022/07/27 17:40:48  brouard
                    196:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                    197: 
1.328     brouard   198:   Revision 1.327  2022/07/27 14:47:35  brouard
                    199:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                    200: 
1.327     brouard   201:   Revision 1.326  2022/07/26 17:33:55  brouard
                    202:   Summary: some test with nres=1
                    203: 
1.326     brouard   204:   Revision 1.325  2022/07/25 14:27:23  brouard
                    205:   Summary: r30
                    206: 
                    207:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                    208:   coredumped, revealed by Feiuno, thank you.
                    209: 
1.325     brouard   210:   Revision 1.324  2022/07/23 17:44:26  brouard
                    211:   *** empty log message ***
                    212: 
1.324     brouard   213:   Revision 1.323  2022/07/22 12:30:08  brouard
                    214:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    215: 
1.323     brouard   216:   Revision 1.322  2022/07/22 12:27:48  brouard
                    217:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    218: 
1.322     brouard   219:   Revision 1.321  2022/07/22 12:04:24  brouard
                    220:   Summary: r28
                    221: 
                    222:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    223: 
1.321     brouard   224:   Revision 1.320  2022/06/02 05:10:11  brouard
                    225:   *** empty log message ***
                    226: 
1.320     brouard   227:   Revision 1.319  2022/06/02 04:45:11  brouard
                    228:   * imach.c (Module): Adding the Wald tests from the log to the main
                    229:   htm for better display of the maximum likelihood estimators.
                    230: 
1.319     brouard   231:   Revision 1.318  2022/05/24 08:10:59  brouard
                    232:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                    233:   of confidencce intervals with product in the equation modelC
                    234: 
1.318     brouard   235:   Revision 1.317  2022/05/15 15:06:23  brouard
                    236:   * imach.c (Module):  Some minor improvements
                    237: 
1.317     brouard   238:   Revision 1.316  2022/05/11 15:11:31  brouard
                    239:   Summary: r27
                    240: 
1.316     brouard   241:   Revision 1.315  2022/05/11 15:06:32  brouard
                    242:   *** empty log message ***
                    243: 
1.315     brouard   244:   Revision 1.314  2022/04/13 17:43:09  brouard
                    245:   * imach.c (Module): Adding link to text data files
                    246: 
1.314     brouard   247:   Revision 1.313  2022/04/11 15:57:42  brouard
                    248:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    249: 
1.313     brouard   250:   Revision 1.312  2022/04/05 21:24:39  brouard
                    251:   *** empty log message ***
                    252: 
1.312     brouard   253:   Revision 1.311  2022/04/05 21:03:51  brouard
                    254:   Summary: Fixed quantitative covariates
                    255: 
                    256:          Fixed covariates (dummy or quantitative)
                    257:        with missing values have never been allowed but are ERRORS and
                    258:        program quits. Standard deviations of fixed covariates were
                    259:        wrongly computed. Mean and standard deviations of time varying
                    260:        covariates are still not computed.
                    261: 
1.311     brouard   262:   Revision 1.310  2022/03/17 08:45:53  brouard
                    263:   Summary: 99r25
                    264: 
                    265:   Improving detection of errors: result lines should be compatible with
                    266:   the model.
                    267: 
1.310     brouard   268:   Revision 1.309  2021/05/20 12:39:14  brouard
                    269:   Summary: Version 0.99r24
                    270: 
1.309     brouard   271:   Revision 1.308  2021/03/31 13:11:57  brouard
                    272:   Summary: Version 0.99r23
                    273: 
                    274: 
                    275:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    276: 
1.308     brouard   277:   Revision 1.307  2021/03/08 18:11:32  brouard
                    278:   Summary: 0.99r22 fixed bug on result:
                    279: 
1.307     brouard   280:   Revision 1.306  2021/02/20 15:44:02  brouard
                    281:   Summary: Version 0.99r21
                    282: 
                    283:   * imach.c (Module): Fix bug on quitting after result lines!
                    284:   (Module): Version 0.99r21
                    285: 
1.306     brouard   286:   Revision 1.305  2021/02/20 15:28:30  brouard
                    287:   * imach.c (Module): Fix bug on quitting after result lines!
                    288: 
1.305     brouard   289:   Revision 1.304  2021/02/12 11:34:20  brouard
                    290:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    291: 
1.304     brouard   292:   Revision 1.303  2021/02/11 19:50:15  brouard
                    293:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    294: 
1.303     brouard   295:   Revision 1.302  2020/02/22 21:00:05  brouard
                    296:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    297:   and life table from the data without any state)
                    298: 
1.302     brouard   299:   Revision 1.301  2019/06/04 13:51:20  brouard
                    300:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    301: 
1.301     brouard   302:   Revision 1.300  2019/05/22 19:09:45  brouard
                    303:   Summary: version 0.99r19 of May 2019
                    304: 
1.300     brouard   305:   Revision 1.299  2019/05/22 18:37:08  brouard
                    306:   Summary: Cleaned 0.99r19
                    307: 
1.299     brouard   308:   Revision 1.298  2019/05/22 18:19:56  brouard
                    309:   *** empty log message ***
                    310: 
1.298     brouard   311:   Revision 1.297  2019/05/22 17:56:10  brouard
                    312:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    313: 
1.297     brouard   314:   Revision 1.296  2019/05/20 13:03:18  brouard
                    315:   Summary: Projection syntax simplified
                    316: 
                    317: 
                    318:   We can now start projections, forward or backward, from the mean date
                    319:   of inteviews up to or down to a number of years of projection:
                    320:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    321:   or
                    322:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    323:   or
                    324:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    325:   or
                    326:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    327: 
1.296     brouard   328:   Revision 1.295  2019/05/18 09:52:50  brouard
                    329:   Summary: doxygen tex bug
                    330: 
1.295     brouard   331:   Revision 1.294  2019/05/16 14:54:33  brouard
                    332:   Summary: There was some wrong lines added
                    333: 
1.294     brouard   334:   Revision 1.293  2019/05/09 15:17:34  brouard
                    335:   *** empty log message ***
                    336: 
1.293     brouard   337:   Revision 1.292  2019/05/09 14:17:20  brouard
                    338:   Summary: Some updates
                    339: 
1.292     brouard   340:   Revision 1.291  2019/05/09 13:44:18  brouard
                    341:   Summary: Before ncovmax
                    342: 
1.291     brouard   343:   Revision 1.290  2019/05/09 13:39:37  brouard
                    344:   Summary: 0.99r18 unlimited number of individuals
                    345: 
                    346:   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.
                    347: 
1.290     brouard   348:   Revision 1.289  2018/12/13 09:16:26  brouard
                    349:   Summary: Bug for young ages (<-30) will be in r17
                    350: 
1.289     brouard   351:   Revision 1.288  2018/05/02 20:58:27  brouard
                    352:   Summary: Some bugs fixed
                    353: 
1.288     brouard   354:   Revision 1.287  2018/05/01 17:57:25  brouard
                    355:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    356: 
1.287     brouard   357:   Revision 1.286  2018/04/27 14:27:04  brouard
                    358:   Summary: some minor bugs
                    359: 
1.286     brouard   360:   Revision 1.285  2018/04/21 21:02:16  brouard
                    361:   Summary: Some bugs fixed, valgrind tested
                    362: 
1.285     brouard   363:   Revision 1.284  2018/04/20 05:22:13  brouard
                    364:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    365: 
1.284     brouard   366:   Revision 1.283  2018/04/19 14:49:16  brouard
                    367:   Summary: Some minor bugs fixed
                    368: 
1.283     brouard   369:   Revision 1.282  2018/02/27 22:50:02  brouard
                    370:   *** empty log message ***
                    371: 
1.282     brouard   372:   Revision 1.281  2018/02/27 19:25:23  brouard
                    373:   Summary: Adding second argument for quitting
                    374: 
1.281     brouard   375:   Revision 1.280  2018/02/21 07:58:13  brouard
                    376:   Summary: 0.99r15
                    377: 
                    378:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    379: 
1.280     brouard   380:   Revision 1.279  2017/07/20 13:35:01  brouard
                    381:   Summary: temporary working
                    382: 
1.279     brouard   383:   Revision 1.278  2017/07/19 14:09:02  brouard
                    384:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    385: 
1.278     brouard   386:   Revision 1.277  2017/07/17 08:53:49  brouard
                    387:   Summary: BOM files can be read now
                    388: 
1.277     brouard   389:   Revision 1.276  2017/06/30 15:48:31  brouard
                    390:   Summary: Graphs improvements
                    391: 
1.276     brouard   392:   Revision 1.275  2017/06/30 13:39:33  brouard
                    393:   Summary: Saito's color
                    394: 
1.275     brouard   395:   Revision 1.274  2017/06/29 09:47:08  brouard
                    396:   Summary: Version 0.99r14
                    397: 
1.274     brouard   398:   Revision 1.273  2017/06/27 11:06:02  brouard
                    399:   Summary: More documentation on projections
                    400: 
1.273     brouard   401:   Revision 1.272  2017/06/27 10:22:40  brouard
                    402:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    403: 
1.272     brouard   404:   Revision 1.271  2017/06/27 10:17:50  brouard
                    405:   Summary: Some bug with rint
                    406: 
1.271     brouard   407:   Revision 1.270  2017/05/24 05:45:29  brouard
                    408:   *** empty log message ***
                    409: 
1.270     brouard   410:   Revision 1.269  2017/05/23 08:39:25  brouard
                    411:   Summary: Code into subroutine, cleanings
                    412: 
1.269     brouard   413:   Revision 1.268  2017/05/18 20:09:32  brouard
                    414:   Summary: backprojection and confidence intervals of backprevalence
                    415: 
1.268     brouard   416:   Revision 1.267  2017/05/13 10:25:05  brouard
                    417:   Summary: temporary save for backprojection
                    418: 
1.267     brouard   419:   Revision 1.266  2017/05/13 07:26:12  brouard
                    420:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    421: 
1.266     brouard   422:   Revision 1.265  2017/04/26 16:22:11  brouard
                    423:   Summary: imach 0.99r13 Some bugs fixed
                    424: 
1.265     brouard   425:   Revision 1.264  2017/04/26 06:01:29  brouard
                    426:   Summary: Labels in graphs
                    427: 
1.264     brouard   428:   Revision 1.263  2017/04/24 15:23:15  brouard
                    429:   Summary: to save
                    430: 
1.263     brouard   431:   Revision 1.262  2017/04/18 16:48:12  brouard
                    432:   *** empty log message ***
                    433: 
1.262     brouard   434:   Revision 1.261  2017/04/05 10:14:09  brouard
                    435:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    436: 
1.261     brouard   437:   Revision 1.260  2017/04/04 17:46:59  brouard
                    438:   Summary: Gnuplot indexations fixed (humm)
                    439: 
1.260     brouard   440:   Revision 1.259  2017/04/04 13:01:16  brouard
                    441:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    442: 
1.259     brouard   443:   Revision 1.258  2017/04/03 10:17:47  brouard
                    444:   Summary: Version 0.99r12
                    445: 
                    446:   Some cleanings, conformed with updated documentation.
                    447: 
1.258     brouard   448:   Revision 1.257  2017/03/29 16:53:30  brouard
                    449:   Summary: Temp
                    450: 
1.257     brouard   451:   Revision 1.256  2017/03/27 05:50:23  brouard
                    452:   Summary: Temporary
                    453: 
1.256     brouard   454:   Revision 1.255  2017/03/08 16:02:28  brouard
                    455:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    456: 
1.255     brouard   457:   Revision 1.254  2017/03/08 07:13:00  brouard
                    458:   Summary: Fixing data parameter line
                    459: 
1.254     brouard   460:   Revision 1.253  2016/12/15 11:59:41  brouard
                    461:   Summary: 0.99 in progress
                    462: 
1.253     brouard   463:   Revision 1.252  2016/09/15 21:15:37  brouard
                    464:   *** empty log message ***
                    465: 
1.252     brouard   466:   Revision 1.251  2016/09/15 15:01:13  brouard
                    467:   Summary: not working
                    468: 
1.251     brouard   469:   Revision 1.250  2016/09/08 16:07:27  brouard
                    470:   Summary: continue
                    471: 
1.250     brouard   472:   Revision 1.249  2016/09/07 17:14:18  brouard
                    473:   Summary: Starting values from frequencies
                    474: 
1.249     brouard   475:   Revision 1.248  2016/09/07 14:10:18  brouard
                    476:   *** empty log message ***
                    477: 
1.248     brouard   478:   Revision 1.247  2016/09/02 11:11:21  brouard
                    479:   *** empty log message ***
                    480: 
1.247     brouard   481:   Revision 1.246  2016/09/02 08:49:22  brouard
                    482:   *** empty log message ***
                    483: 
1.246     brouard   484:   Revision 1.245  2016/09/02 07:25:01  brouard
                    485:   *** empty log message ***
                    486: 
1.245     brouard   487:   Revision 1.244  2016/09/02 07:17:34  brouard
                    488:   *** empty log message ***
                    489: 
1.244     brouard   490:   Revision 1.243  2016/09/02 06:45:35  brouard
                    491:   *** empty log message ***
                    492: 
1.243     brouard   493:   Revision 1.242  2016/08/30 15:01:20  brouard
                    494:   Summary: Fixing a lots
                    495: 
1.242     brouard   496:   Revision 1.241  2016/08/29 17:17:25  brouard
                    497:   Summary: gnuplot problem in Back projection to fix
                    498: 
1.241     brouard   499:   Revision 1.240  2016/08/29 07:53:18  brouard
                    500:   Summary: Better
                    501: 
1.240     brouard   502:   Revision 1.239  2016/08/26 15:51:03  brouard
                    503:   Summary: Improvement in Powell output in order to copy and paste
                    504: 
                    505:   Author:
                    506: 
1.239     brouard   507:   Revision 1.238  2016/08/26 14:23:35  brouard
                    508:   Summary: Starting tests of 0.99
                    509: 
1.238     brouard   510:   Revision 1.237  2016/08/26 09:20:19  brouard
                    511:   Summary: to valgrind
                    512: 
1.237     brouard   513:   Revision 1.236  2016/08/25 10:50:18  brouard
                    514:   *** empty log message ***
                    515: 
1.236     brouard   516:   Revision 1.235  2016/08/25 06:59:23  brouard
                    517:   *** empty log message ***
                    518: 
1.235     brouard   519:   Revision 1.234  2016/08/23 16:51:20  brouard
                    520:   *** empty log message ***
                    521: 
1.234     brouard   522:   Revision 1.233  2016/08/23 07:40:50  brouard
                    523:   Summary: not working
                    524: 
1.233     brouard   525:   Revision 1.232  2016/08/22 14:20:21  brouard
                    526:   Summary: not working
                    527: 
1.232     brouard   528:   Revision 1.231  2016/08/22 07:17:15  brouard
                    529:   Summary: not working
                    530: 
1.231     brouard   531:   Revision 1.230  2016/08/22 06:55:53  brouard
                    532:   Summary: Not working
                    533: 
1.230     brouard   534:   Revision 1.229  2016/07/23 09:45:53  brouard
                    535:   Summary: Completing for func too
                    536: 
1.229     brouard   537:   Revision 1.228  2016/07/22 17:45:30  brouard
                    538:   Summary: Fixing some arrays, still debugging
                    539: 
1.227     brouard   540:   Revision 1.226  2016/07/12 18:42:34  brouard
                    541:   Summary: temp
                    542: 
1.226     brouard   543:   Revision 1.225  2016/07/12 08:40:03  brouard
                    544:   Summary: saving but not running
                    545: 
1.225     brouard   546:   Revision 1.224  2016/07/01 13:16:01  brouard
                    547:   Summary: Fixes
                    548: 
1.224     brouard   549:   Revision 1.223  2016/02/19 09:23:35  brouard
                    550:   Summary: temporary
                    551: 
1.223     brouard   552:   Revision 1.222  2016/02/17 08:14:50  brouard
                    553:   Summary: Probably last 0.98 stable version 0.98r6
                    554: 
1.222     brouard   555:   Revision 1.221  2016/02/15 23:35:36  brouard
                    556:   Summary: minor bug
                    557: 
1.220     brouard   558:   Revision 1.219  2016/02/15 00:48:12  brouard
                    559:   *** empty log message ***
                    560: 
1.219     brouard   561:   Revision 1.218  2016/02/12 11:29:23  brouard
                    562:   Summary: 0.99 Back projections
                    563: 
1.218     brouard   564:   Revision 1.217  2015/12/23 17:18:31  brouard
                    565:   Summary: Experimental backcast
                    566: 
1.217     brouard   567:   Revision 1.216  2015/12/18 17:32:11  brouard
                    568:   Summary: 0.98r4 Warning and status=-2
                    569: 
                    570:   Version 0.98r4 is now:
                    571:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    572:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    573:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    574: 
1.216     brouard   575:   Revision 1.215  2015/12/16 08:52:24  brouard
                    576:   Summary: 0.98r4 working
                    577: 
1.215     brouard   578:   Revision 1.214  2015/12/16 06:57:54  brouard
                    579:   Summary: temporary not working
                    580: 
1.214     brouard   581:   Revision 1.213  2015/12/11 18:22:17  brouard
                    582:   Summary: 0.98r4
                    583: 
1.213     brouard   584:   Revision 1.212  2015/11/21 12:47:24  brouard
                    585:   Summary: minor typo
                    586: 
1.212     brouard   587:   Revision 1.211  2015/11/21 12:41:11  brouard
                    588:   Summary: 0.98r3 with some graph of projected cross-sectional
                    589: 
                    590:   Author: Nicolas Brouard
                    591: 
1.211     brouard   592:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   593:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   594:   Summary: Adding ftolpl parameter
                    595:   Author: N Brouard
                    596: 
                    597:   We had difficulties to get smoothed confidence intervals. It was due
                    598:   to the period prevalence which wasn't computed accurately. The inner
                    599:   parameter ftolpl is now an outer parameter of the .imach parameter
                    600:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    601:   computation are long.
                    602: 
1.209     brouard   603:   Revision 1.208  2015/11/17 14:31:57  brouard
                    604:   Summary: temporary
                    605: 
1.208     brouard   606:   Revision 1.207  2015/10/27 17:36:57  brouard
                    607:   *** empty log message ***
                    608: 
1.207     brouard   609:   Revision 1.206  2015/10/24 07:14:11  brouard
                    610:   *** empty log message ***
                    611: 
1.206     brouard   612:   Revision 1.205  2015/10/23 15:50:53  brouard
                    613:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    614: 
1.205     brouard   615:   Revision 1.204  2015/10/01 16:20:26  brouard
                    616:   Summary: Some new graphs of contribution to likelihood
                    617: 
1.204     brouard   618:   Revision 1.203  2015/09/30 17:45:14  brouard
                    619:   Summary: looking at better estimation of the hessian
                    620: 
                    621:   Also a better criteria for convergence to the period prevalence And
                    622:   therefore adding the number of years needed to converge. (The
                    623:   prevalence in any alive state shold sum to one
                    624: 
1.203     brouard   625:   Revision 1.202  2015/09/22 19:45:16  brouard
                    626:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    627: 
1.202     brouard   628:   Revision 1.201  2015/09/15 17:34:58  brouard
                    629:   Summary: 0.98r0
                    630: 
                    631:   - Some new graphs like suvival functions
                    632:   - Some bugs fixed like model=1+age+V2.
                    633: 
1.201     brouard   634:   Revision 1.200  2015/09/09 16:53:55  brouard
                    635:   Summary: Big bug thanks to Flavia
                    636: 
                    637:   Even model=1+age+V2. did not work anymore
                    638: 
1.200     brouard   639:   Revision 1.199  2015/09/07 14:09:23  brouard
                    640:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    641: 
1.199     brouard   642:   Revision 1.198  2015/09/03 07:14:39  brouard
                    643:   Summary: 0.98q5 Flavia
                    644: 
1.198     brouard   645:   Revision 1.197  2015/09/01 18:24:39  brouard
                    646:   *** empty log message ***
                    647: 
1.197     brouard   648:   Revision 1.196  2015/08/18 23:17:52  brouard
                    649:   Summary: 0.98q5
                    650: 
1.196     brouard   651:   Revision 1.195  2015/08/18 16:28:39  brouard
                    652:   Summary: Adding a hack for testing purpose
                    653: 
                    654:   After reading the title, ftol and model lines, if the comment line has
                    655:   a q, starting with #q, the answer at the end of the run is quit. It
                    656:   permits to run test files in batch with ctest. The former workaround was
                    657:   $ echo q | imach foo.imach
                    658: 
1.195     brouard   659:   Revision 1.194  2015/08/18 13:32:00  brouard
                    660:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    661: 
1.194     brouard   662:   Revision 1.193  2015/08/04 07:17:42  brouard
                    663:   Summary: 0.98q4
                    664: 
1.193     brouard   665:   Revision 1.192  2015/07/16 16:49:02  brouard
                    666:   Summary: Fixing some outputs
                    667: 
1.192     brouard   668:   Revision 1.191  2015/07/14 10:00:33  brouard
                    669:   Summary: Some fixes
                    670: 
1.191     brouard   671:   Revision 1.190  2015/05/05 08:51:13  brouard
                    672:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    673: 
                    674:   Fix 1+age+.
                    675: 
1.190     brouard   676:   Revision 1.189  2015/04/30 14:45:16  brouard
                    677:   Summary: 0.98q2
                    678: 
1.189     brouard   679:   Revision 1.188  2015/04/30 08:27:53  brouard
                    680:   *** empty log message ***
                    681: 
1.188     brouard   682:   Revision 1.187  2015/04/29 09:11:15  brouard
                    683:   *** empty log message ***
                    684: 
1.187     brouard   685:   Revision 1.186  2015/04/23 12:01:52  brouard
                    686:   Summary: V1*age is working now, version 0.98q1
                    687: 
                    688:   Some codes had been disabled in order to simplify and Vn*age was
                    689:   working in the optimization phase, ie, giving correct MLE parameters,
                    690:   but, as usual, outputs were not correct and program core dumped.
                    691: 
1.186     brouard   692:   Revision 1.185  2015/03/11 13:26:42  brouard
                    693:   Summary: Inclusion of compile and links command line for Intel Compiler
                    694: 
1.185     brouard   695:   Revision 1.184  2015/03/11 11:52:39  brouard
                    696:   Summary: Back from Windows 8. Intel Compiler
                    697: 
1.184     brouard   698:   Revision 1.183  2015/03/10 20:34:32  brouard
                    699:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    700: 
                    701:   We use directest instead of original Powell test; probably no
                    702:   incidence on the results, but better justifications;
                    703:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    704:   wrong results.
                    705: 
1.183     brouard   706:   Revision 1.182  2015/02/12 08:19:57  brouard
                    707:   Summary: Trying to keep directest which seems simpler and more general
                    708:   Author: Nicolas Brouard
                    709: 
1.182     brouard   710:   Revision 1.181  2015/02/11 23:22:24  brouard
                    711:   Summary: Comments on Powell added
                    712: 
                    713:   Author:
                    714: 
1.181     brouard   715:   Revision 1.180  2015/02/11 17:33:45  brouard
                    716:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    717: 
1.180     brouard   718:   Revision 1.179  2015/01/04 09:57:06  brouard
                    719:   Summary: back to OS/X
                    720: 
1.179     brouard   721:   Revision 1.178  2015/01/04 09:35:48  brouard
                    722:   *** empty log message ***
                    723: 
1.178     brouard   724:   Revision 1.177  2015/01/03 18:40:56  brouard
                    725:   Summary: Still testing ilc32 on OSX
                    726: 
1.177     brouard   727:   Revision 1.176  2015/01/03 16:45:04  brouard
                    728:   *** empty log message ***
                    729: 
1.176     brouard   730:   Revision 1.175  2015/01/03 16:33:42  brouard
                    731:   *** empty log message ***
                    732: 
1.175     brouard   733:   Revision 1.174  2015/01/03 16:15:49  brouard
                    734:   Summary: Still in cross-compilation
                    735: 
1.174     brouard   736:   Revision 1.173  2015/01/03 12:06:26  brouard
                    737:   Summary: trying to detect cross-compilation
                    738: 
1.173     brouard   739:   Revision 1.172  2014/12/27 12:07:47  brouard
                    740:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    741: 
1.172     brouard   742:   Revision 1.171  2014/12/23 13:26:59  brouard
                    743:   Summary: Back from Visual C
                    744: 
                    745:   Still problem with utsname.h on Windows
                    746: 
1.171     brouard   747:   Revision 1.170  2014/12/23 11:17:12  brouard
                    748:   Summary: Cleaning some \%% back to %%
                    749: 
                    750:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    751: 
1.170     brouard   752:   Revision 1.169  2014/12/22 23:08:31  brouard
                    753:   Summary: 0.98p
                    754: 
                    755:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    756: 
1.169     brouard   757:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   758:   Summary: update
1.169     brouard   759: 
1.168     brouard   760:   Revision 1.167  2014/12/22 13:50:56  brouard
                    761:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    762: 
                    763:   Testing on Linux 64
                    764: 
1.167     brouard   765:   Revision 1.166  2014/12/22 11:40:47  brouard
                    766:   *** empty log message ***
                    767: 
1.166     brouard   768:   Revision 1.165  2014/12/16 11:20:36  brouard
                    769:   Summary: After compiling on Visual C
                    770: 
                    771:   * imach.c (Module): Merging 1.61 to 1.162
                    772: 
1.165     brouard   773:   Revision 1.164  2014/12/16 10:52:11  brouard
                    774:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    775: 
                    776:   * imach.c (Module): Merging 1.61 to 1.162
                    777: 
1.164     brouard   778:   Revision 1.163  2014/12/16 10:30:11  brouard
                    779:   * imach.c (Module): Merging 1.61 to 1.162
                    780: 
1.163     brouard   781:   Revision 1.162  2014/09/25 11:43:39  brouard
                    782:   Summary: temporary backup 0.99!
                    783: 
1.162     brouard   784:   Revision 1.1  2014/09/16 11:06:58  brouard
                    785:   Summary: With some code (wrong) for nlopt
                    786: 
                    787:   Author:
                    788: 
                    789:   Revision 1.161  2014/09/15 20:41:41  brouard
                    790:   Summary: Problem with macro SQR on Intel compiler
                    791: 
1.161     brouard   792:   Revision 1.160  2014/09/02 09:24:05  brouard
                    793:   *** empty log message ***
                    794: 
1.160     brouard   795:   Revision 1.159  2014/09/01 10:34:10  brouard
                    796:   Summary: WIN32
                    797:   Author: Brouard
                    798: 
1.159     brouard   799:   Revision 1.158  2014/08/27 17:11:51  brouard
                    800:   *** empty log message ***
                    801: 
1.158     brouard   802:   Revision 1.157  2014/08/27 16:26:55  brouard
                    803:   Summary: Preparing windows Visual studio version
                    804:   Author: Brouard
                    805: 
                    806:   In order to compile on Visual studio, time.h is now correct and time_t
                    807:   and tm struct should be used. difftime should be used but sometimes I
                    808:   just make the differences in raw time format (time(&now).
                    809:   Trying to suppress #ifdef LINUX
                    810:   Add xdg-open for __linux in order to open default browser.
                    811: 
1.157     brouard   812:   Revision 1.156  2014/08/25 20:10:10  brouard
                    813:   *** empty log message ***
                    814: 
1.156     brouard   815:   Revision 1.155  2014/08/25 18:32:34  brouard
                    816:   Summary: New compile, minor changes
                    817:   Author: Brouard
                    818: 
1.155     brouard   819:   Revision 1.154  2014/06/20 17:32:08  brouard
                    820:   Summary: Outputs now all graphs of convergence to period prevalence
                    821: 
1.154     brouard   822:   Revision 1.153  2014/06/20 16:45:46  brouard
                    823:   Summary: If 3 live state, convergence to period prevalence on same graph
                    824:   Author: Brouard
                    825: 
1.153     brouard   826:   Revision 1.152  2014/06/18 17:54:09  brouard
                    827:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    828: 
1.152     brouard   829:   Revision 1.151  2014/06/18 16:43:30  brouard
                    830:   *** empty log message ***
                    831: 
1.151     brouard   832:   Revision 1.150  2014/06/18 16:42:35  brouard
                    833:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    834:   Author: brouard
                    835: 
1.150     brouard   836:   Revision 1.149  2014/06/18 15:51:14  brouard
                    837:   Summary: Some fixes in parameter files errors
                    838:   Author: Nicolas Brouard
                    839: 
1.149     brouard   840:   Revision 1.148  2014/06/17 17:38:48  brouard
                    841:   Summary: Nothing new
                    842:   Author: Brouard
                    843: 
                    844:   Just a new packaging for OS/X version 0.98nS
                    845: 
1.148     brouard   846:   Revision 1.147  2014/06/16 10:33:11  brouard
                    847:   *** empty log message ***
                    848: 
1.147     brouard   849:   Revision 1.146  2014/06/16 10:20:28  brouard
                    850:   Summary: Merge
                    851:   Author: Brouard
                    852: 
                    853:   Merge, before building revised version.
                    854: 
1.146     brouard   855:   Revision 1.145  2014/06/10 21:23:15  brouard
                    856:   Summary: Debugging with valgrind
                    857:   Author: Nicolas Brouard
                    858: 
                    859:   Lot of changes in order to output the results with some covariates
                    860:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    861:   improve the code.
                    862:   No more memory valgrind error but a lot has to be done in order to
                    863:   continue the work of splitting the code into subroutines.
                    864:   Also, decodemodel has been improved. Tricode is still not
                    865:   optimal. nbcode should be improved. Documentation has been added in
                    866:   the source code.
                    867: 
1.144     brouard   868:   Revision 1.143  2014/01/26 09:45:38  brouard
                    869:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    870: 
                    871:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    872:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    873: 
1.143     brouard   874:   Revision 1.142  2014/01/26 03:57:36  brouard
                    875:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    876: 
                    877:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    878: 
1.142     brouard   879:   Revision 1.141  2014/01/26 02:42:01  brouard
                    880:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    881: 
1.141     brouard   882:   Revision 1.140  2011/09/02 10:37:54  brouard
                    883:   Summary: times.h is ok with mingw32 now.
                    884: 
1.140     brouard   885:   Revision 1.139  2010/06/14 07:50:17  brouard
                    886:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    887:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    888: 
1.139     brouard   889:   Revision 1.138  2010/04/30 18:19:40  brouard
                    890:   *** empty log message ***
                    891: 
1.138     brouard   892:   Revision 1.137  2010/04/29 18:11:38  brouard
                    893:   (Module): Checking covariates for more complex models
                    894:   than V1+V2. A lot of change to be done. Unstable.
                    895: 
1.137     brouard   896:   Revision 1.136  2010/04/26 20:30:53  brouard
                    897:   (Module): merging some libgsl code. Fixing computation
                    898:   of likelione (using inter/intrapolation if mle = 0) in order to
                    899:   get same likelihood as if mle=1.
                    900:   Some cleaning of code and comments added.
                    901: 
1.136     brouard   902:   Revision 1.135  2009/10/29 15:33:14  brouard
                    903:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    904: 
1.135     brouard   905:   Revision 1.134  2009/10/29 13:18:53  brouard
                    906:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    907: 
1.134     brouard   908:   Revision 1.133  2009/07/06 10:21:25  brouard
                    909:   just nforces
                    910: 
1.133     brouard   911:   Revision 1.132  2009/07/06 08:22:05  brouard
                    912:   Many tings
                    913: 
1.132     brouard   914:   Revision 1.131  2009/06/20 16:22:47  brouard
                    915:   Some dimensions resccaled
                    916: 
1.131     brouard   917:   Revision 1.130  2009/05/26 06:44:34  brouard
                    918:   (Module): Max Covariate is now set to 20 instead of 8. A
                    919:   lot of cleaning with variables initialized to 0. Trying to make
                    920:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    921: 
1.130     brouard   922:   Revision 1.129  2007/08/31 13:49:27  lievre
                    923:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    924: 
1.129     lievre    925:   Revision 1.128  2006/06/30 13:02:05  brouard
                    926:   (Module): Clarifications on computing e.j
                    927: 
1.128     brouard   928:   Revision 1.127  2006/04/28 18:11:50  brouard
                    929:   (Module): Yes the sum of survivors was wrong since
                    930:   imach-114 because nhstepm was no more computed in the age
                    931:   loop. Now we define nhstepma in the age loop.
                    932:   (Module): In order to speed up (in case of numerous covariates) we
                    933:   compute health expectancies (without variances) in a first step
                    934:   and then all the health expectancies with variances or standard
                    935:   deviation (needs data from the Hessian matrices) which slows the
                    936:   computation.
                    937:   In the future we should be able to stop the program is only health
                    938:   expectancies and graph are needed without standard deviations.
                    939: 
1.127     brouard   940:   Revision 1.126  2006/04/28 17:23:28  brouard
                    941:   (Module): Yes the sum of survivors was wrong since
                    942:   imach-114 because nhstepm was no more computed in the age
                    943:   loop. Now we define nhstepma in the age loop.
                    944:   Version 0.98h
                    945: 
1.126     brouard   946:   Revision 1.125  2006/04/04 15:20:31  lievre
                    947:   Errors in calculation of health expectancies. Age was not initialized.
                    948:   Forecasting file added.
                    949: 
                    950:   Revision 1.124  2006/03/22 17:13:53  lievre
                    951:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    952:   The log-likelihood is printed in the log file
                    953: 
                    954:   Revision 1.123  2006/03/20 10:52:43  brouard
                    955:   * imach.c (Module): <title> changed, corresponds to .htm file
                    956:   name. <head> headers where missing.
                    957: 
                    958:   * imach.c (Module): Weights can have a decimal point as for
                    959:   English (a comma might work with a correct LC_NUMERIC environment,
                    960:   otherwise the weight is truncated).
                    961:   Modification of warning when the covariates values are not 0 or
                    962:   1.
                    963:   Version 0.98g
                    964: 
                    965:   Revision 1.122  2006/03/20 09:45:41  brouard
                    966:   (Module): Weights can have a decimal point as for
                    967:   English (a comma might work with a correct LC_NUMERIC environment,
                    968:   otherwise the weight is truncated).
                    969:   Modification of warning when the covariates values are not 0 or
                    970:   1.
                    971:   Version 0.98g
                    972: 
                    973:   Revision 1.121  2006/03/16 17:45:01  lievre
                    974:   * imach.c (Module): Comments concerning covariates added
                    975: 
                    976:   * imach.c (Module): refinements in the computation of lli if
                    977:   status=-2 in order to have more reliable computation if stepm is
                    978:   not 1 month. Version 0.98f
                    979: 
                    980:   Revision 1.120  2006/03/16 15:10:38  lievre
                    981:   (Module): refinements in the computation of lli if
                    982:   status=-2 in order to have more reliable computation if stepm is
                    983:   not 1 month. Version 0.98f
                    984: 
                    985:   Revision 1.119  2006/03/15 17:42:26  brouard
                    986:   (Module): Bug if status = -2, the loglikelihood was
                    987:   computed as likelihood omitting the logarithm. Version O.98e
                    988: 
                    989:   Revision 1.118  2006/03/14 18:20:07  brouard
                    990:   (Module): varevsij Comments added explaining the second
                    991:   table of variances if popbased=1 .
                    992:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    993:   (Module): Function pstamp added
                    994:   (Module): Version 0.98d
                    995: 
                    996:   Revision 1.117  2006/03/14 17:16:22  brouard
                    997:   (Module): varevsij Comments added explaining the second
                    998:   table of variances if popbased=1 .
                    999:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                   1000:   (Module): Function pstamp added
                   1001:   (Module): Version 0.98d
                   1002: 
                   1003:   Revision 1.116  2006/03/06 10:29:27  brouard
                   1004:   (Module): Variance-covariance wrong links and
                   1005:   varian-covariance of ej. is needed (Saito).
                   1006: 
                   1007:   Revision 1.115  2006/02/27 12:17:45  brouard
                   1008:   (Module): One freematrix added in mlikeli! 0.98c
                   1009: 
                   1010:   Revision 1.114  2006/02/26 12:57:58  brouard
                   1011:   (Module): Some improvements in processing parameter
                   1012:   filename with strsep.
                   1013: 
                   1014:   Revision 1.113  2006/02/24 14:20:24  brouard
                   1015:   (Module): Memory leaks checks with valgrind and:
                   1016:   datafile was not closed, some imatrix were not freed and on matrix
                   1017:   allocation too.
                   1018: 
                   1019:   Revision 1.112  2006/01/30 09:55:26  brouard
                   1020:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                   1021: 
                   1022:   Revision 1.111  2006/01/25 20:38:18  brouard
                   1023:   (Module): Lots of cleaning and bugs added (Gompertz)
                   1024:   (Module): Comments can be added in data file. Missing date values
                   1025:   can be a simple dot '.'.
                   1026: 
                   1027:   Revision 1.110  2006/01/25 00:51:50  brouard
                   1028:   (Module): Lots of cleaning and bugs added (Gompertz)
                   1029: 
                   1030:   Revision 1.109  2006/01/24 19:37:15  brouard
                   1031:   (Module): Comments (lines starting with a #) are allowed in data.
                   1032: 
                   1033:   Revision 1.108  2006/01/19 18:05:42  lievre
                   1034:   Gnuplot problem appeared...
                   1035:   To be fixed
                   1036: 
                   1037:   Revision 1.107  2006/01/19 16:20:37  brouard
                   1038:   Test existence of gnuplot in imach path
                   1039: 
                   1040:   Revision 1.106  2006/01/19 13:24:36  brouard
                   1041:   Some cleaning and links added in html output
                   1042: 
                   1043:   Revision 1.105  2006/01/05 20:23:19  lievre
                   1044:   *** empty log message ***
                   1045: 
                   1046:   Revision 1.104  2005/09/30 16:11:43  lievre
                   1047:   (Module): sump fixed, loop imx fixed, and simplifications.
                   1048:   (Module): If the status is missing at the last wave but we know
                   1049:   that the person is alive, then we can code his/her status as -2
                   1050:   (instead of missing=-1 in earlier versions) and his/her
                   1051:   contributions to the likelihood is 1 - Prob of dying from last
                   1052:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                   1053:   the healthy state at last known wave). Version is 0.98
                   1054: 
                   1055:   Revision 1.103  2005/09/30 15:54:49  lievre
                   1056:   (Module): sump fixed, loop imx fixed, and simplifications.
                   1057: 
                   1058:   Revision 1.102  2004/09/15 17:31:30  brouard
                   1059:   Add the possibility to read data file including tab characters.
                   1060: 
                   1061:   Revision 1.101  2004/09/15 10:38:38  brouard
                   1062:   Fix on curr_time
                   1063: 
                   1064:   Revision 1.100  2004/07/12 18:29:06  brouard
                   1065:   Add version for Mac OS X. Just define UNIX in Makefile
                   1066: 
                   1067:   Revision 1.99  2004/06/05 08:57:40  brouard
                   1068:   *** empty log message ***
                   1069: 
                   1070:   Revision 1.98  2004/05/16 15:05:56  brouard
                   1071:   New version 0.97 . First attempt to estimate force of mortality
                   1072:   directly from the data i.e. without the need of knowing the health
                   1073:   state at each age, but using a Gompertz model: log u =a + b*age .
                   1074:   This is the basic analysis of mortality and should be done before any
                   1075:   other analysis, in order to test if the mortality estimated from the
                   1076:   cross-longitudinal survey is different from the mortality estimated
                   1077:   from other sources like vital statistic data.
                   1078: 
                   1079:   The same imach parameter file can be used but the option for mle should be -3.
                   1080: 
1.324     brouard  1081:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard  1082:   former routines in order to include the new code within the former code.
                   1083: 
                   1084:   The output is very simple: only an estimate of the intercept and of
                   1085:   the slope with 95% confident intervals.
                   1086: 
                   1087:   Current limitations:
                   1088:   A) Even if you enter covariates, i.e. with the
                   1089:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                   1090:   B) There is no computation of Life Expectancy nor Life Table.
                   1091: 
                   1092:   Revision 1.97  2004/02/20 13:25:42  lievre
                   1093:   Version 0.96d. Population forecasting command line is (temporarily)
                   1094:   suppressed.
                   1095: 
                   1096:   Revision 1.96  2003/07/15 15:38:55  brouard
                   1097:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                   1098:   rewritten within the same printf. Workaround: many printfs.
                   1099: 
                   1100:   Revision 1.95  2003/07/08 07:54:34  brouard
                   1101:   * imach.c (Repository):
                   1102:   (Repository): Using imachwizard code to output a more meaningful covariance
                   1103:   matrix (cov(a12,c31) instead of numbers.
                   1104: 
                   1105:   Revision 1.94  2003/06/27 13:00:02  brouard
                   1106:   Just cleaning
                   1107: 
                   1108:   Revision 1.93  2003/06/25 16:33:55  brouard
                   1109:   (Module): On windows (cygwin) function asctime_r doesn't
                   1110:   exist so I changed back to asctime which exists.
                   1111:   (Module): Version 0.96b
                   1112: 
                   1113:   Revision 1.92  2003/06/25 16:30:45  brouard
                   1114:   (Module): On windows (cygwin) function asctime_r doesn't
                   1115:   exist so I changed back to asctime which exists.
                   1116: 
                   1117:   Revision 1.91  2003/06/25 15:30:29  brouard
                   1118:   * imach.c (Repository): Duplicated warning errors corrected.
                   1119:   (Repository): Elapsed time after each iteration is now output. It
                   1120:   helps to forecast when convergence will be reached. Elapsed time
                   1121:   is stamped in powell.  We created a new html file for the graphs
                   1122:   concerning matrix of covariance. It has extension -cov.htm.
                   1123: 
                   1124:   Revision 1.90  2003/06/24 12:34:15  brouard
                   1125:   (Module): Some bugs corrected for windows. Also, when
                   1126:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1127:   of the covariance matrix to be input.
                   1128: 
                   1129:   Revision 1.89  2003/06/24 12:30:52  brouard
                   1130:   (Module): Some bugs corrected for windows. Also, when
                   1131:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1132:   of the covariance matrix to be input.
                   1133: 
                   1134:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1135:   * 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.
                   1136: 
                   1137:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1138:   Version 0.96
                   1139: 
                   1140:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1141:   (Module): Change position of html and gnuplot routines and added
                   1142:   routine fileappend.
                   1143: 
                   1144:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1145:   * imach.c (Repository): Check when date of death was earlier that
                   1146:   current date of interview. It may happen when the death was just
                   1147:   prior to the death. In this case, dh was negative and likelihood
                   1148:   was wrong (infinity). We still send an "Error" but patch by
                   1149:   assuming that the date of death was just one stepm after the
                   1150:   interview.
                   1151:   (Repository): Because some people have very long ID (first column)
                   1152:   we changed int to long in num[] and we added a new lvector for
                   1153:   memory allocation. But we also truncated to 8 characters (left
                   1154:   truncation)
                   1155:   (Repository): No more line truncation errors.
                   1156: 
                   1157:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1158:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1159:   place. It differs from routine "prevalence" which may be called
                   1160:   many times. Probs is memory consuming and must be used with
                   1161:   parcimony.
                   1162:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1163: 
                   1164:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1165:   *** empty log message ***
                   1166: 
                   1167:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1168:   Add log in  imach.c and  fullversion number is now printed.
                   1169: 
                   1170: */
                   1171: /*
                   1172:    Interpolated Markov Chain
                   1173: 
                   1174:   Short summary of the programme:
                   1175:   
1.227     brouard  1176:   This program computes Healthy Life Expectancies or State-specific
                   1177:   (if states aren't health statuses) Expectancies from
                   1178:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1179: 
                   1180:   -1- a first survey ("cross") where individuals from different ages
                   1181:   are interviewed on their health status or degree of disability (in
                   1182:   the case of a health survey which is our main interest)
                   1183: 
                   1184:   -2- at least a second wave of interviews ("longitudinal") which
                   1185:   measure each change (if any) in individual health status.  Health
                   1186:   expectancies are computed from the time spent in each health state
                   1187:   according to a model. More health states you consider, more time is
                   1188:   necessary to reach the Maximum Likelihood of the parameters involved
                   1189:   in the model.  The simplest model is the multinomial logistic model
                   1190:   where pij is the probability to be observed in state j at the second
                   1191:   wave conditional to be observed in state i at the first
                   1192:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1193:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1194:   have a more complex model than "constant and age", you should modify
                   1195:   the program where the markup *Covariates have to be included here
                   1196:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1197:   convergence.
                   1198: 
                   1199:   The advantage of this computer programme, compared to a simple
                   1200:   multinomial logistic model, is clear when the delay between waves is not
                   1201:   identical for each individual. Also, if a individual missed an
                   1202:   intermediate interview, the information is lost, but taken into
                   1203:   account using an interpolation or extrapolation.  
                   1204: 
                   1205:   hPijx is the probability to be observed in state i at age x+h
                   1206:   conditional to the observed state i at age x. The delay 'h' can be
                   1207:   split into an exact number (nh*stepm) of unobserved intermediate
                   1208:   states. This elementary transition (by month, quarter,
                   1209:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1210:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1211:   and the contribution of each individual to the likelihood is simply
                   1212:   hPijx.
                   1213: 
                   1214:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1215:   of the life expectancies. It also computes the period (stable) prevalence.
                   1216: 
                   1217: Back prevalence and projections:
1.227     brouard  1218: 
                   1219:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1220:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1221:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1222:    mobilavproj)
                   1223: 
                   1224:     Computes the back prevalence limit for any combination of
                   1225:     covariate values k at any age between ageminpar and agemaxpar and
                   1226:     returns it in **bprlim. In the loops,
                   1227: 
                   1228:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1229:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1230: 
                   1231:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1232:    Computes for any combination of covariates k and any age between bage and fage 
                   1233:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1234:                        oldm=oldms;savm=savms;
1.227     brouard  1235: 
1.267     brouard  1236:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1237:      Computes the transition matrix starting at age 'age' over
                   1238:      'nhstepm*hstepm*stepm' months (i.e. until
                   1239:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1240:      nhstepm*hstepm matrices. 
                   1241: 
                   1242:      Returns p3mat[i][j][h] after calling
                   1243:      p3mat[i][j][h]=matprod2(newm,
                   1244:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1245:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1246:      oldm);
1.226     brouard  1247: 
                   1248: Important routines
                   1249: 
                   1250: - func (or funcone), computes logit (pij) distinguishing
                   1251:   o fixed variables (single or product dummies or quantitative);
                   1252:   o varying variables by:
                   1253:    (1) wave (single, product dummies, quantitative), 
                   1254:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1255:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1256:        % varying dummy (not done) or quantitative (not done);
                   1257: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1258:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1259: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.364     brouard  1260:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, eliminating 1 1 if
1.226     brouard  1261:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1262: 
1.226     brouard  1263: 
                   1264:   
1.324     brouard  1265:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1266:            Institut national d'études démographiques, Paris.
1.126     brouard  1267:   This software have been partly granted by Euro-REVES, a concerted action
                   1268:   from the European Union.
                   1269:   It is copyrighted identically to a GNU software product, ie programme and
                   1270:   software can be distributed freely for non commercial use. Latest version
                   1271:   can be accessed at http://euroreves.ined.fr/imach .
                   1272: 
                   1273:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1274:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1275:   
                   1276:   **********************************************************************/
                   1277: /*
                   1278:   main
                   1279:   read parameterfile
                   1280:   read datafile
                   1281:   concatwav
                   1282:   freqsummary
                   1283:   if (mle >= 1)
                   1284:     mlikeli
                   1285:   print results files
                   1286:   if mle==1 
                   1287:      computes hessian
                   1288:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1289:       begin-prev-date,...
                   1290:   open gnuplot file
                   1291:   open html file
1.145     brouard  1292:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1293:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1294:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1295:     freexexit2 possible for memory heap.
                   1296: 
                   1297:   h Pij x                         | pij_nom  ficrestpij
                   1298:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1299:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1300:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1301: 
                   1302:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1303:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1304:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1305:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1306:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1307: 
1.126     brouard  1308:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1309:   health expectancies
                   1310:   Variance-covariance of DFLE
                   1311:   prevalence()
                   1312:    movingaverage()
                   1313:   varevsij() 
                   1314:   if popbased==1 varevsij(,popbased)
                   1315:   total life expectancies
                   1316:   Variance of period (stable) prevalence
                   1317:  end
                   1318: */
                   1319: 
1.187     brouard  1320: /* #define DEBUG */
                   1321: /* #define DEBUGBRENT */
1.203     brouard  1322: /* #define DEBUGLINMIN */
                   1323: /* #define DEBUGHESS */
                   1324: #define DEBUGHESSIJ
1.224     brouard  1325: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1326: #define POWELL /* Instead of NLOPT */
1.224     brouard  1327: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1328: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1329: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1330: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.359     brouard  1331: /* #define POWELLORIGINCONJUGATE  /\* Don't use conjugate but biggest decrease if valuable *\/ */
                   1332: /* #define NOTMINFIT */
1.126     brouard  1333: 
                   1334: #include <math.h>
                   1335: #include <stdio.h>
                   1336: #include <stdlib.h>
                   1337: #include <string.h>
1.226     brouard  1338: #include <ctype.h>
1.159     brouard  1339: 
                   1340: #ifdef _WIN32
                   1341: #include <io.h>
1.172     brouard  1342: #include <windows.h>
                   1343: #include <tchar.h>
1.159     brouard  1344: #else
1.126     brouard  1345: #include <unistd.h>
1.159     brouard  1346: #endif
1.126     brouard  1347: 
                   1348: #include <limits.h>
                   1349: #include <sys/types.h>
1.171     brouard  1350: 
                   1351: #if defined(__GNUC__)
                   1352: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1353: #endif
                   1354: 
1.126     brouard  1355: #include <sys/stat.h>
                   1356: #include <errno.h>
1.159     brouard  1357: /* extern int errno; */
1.126     brouard  1358: 
1.157     brouard  1359: /* #ifdef LINUX */
                   1360: /* #include <time.h> */
                   1361: /* #include "timeval.h" */
                   1362: /* #else */
                   1363: /* #include <sys/time.h> */
                   1364: /* #endif */
                   1365: 
1.126     brouard  1366: #include <time.h>
                   1367: 
1.136     brouard  1368: #ifdef GSL
                   1369: #include <gsl/gsl_errno.h>
                   1370: #include <gsl/gsl_multimin.h>
                   1371: #endif
                   1372: 
1.167     brouard  1373: 
1.162     brouard  1374: #ifdef NLOPT
                   1375: #include <nlopt.h>
                   1376: typedef struct {
                   1377:   double (* function)(double [] );
                   1378: } myfunc_data ;
                   1379: #endif
                   1380: 
1.126     brouard  1381: /* #include <libintl.h> */
                   1382: /* #define _(String) gettext (String) */
                   1383: 
1.349     brouard  1384: #define MAXLINE 16384 /* Was 256 and 1024 and 2048. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1385: 
                   1386: #define GNUPLOTPROGRAM "gnuplot"
1.343     brouard  1387: #define GNUPLOTVERSION 5.1
                   1388: double gnuplotversion=GNUPLOTVERSION;
1.126     brouard  1389: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1390: #define FILENAMELENGTH 256
1.126     brouard  1391: 
                   1392: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1393: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1394: 
1.349     brouard  1395: #define MAXPARM 216 /**< Maximum number of parameters for the optimization was 128 */
1.144     brouard  1396: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1397: 
                   1398: #define NINTERVMAX 8
1.144     brouard  1399: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1400: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1401: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1402: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1403: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1404: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1405: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1406: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1407: /* #define AGESUP 130 */
1.288     brouard  1408: /* #define AGESUP 150 */
                   1409: #define AGESUP 200
1.268     brouard  1410: #define AGEINF 0
1.218     brouard  1411: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1412: #define AGEBASE 40
1.194     brouard  1413: #define AGEOVERFLOW 1.e20
1.164     brouard  1414: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1415: #ifdef _WIN32
                   1416: #define DIRSEPARATOR '\\'
                   1417: #define CHARSEPARATOR "\\"
                   1418: #define ODIRSEPARATOR '/'
                   1419: #else
1.126     brouard  1420: #define DIRSEPARATOR '/'
                   1421: #define CHARSEPARATOR "/"
                   1422: #define ODIRSEPARATOR '\\'
                   1423: #endif
                   1424: 
1.367   ! brouard  1425: /* $Id: imach.c,v 1.366 2024/07/02 09:42:10 brouard Exp $ */
1.126     brouard  1426: /* $State: Exp $ */
1.196     brouard  1427: #include "version.h"
                   1428: char version[]=__IMACH_VERSION__;
1.360     brouard  1429: 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.367   ! brouard  1430: char fullversion[]="$Revision: 1.366 $ $Date: 2024/07/02 09:42:10 $"; 
1.126     brouard  1431: char strstart[80];
                   1432: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1433: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.342     brouard  1434: int debugILK=0; /* debugILK is set by a #d in a comment line */
1.187     brouard  1435: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1436: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1437: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
1.335     brouard  1438: 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  1439: 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  1440: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1441: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1442: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
1.349     brouard  1443: int cptcovprodage=0; /**< Number of fixed covariates with age: V3*age or V2*V3*age 1 */
                   1444: int cptcovprodvage=0; /**< Number of varying covariates with age: V7*age or V7*V6*age */
                   1445: int cptcovdageprod=0; /**< Number of doubleproducts with age, since 0.99r44 only: age*Vn*Vm for gnuplot printing*/
1.145     brouard  1446: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335     brouard  1447: 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  1448: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1449: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.339     brouard  1450: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
1.349     brouard  1451: 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 */
                   1452: 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 */
                   1453: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (single or product, dummy or quantitative) in the model */
                   1454: 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  1455: int nsd=0; /**< Total number of single dummy variables (output) */
                   1456: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1457: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1458: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1459: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1460: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1461: int cptcov=0; /* Working variable */
1.334     brouard  1462: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1463: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1464: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1465: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1466: int nlstate=2; /* Number of live states */
                   1467: int ndeath=1; /* Number of dead states */
1.130     brouard  1468: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.339     brouard  1469: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
                   1470: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
1.126     brouard  1471: int popbased=0;
                   1472: 
                   1473: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1474: int maxwav=0; /* Maxim number of waves */
                   1475: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1476: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
1.359     brouard  1477: int gipmx = 0;
                   1478: double gsw = 0; /* Global variables on the number of contributions
1.126     brouard  1479:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1480: int mle=1, weightopt=0;
1.126     brouard  1481: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1482: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1483: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1484:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1485: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1486: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1487: 
1.130     brouard  1488: double jmean=1; /* Mean space between 2 waves */
1.366     brouard  1489: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b); /* test */
                   1490: /* double **matprod2();  *//* test */
1.126     brouard  1491: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1492: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1493: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1494: 
1.136     brouard  1495: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1496: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1497: FILE *ficlog, *ficrespow;
1.130     brouard  1498: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1499: double fretone; /* Only one call to likelihood */
1.130     brouard  1500: long ipmx=0; /* Number of contributions */
1.126     brouard  1501: double sw; /* Sum of weights */
                   1502: char filerespow[FILENAMELENGTH];
                   1503: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1504: FILE *ficresilk;
                   1505: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1506: FILE *ficresprobmorprev;
                   1507: FILE *fichtm, *fichtmcov; /* Html File */
                   1508: FILE *ficreseij;
                   1509: char filerese[FILENAMELENGTH];
                   1510: FILE *ficresstdeij;
                   1511: char fileresstde[FILENAMELENGTH];
                   1512: FILE *ficrescveij;
                   1513: char filerescve[FILENAMELENGTH];
                   1514: FILE  *ficresvij;
                   1515: char fileresv[FILENAMELENGTH];
1.269     brouard  1516: 
1.126     brouard  1517: char title[MAXLINE];
1.234     brouard  1518: char model[MAXLINE]; /**< The model line */
1.217     brouard  1519: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1520: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1521: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1522: char command[FILENAMELENGTH];
                   1523: int  outcmd=0;
                   1524: 
1.217     brouard  1525: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1526: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1527: char filelog[FILENAMELENGTH]; /* Log file */
                   1528: char filerest[FILENAMELENGTH];
                   1529: char fileregp[FILENAMELENGTH];
                   1530: char popfile[FILENAMELENGTH];
                   1531: 
                   1532: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1533: 
1.157     brouard  1534: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1535: /* struct timezone tzp; */
                   1536: /* extern int gettimeofday(); */
                   1537: 
1.366     brouard  1538: /* extern time_t time(); */ /* Commented out for clang */
                   1539: /* struct tm tml, *gmtime(), *localtime(); */
                   1540: 
1.157     brouard  1541: 
                   1542: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1543: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
1.349     brouard  1544: time_t   rlast_btime; /* raw time */
1.366     brouard  1545: /* struct tm tm; */
                   1546: struct tm tm, tml;
1.157     brouard  1547: 
1.126     brouard  1548: char strcurr[80], strfor[80];
                   1549: 
                   1550: char *endptr;
                   1551: long lval;
                   1552: double dval;
                   1553: 
1.362     brouard  1554: /* This for praxis gegen */
                   1555:   /* int prin=1; */
                   1556:   double h0=0.25;
                   1557:   double macheps;
                   1558:   double ffmin;
                   1559: 
1.126     brouard  1560: #define NR_END 1
                   1561: #define FREE_ARG char*
                   1562: #define FTOL 1.0e-10
                   1563: 
                   1564: #define NRANSI 
1.240     brouard  1565: #define ITMAX 200
                   1566: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1567: 
                   1568: #define TOL 2.0e-4 
                   1569: 
                   1570: #define CGOLD 0.3819660 
                   1571: #define ZEPS 1.0e-10 
                   1572: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1573: 
                   1574: #define GOLD 1.618034 
                   1575: #define GLIMIT 100.0 
                   1576: #define TINY 1.0e-20 
                   1577: 
                   1578: static double maxarg1,maxarg2;
                   1579: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1580: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1581:   
                   1582: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1583: #define rint(a) floor(a+0.5)
1.166     brouard  1584: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1585: #define mytinydouble 1.0e-16
1.166     brouard  1586: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1587: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1588: /* static double dsqrarg; */
                   1589: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1590: static double sqrarg;
                   1591: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1592: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1593: int agegomp= AGEGOMP;
                   1594: 
                   1595: int imx; 
                   1596: int stepm=1;
                   1597: /* Stepm, step in month: minimum step interpolation*/
                   1598: 
                   1599: int estepm;
                   1600: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1601: 
                   1602: int m,nb;
                   1603: long *num;
1.197     brouard  1604: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1605: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1606:                   covariate for which somebody answered excluding 
                   1607:                   undefined. Usually 2: 0 and 1. */
                   1608: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1609:                             covariate for which somebody answered including 
                   1610:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1611: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1612: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1613: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1614: 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  1615: double *ageexmed,*agecens;
                   1616: double dateintmean=0;
1.296     brouard  1617:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1618:   double anprojf, mprojf, jprojf;
1.126     brouard  1619: 
1.296     brouard  1620:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1621:   double anbackf, mbackf, jbackf;
                   1622:   double jintmean,mintmean,aintmean;  
1.126     brouard  1623: double *weight;
                   1624: int **s; /* Status */
1.141     brouard  1625: double *agedc;
1.145     brouard  1626: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1627:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1628:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1629: double **coqvar; /* Fixed quantitative covariate nqv */
1.341     brouard  1630: double ***cotvar; /* Time varying covariate start at ncovcol + nqv + (1 to ntv) */
1.225     brouard  1631: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1632: double  idx; 
                   1633: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1634: /* Some documentation */
                   1635:       /*   Design original data
                   1636:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1637:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1638:        *                                                             ntv=3     nqtv=1
1.330     brouard  1639:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1640:        * For time varying covariate, quanti or dummies
                   1641:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
1.341     brouard  1642:        *       cotvar[wav][ncovcol+nqv+ iv(1 to nqtv)][i]= [(1 to nqtv)][i]=(V12) quanti
1.319     brouard  1643:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1644:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1645:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1646:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1647:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1648:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1649:        */
                   1650: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1651: /* 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
                   1652:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1653:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1654: */
1.349     brouard  1655: /*           V5+V4+ V3+V4*V3 +V5*age+V2 +V1*V2+V1*age+V1+V4*V3*age */
                   1656: /*    kmodel  1  2   3    4     5     6    7     8     9    10 */
                   1657: /*Typevar[k]=  0  0   0   2     1    0    2     1     0    3 *//*0 for simple covariate (dummy, quantitative,*/
                   1658:                                                                /* fixed or varying), 1 for age product, 2 for*/
                   1659:                                                                /* product without age, 3 for age and double product   */
                   1660: /*Dummy[k]=    1  0   0   1     3    1    1     2     0     3  *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1661:                                                                 /*(single or product without age), 2 dummy*/
                   1662:                                                                /* with age product, 3 quant with age product*/
                   1663: /*Tvar[k]=     5  4   3   6     5    2    7     1     1     6 */
                   1664: /*    nsd         1   2                               3 */ /* Counting single dummies covar fixed or tv */
                   1665: /*TnsdVar[Tvar]   1   2                               3 */ 
                   1666: /*Tvaraff[nsd]    4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1667: /*TvarsD[nsd]     4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1668: /*TvarsDind[nsd]  2   3                               9 */ /* position K of single dummy cova */
                   1669: /*    nsq      1                     2                  */ /* Counting single quantit tv */
                   1670: /* TvarsQ[k]   5                     2                  */ /* Number of single quantitative cova */
                   1671: /* TvarsQind   1                     6                  */ /* position K of single quantitative cova */
                   1672: /* Tprod[i]=k             1               2             */ /* Position in model of the ith prod without age */
                   1673: /* cptcovage                    1               2         3 */ /* Counting cov*age in the model equation */
                   1674: /* Tage[cptcovage]=k            5               8         10 */ /* Position in the model of ith cov*age */
1.350     brouard  1675: /* 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"*/
                   1676: /*  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  1677: /*  p Tvard[2][1]@21 = {7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0 <repeats 11 times>} */
1.350     brouard  1678: /* 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}*/
                   1679: /* 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  1680: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2               */ /* Position in model of the ith prod without age */
1.330     brouard  1681: /* 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  1682: /* 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  1683: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1684: /* Type                    */
                   1685: /* V         1  2  3  4  5 */
                   1686: /*           F  F  V  V  V */
                   1687: /*           D  Q  D  D  Q */
                   1688: /*                         */
                   1689: int *TvarsD;
1.330     brouard  1690: int *TnsdVar;
1.234     brouard  1691: int *TvarsDind;
                   1692: int *TvarsQ;
                   1693: int *TvarsQind;
                   1694: 
1.318     brouard  1695: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1696: int nresult=0;
1.258     brouard  1697: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1698: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1699: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1700: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1701: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1702: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1703: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1704: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1705: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1706: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1707: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1708: 
                   1709: /* 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
                   1710:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1711:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1712: */
1.234     brouard  1713: /* 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  1714: 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 */
                   1715: 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 */
                   1716: 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 */
                   1717: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1718: 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 */
                   1719: 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  1720: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1721: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1722: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1723: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1724: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1725: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1726: 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 */
                   1727: 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  1728: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1729: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
1.349     brouard  1730: int *TvarVVA; /* We count ncovvt time varying covariates (single or products with age) and put their name into TvarVVA */
                   1731: int *TvarVVAind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1732: int *TvarAVVA; /* We count ALL ncovta time varying covariates (single or products with age) and put their name into TvarVVA */
                   1733: int *TvarAVVAind; /* We count ALL ncovta time varying covariates (single or products without age) and put their name into TvarVV */
1.339     brouard  1734:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  1735:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age */
                   1736:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   1737:       /* TvarVV={3,1,3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */        
                   1738:       /* 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  1739: int *Tvarsel; /**< Selected covariates for output */
                   1740: double *Tvalsel; /**< Selected modality value of covariate for output */
1.349     brouard  1741: 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  1742: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1743: 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  1744: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1745: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1746: int *Tage;
1.227     brouard  1747: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1748: 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  1749: 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*/ 
                   1750: 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  1751: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1752: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1753: int **Tvard;
1.330     brouard  1754: int **Tvardk;
1.227     brouard  1755: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1756: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1757: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1758:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1759:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1760: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1761: double *lsurv, *lpop, *tpop;
                   1762: 
1.231     brouard  1763: #define FD 1; /* Fixed dummy covariate */
                   1764: #define FQ 2; /* Fixed quantitative covariate */
                   1765: #define FP 3; /* Fixed product covariate */
                   1766: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1767: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1768: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1769: #define VD 10; /* Varying dummy covariate */
                   1770: #define VQ 11; /* Varying quantitative covariate */
                   1771: #define VP 12; /* Varying product covariate */
                   1772: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1773: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1774: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1775: #define APFD 16; /* Age product * fixed dummy covariate */
                   1776: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1777: #define APVD 18; /* Age product * varying dummy covariate */
                   1778: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1779: 
                   1780: #define FTYPE 1; /* Fixed covariate */
                   1781: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1782: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1783: 
                   1784: struct kmodel{
                   1785:        int maintype; /* main type */
                   1786:        int subtype; /* subtype */
                   1787: };
                   1788: struct kmodel modell[NCOVMAX];
                   1789: 
1.143     brouard  1790: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1791: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1792: 
                   1793: /**************** split *************************/
                   1794: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1795: {
                   1796:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1797:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1798:   */ 
                   1799:   char *ss;                            /* pointer */
1.186     brouard  1800:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1801: 
                   1802:   l1 = strlen(path );                  /* length of path */
                   1803:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1804:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1805:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1806:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1807:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1808:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1809:     /* get current working directory */
                   1810:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1811: #ifdef WIN32
                   1812:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1813: #else
                   1814:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1815: #endif
1.126     brouard  1816:       return( GLOCK_ERROR_GETCWD );
                   1817:     }
                   1818:     /* got dirc from getcwd*/
                   1819:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1820:   } else {                             /* strip directory from path */
1.126     brouard  1821:     ss++;                              /* after this, the filename */
                   1822:     l2 = strlen( ss );                 /* length of filename */
                   1823:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1824:     strcpy( name, ss );                /* save file name */
                   1825:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1826:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1827:     printf(" DIRC2 = %s \n",dirc);
                   1828:   }
                   1829:   /* We add a separator at the end of dirc if not exists */
                   1830:   l1 = strlen( dirc );                 /* length of directory */
                   1831:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1832:     dirc[l1] =  DIRSEPARATOR;
                   1833:     dirc[l1+1] = 0; 
                   1834:     printf(" DIRC3 = %s \n",dirc);
                   1835:   }
                   1836:   ss = strrchr( name, '.' );           /* find last / */
                   1837:   if (ss >0){
                   1838:     ss++;
                   1839:     strcpy(ext,ss);                    /* save extension */
                   1840:     l1= strlen( name);
                   1841:     l2= strlen(ss)+1;
                   1842:     strncpy( finame, name, l1-l2);
                   1843:     finame[l1-l2]= 0;
                   1844:   }
                   1845: 
                   1846:   return( 0 );                         /* we're done */
                   1847: }
                   1848: 
                   1849: 
                   1850: /******************************************/
                   1851: 
                   1852: void replace_back_to_slash(char *s, char*t)
                   1853: {
                   1854:   int i;
                   1855:   int lg=0;
                   1856:   i=0;
                   1857:   lg=strlen(t);
                   1858:   for(i=0; i<= lg; i++) {
                   1859:     (s[i] = t[i]);
                   1860:     if (t[i]== '\\') s[i]='/';
                   1861:   }
                   1862: }
                   1863: 
1.132     brouard  1864: char *trimbb(char *out, char *in)
1.137     brouard  1865: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1866:   char *s;
                   1867:   s=out;
                   1868:   while (*in != '\0'){
1.137     brouard  1869:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1870:       in++;
                   1871:     }
                   1872:     *out++ = *in++;
                   1873:   }
                   1874:   *out='\0';
                   1875:   return s;
                   1876: }
                   1877: 
1.351     brouard  1878: char *trimbtab(char *out, char *in)
                   1879: { /* Trim  blanks or tabs in line but keeps first blanks if line starts with blanks */
                   1880:   char *s;
                   1881:   s=out;
                   1882:   while (*in != '\0'){
                   1883:     while( (*in == ' ' || *in == '\t')){ /* && *(in+1) != '\0'){*/
                   1884:       in++;
                   1885:     }
                   1886:     *out++ = *in++;
                   1887:   }
                   1888:   *out='\0';
                   1889:   return s;
                   1890: }
                   1891: 
1.187     brouard  1892: /* char *substrchaine(char *out, char *in, char *chain) */
                   1893: /* { */
                   1894: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1895: /*   char *s, *t; */
                   1896: /*   t=in;s=out; */
                   1897: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1898: /*     *out++ = *in++; */
                   1899: /*   } */
                   1900: 
                   1901: /*   /\* *in matches *chain *\/ */
                   1902: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1903: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1904: /*   } */
                   1905: /*   in--; chain--; */
                   1906: /*   while ( (*in != '\0')){ */
                   1907: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1908: /*     *out++ = *in++; */
                   1909: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1910: /*   } */
                   1911: /*   *out='\0'; */
                   1912: /*   out=s; */
                   1913: /*   return out; */
                   1914: /* } */
                   1915: char *substrchaine(char *out, char *in, char *chain)
                   1916: {
                   1917:   /* Substract chain 'chain' from 'in', return and output 'out' */
1.349     brouard  1918:   /* in="V1+V1*age+age*age+V2", chain="+age*age" out="V1+V1*age+V2" */
1.187     brouard  1919: 
                   1920:   char *strloc;
                   1921: 
1.349     brouard  1922:   strcpy (out, in);                   /* out="V1+V1*age+age*age+V2" */
                   1923:   strloc = strstr(out, chain); /* strloc points to out at "+age*age+V2"  */
                   1924:   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  1925:   if(strloc != NULL){ 
1.349     brouard  1926:     /* will affect out */ /* strloc+strlen(chain)=|+V2 = "V1+V1*age+age*age|+V2" */ /* Will also work in Unicodek */
                   1927:     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)*/
                   1928:     /* equivalent to strcpy (strloc, strloc +strlen(chain)) if no overlap; Copies from "+V2" to V1+V1*age+ */
1.187     brouard  1929:   }
1.349     brouard  1930:   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  1931:   return out;
                   1932: }
                   1933: 
                   1934: 
1.145     brouard  1935: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1936: {
1.187     brouard  1937:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.349     brouard  1938:      and alocc starts after first occurence of char 'occ' : ex cutl(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1939:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1940:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1941:   */
1.160     brouard  1942:   char *s, *t;
1.145     brouard  1943:   t=in;s=in;
                   1944:   while ((*in != occ) && (*in != '\0')){
                   1945:     *alocc++ = *in++;
                   1946:   }
                   1947:   if( *in == occ){
                   1948:     *(alocc)='\0';
                   1949:     s=++in;
                   1950:   }
                   1951:  
                   1952:   if (s == t) {/* occ not found */
                   1953:     *(alocc-(in-s))='\0';
                   1954:     in=s;
                   1955:   }
                   1956:   while ( *in != '\0'){
                   1957:     *blocc++ = *in++;
                   1958:   }
                   1959: 
                   1960:   *blocc='\0';
                   1961:   return t;
                   1962: }
1.137     brouard  1963: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1964: {
1.187     brouard  1965:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1966:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1967:      gives blocc="abcdef2ghi" and alocc="j".
                   1968:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1969:   */
                   1970:   char *s, *t;
                   1971:   t=in;s=in;
                   1972:   while (*in != '\0'){
                   1973:     while( *in == occ){
                   1974:       *blocc++ = *in++;
                   1975:       s=in;
                   1976:     }
                   1977:     *blocc++ = *in++;
                   1978:   }
                   1979:   if (s == t) /* occ not found */
                   1980:     *(blocc-(in-s))='\0';
                   1981:   else
                   1982:     *(blocc-(in-s)-1)='\0';
                   1983:   in=s;
                   1984:   while ( *in != '\0'){
                   1985:     *alocc++ = *in++;
                   1986:   }
                   1987: 
                   1988:   *alocc='\0';
                   1989:   return s;
                   1990: }
                   1991: 
1.126     brouard  1992: int nbocc(char *s, char occ)
                   1993: {
                   1994:   int i,j=0;
                   1995:   int lg=20;
                   1996:   i=0;
                   1997:   lg=strlen(s);
                   1998:   for(i=0; i<= lg; i++) {
1.234     brouard  1999:     if  (s[i] == occ ) j++;
1.126     brouard  2000:   }
                   2001:   return j;
                   2002: }
                   2003: 
1.349     brouard  2004: int nboccstr(char *textin, char *chain)
                   2005: {
                   2006:   /* Counts the number of occurence of "chain"  in string textin */
                   2007:   /*  in="+V7*V4+age*V2+age*V3+age*V4"  chain="age" */
                   2008:   char *strloc;
                   2009:   
1.366     brouard  2010:   int j=0;
1.349     brouard  2011: 
                   2012:   strloc=textin; /* strloc points to "^+V7*V4+age+..." in textin */
                   2013:   for(;;) {
                   2014:     strloc= strstr(strloc,chain); /* strloc points to first character of chain in textin if found. Example strloc points^ to "+V7*V4+^age" in textin  */
                   2015:     if(strloc != NULL){
                   2016:       strloc = strloc+strlen(chain); /* strloc points to "+V7*V4+age^" in textin */
                   2017:       j++;
                   2018:     }else
                   2019:       break;
                   2020:   }
                   2021:   return j;
                   2022:   
                   2023: }
1.137     brouard  2024: /* void cutv(char *u,char *v, char*t, char occ) */
                   2025: /* { */
                   2026: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   2027: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   2028: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   2029: /*   int i,lg,j,p=0; */
                   2030: /*   i=0; */
                   2031: /*   lg=strlen(t); */
                   2032: /*   for(j=0; j<=lg-1; j++) { */
                   2033: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   2034: /*   } */
1.126     brouard  2035: 
1.137     brouard  2036: /*   for(j=0; j<p; j++) { */
                   2037: /*     (u[j] = t[j]); */
                   2038: /*   } */
                   2039: /*      u[p]='\0'; */
1.126     brouard  2040: 
1.137     brouard  2041: /*    for(j=0; j<= lg; j++) { */
                   2042: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   2043: /*   } */
                   2044: /* } */
1.126     brouard  2045: 
1.160     brouard  2046: #ifdef _WIN32
                   2047: char * strsep(char **pp, const char *delim)
                   2048: {
                   2049:   char *p, *q;
                   2050:          
                   2051:   if ((p = *pp) == NULL)
                   2052:     return 0;
                   2053:   if ((q = strpbrk (p, delim)) != NULL)
                   2054:   {
                   2055:     *pp = q + 1;
                   2056:     *q = '\0';
                   2057:   }
                   2058:   else
                   2059:     *pp = 0;
                   2060:   return p;
                   2061: }
                   2062: #endif
                   2063: 
1.126     brouard  2064: /********************** nrerror ********************/
                   2065: 
                   2066: void nrerror(char error_text[])
                   2067: {
                   2068:   fprintf(stderr,"ERREUR ...\n");
                   2069:   fprintf(stderr,"%s\n",error_text);
                   2070:   exit(EXIT_FAILURE);
                   2071: }
                   2072: /*********************** vector *******************/
                   2073: double *vector(int nl, int nh)
                   2074: {
                   2075:   double *v;
                   2076:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   2077:   if (!v) nrerror("allocation failure in vector");
                   2078:   return v-nl+NR_END;
                   2079: }
                   2080: 
                   2081: /************************ free vector ******************/
                   2082: void free_vector(double*v, int nl, int nh)
                   2083: {
                   2084:   free((FREE_ARG)(v+nl-NR_END));
                   2085: }
                   2086: 
                   2087: /************************ivector *******************************/
                   2088: int *ivector(long nl,long nh)
                   2089: {
                   2090:   int *v;
                   2091:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   2092:   if (!v) nrerror("allocation failure in ivector");
                   2093:   return v-nl+NR_END;
                   2094: }
                   2095: 
                   2096: /******************free ivector **************************/
                   2097: void free_ivector(int *v, long nl, long nh)
                   2098: {
                   2099:   free((FREE_ARG)(v+nl-NR_END));
                   2100: }
                   2101: 
                   2102: /************************lvector *******************************/
                   2103: long *lvector(long nl,long nh)
                   2104: {
                   2105:   long *v;
                   2106:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   2107:   if (!v) nrerror("allocation failure in ivector");
                   2108:   return v-nl+NR_END;
                   2109: }
                   2110: 
                   2111: /******************free lvector **************************/
                   2112: void free_lvector(long *v, long nl, long nh)
                   2113: {
                   2114:   free((FREE_ARG)(v+nl-NR_END));
                   2115: }
                   2116: 
                   2117: /******************* imatrix *******************************/
                   2118: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   2119:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   2120: { 
                   2121:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   2122:   int **m; 
                   2123:   
                   2124:   /* allocate pointers to rows */ 
                   2125:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   2126:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   2127:   m += NR_END; 
                   2128:   m -= nrl; 
                   2129:   
                   2130:   
                   2131:   /* allocate rows and set pointers to them */ 
                   2132:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   2133:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   2134:   m[nrl] += NR_END; 
                   2135:   m[nrl] -= ncl; 
                   2136:   
                   2137:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   2138:   
                   2139:   /* return pointer to array of pointers to rows */ 
                   2140:   return m; 
                   2141: } 
                   2142: 
                   2143: /****************** free_imatrix *************************/
1.366     brouard  2144: /* void free_imatrix(m,nrl,nrh,ncl,nch); */
                   2145: /*       int **m; */
                   2146: /*       long nch,ncl,nrh,nrl; */
                   2147: void free_imatrix(int **m,long nrl, long nrh, long ncl, long nch)
                   2148:      /* free an int matrix allocated by imatrix() */
                   2149: {
                   2150:   free((FREE_ARG) (m[nrl]+ncl-NR_END));
                   2151:   free((FREE_ARG) (m+nrl-NR_END));
                   2152: }
1.126     brouard  2153: 
                   2154: /******************* matrix *******************************/
                   2155: double **matrix(long nrl, long nrh, long ncl, long nch)
                   2156: {
                   2157:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   2158:   double **m;
                   2159: 
                   2160:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2161:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2162:   m += NR_END;
                   2163:   m -= nrl;
                   2164: 
                   2165:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2166:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2167:   m[nrl] += NR_END;
                   2168:   m[nrl] -= ncl;
                   2169: 
                   2170:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2171:   return m;
1.145     brouard  2172:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   2173: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   2174: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  2175:    */
                   2176: }
                   2177: 
                   2178: /*************************free matrix ************************/
                   2179: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   2180: {
                   2181:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2182:   free((FREE_ARG)(m+nrl-NR_END));
                   2183: }
                   2184: 
                   2185: /******************* ma3x *******************************/
                   2186: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   2187: {
                   2188:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   2189:   double ***m;
                   2190: 
                   2191:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2192:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2193:   m += NR_END;
                   2194:   m -= nrl;
                   2195: 
                   2196:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2197:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2198:   m[nrl] += NR_END;
                   2199:   m[nrl] -= ncl;
                   2200: 
                   2201:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2202: 
                   2203:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   2204:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2205:   m[nrl][ncl] += NR_END;
                   2206:   m[nrl][ncl] -= nll;
                   2207:   for (j=ncl+1; j<=nch; j++) 
                   2208:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2209:   
                   2210:   for (i=nrl+1; i<=nrh; i++) {
                   2211:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2212:     for (j=ncl+1; j<=nch; j++) 
                   2213:       m[i][j]=m[i][j-1]+nlay;
                   2214:   }
                   2215:   return m; 
                   2216:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2217:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2218:   */
                   2219: }
                   2220: 
                   2221: /*************************free ma3x ************************/
                   2222: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2223: {
                   2224:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2225:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2226:   free((FREE_ARG)(m+nrl-NR_END));
                   2227: }
                   2228: 
                   2229: /*************** function subdirf ***********/
                   2230: char *subdirf(char fileres[])
                   2231: {
                   2232:   /* Caution optionfilefiname is hidden */
                   2233:   strcpy(tmpout,optionfilefiname);
                   2234:   strcat(tmpout,"/"); /* Add to the right */
                   2235:   strcat(tmpout,fileres);
                   2236:   return tmpout;
                   2237: }
                   2238: 
                   2239: /*************** function subdirf2 ***********/
                   2240: char *subdirf2(char fileres[], char *preop)
                   2241: {
1.314     brouard  2242:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2243:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2244:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2245:   /* Caution optionfilefiname is hidden */
                   2246:   strcpy(tmpout,optionfilefiname);
                   2247:   strcat(tmpout,"/");
                   2248:   strcat(tmpout,preop);
                   2249:   strcat(tmpout,fileres);
                   2250:   return tmpout;
                   2251: }
                   2252: 
                   2253: /*************** function subdirf3 ***********/
                   2254: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2255: {
                   2256:   
                   2257:   /* Caution optionfilefiname is hidden */
                   2258:   strcpy(tmpout,optionfilefiname);
                   2259:   strcat(tmpout,"/");
                   2260:   strcat(tmpout,preop);
                   2261:   strcat(tmpout,preop2);
                   2262:   strcat(tmpout,fileres);
                   2263:   return tmpout;
                   2264: }
1.213     brouard  2265:  
                   2266: /*************** function subdirfext ***********/
                   2267: char *subdirfext(char fileres[], char *preop, char *postop)
                   2268: {
                   2269:   
                   2270:   strcpy(tmpout,preop);
                   2271:   strcat(tmpout,fileres);
                   2272:   strcat(tmpout,postop);
                   2273:   return tmpout;
                   2274: }
1.126     brouard  2275: 
1.213     brouard  2276: /*************** function subdirfext3 ***********/
                   2277: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2278: {
                   2279:   
                   2280:   /* Caution optionfilefiname is hidden */
                   2281:   strcpy(tmpout,optionfilefiname);
                   2282:   strcat(tmpout,"/");
                   2283:   strcat(tmpout,preop);
                   2284:   strcat(tmpout,fileres);
                   2285:   strcat(tmpout,postop);
                   2286:   return tmpout;
                   2287: }
                   2288:  
1.162     brouard  2289: char *asc_diff_time(long time_sec, char ascdiff[])
                   2290: {
                   2291:   long sec_left, days, hours, minutes;
                   2292:   days = (time_sec) / (60*60*24);
                   2293:   sec_left = (time_sec) % (60*60*24);
                   2294:   hours = (sec_left) / (60*60) ;
                   2295:   sec_left = (sec_left) %(60*60);
                   2296:   minutes = (sec_left) /60;
                   2297:   sec_left = (sec_left) % (60);
                   2298:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2299:   return ascdiff;
                   2300: }
                   2301: 
1.126     brouard  2302: /***************** f1dim *************************/
                   2303: extern int ncom; 
                   2304: extern double *pcom,*xicom;
                   2305: extern double (*nrfunc)(double []); 
                   2306:  
                   2307: double f1dim(double x) 
                   2308: { 
                   2309:   int j; 
                   2310:   double f;
                   2311:   double *xt; 
                   2312:  
                   2313:   xt=vector(1,ncom); 
                   2314:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2315:   f=(*nrfunc)(xt); 
                   2316:   free_vector(xt,1,ncom); 
                   2317:   return f; 
                   2318: } 
                   2319: 
                   2320: /*****************brent *************************/
                   2321: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2322: {
                   2323:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2324:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2325:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2326:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2327:    * returned function value. 
                   2328:   */
1.126     brouard  2329:   int iter; 
                   2330:   double a,b,d,etemp;
1.159     brouard  2331:   double fu=0,fv,fw,fx;
1.164     brouard  2332:   double ftemp=0.;
1.126     brouard  2333:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2334:   double e=0.0; 
                   2335:  
                   2336:   a=(ax < cx ? ax : cx); 
                   2337:   b=(ax > cx ? ax : cx); 
                   2338:   x=w=v=bx; 
                   2339:   fw=fv=fx=(*f)(x); 
                   2340:   for (iter=1;iter<=ITMAX;iter++) { 
                   2341:     xm=0.5*(a+b); 
                   2342:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2343:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2344:     printf(".");fflush(stdout);
                   2345:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2346: #ifdef DEBUGBRENT
1.126     brouard  2347:     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);
                   2348:     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);
                   2349:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2350: #endif
                   2351:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2352:       *xmin=x; 
                   2353:       return fx; 
                   2354:     } 
                   2355:     ftemp=fu;
                   2356:     if (fabs(e) > tol1) { 
                   2357:       r=(x-w)*(fx-fv); 
                   2358:       q=(x-v)*(fx-fw); 
                   2359:       p=(x-v)*q-(x-w)*r; 
                   2360:       q=2.0*(q-r); 
                   2361:       if (q > 0.0) p = -p; 
                   2362:       q=fabs(q); 
                   2363:       etemp=e; 
                   2364:       e=d; 
                   2365:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2366:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2367:       else { 
1.224     brouard  2368:                                d=p/q; 
                   2369:                                u=x+d; 
                   2370:                                if (u-a < tol2 || b-u < tol2) 
                   2371:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2372:       } 
                   2373:     } else { 
                   2374:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2375:     } 
                   2376:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2377:     fu=(*f)(u); 
                   2378:     if (fu <= fx) { 
                   2379:       if (u >= x) a=x; else b=x; 
                   2380:       SHFT(v,w,x,u) 
1.183     brouard  2381:       SHFT(fv,fw,fx,fu) 
                   2382:     } else { 
                   2383:       if (u < x) a=u; else b=u; 
                   2384:       if (fu <= fw || w == x) { 
1.224     brouard  2385:                                v=w; 
                   2386:                                w=u; 
                   2387:                                fv=fw; 
                   2388:                                fw=fu; 
1.183     brouard  2389:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2390:                                v=u; 
                   2391:                                fv=fu; 
1.183     brouard  2392:       } 
                   2393:     } 
1.126     brouard  2394:   } 
                   2395:   nrerror("Too many iterations in brent"); 
                   2396:   *xmin=x; 
                   2397:   return fx; 
                   2398: } 
                   2399: 
                   2400: /****************** mnbrak ***********************/
                   2401: 
                   2402: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2403:            double (*func)(double)) 
1.183     brouard  2404: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2405: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2406: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2407: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2408:    */
1.126     brouard  2409:   double ulim,u,r,q, dum;
                   2410:   double fu; 
1.187     brouard  2411: 
1.366     brouard  2412:   /* double scale=10.; */
                   2413:   /* int iterscale=0; */
1.187     brouard  2414: 
                   2415:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2416:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2417: 
                   2418: 
                   2419:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2420:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2421:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2422:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2423:   /* } */
                   2424: 
1.126     brouard  2425:   if (*fb > *fa) { 
                   2426:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2427:     SHFT(dum,*fb,*fa,dum) 
                   2428:   } 
1.126     brouard  2429:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2430:   *fc=(*func)(*cx); 
1.183     brouard  2431: #ifdef DEBUG
1.224     brouard  2432:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2433:   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  2434: #endif
1.224     brouard  2435:   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  2436:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2437:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2438:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2439:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2440:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2441:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2442:       fu=(*func)(u); 
1.163     brouard  2443: #ifdef DEBUG
                   2444:       /* f(x)=A(x-u)**2+f(u) */
                   2445:       double A, fparabu; 
                   2446:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2447:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2448:       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);
                   2449:       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  2450:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2451:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2452:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2453:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2454: #endif 
1.184     brouard  2455: #ifdef MNBRAKORIGINAL
1.183     brouard  2456: #else
1.191     brouard  2457: /*       if (fu > *fc) { */
                   2458: /* #ifdef DEBUG */
                   2459: /*       printf("mnbrak4  fu > fc \n"); */
                   2460: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2461: /* #endif */
                   2462: /*     /\* 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 *\\/  *\/ */
                   2463: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2464: /*     dum=u; /\* Shifting c and u *\/ */
                   2465: /*     u = *cx; */
                   2466: /*     *cx = dum; */
                   2467: /*     dum = fu; */
                   2468: /*     fu = *fc; */
                   2469: /*     *fc =dum; */
                   2470: /*       } else { /\* end *\/ */
                   2471: /* #ifdef DEBUG */
                   2472: /*       printf("mnbrak3  fu < fc \n"); */
                   2473: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2474: /* #endif */
                   2475: /*     dum=u; /\* Shifting c and u *\/ */
                   2476: /*     u = *cx; */
                   2477: /*     *cx = dum; */
                   2478: /*     dum = fu; */
                   2479: /*     fu = *fc; */
                   2480: /*     *fc =dum; */
                   2481: /*       } */
1.224     brouard  2482: #ifdef DEBUGMNBRAK
                   2483:                 double A, fparabu; 
                   2484:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2485:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2486:      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);
                   2487:      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  2488: #endif
1.191     brouard  2489:       dum=u; /* Shifting c and u */
                   2490:       u = *cx;
                   2491:       *cx = dum;
                   2492:       dum = fu;
                   2493:       fu = *fc;
                   2494:       *fc =dum;
1.183     brouard  2495: #endif
1.162     brouard  2496:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2497: #ifdef DEBUG
1.224     brouard  2498:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2499:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2500: #endif
1.126     brouard  2501:       fu=(*func)(u); 
                   2502:       if (fu < *fc) { 
1.183     brouard  2503: #ifdef DEBUG
1.224     brouard  2504:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2505:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2506: #endif
                   2507:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2508:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2509: #ifdef DEBUG
                   2510:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2511: #endif
                   2512:       } 
1.162     brouard  2513:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2514: #ifdef DEBUG
1.224     brouard  2515:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2516:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2517: #endif
1.126     brouard  2518:       u=ulim; 
                   2519:       fu=(*func)(u); 
1.183     brouard  2520:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2521: #ifdef DEBUG
1.224     brouard  2522:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2523:       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  2524: #endif
1.126     brouard  2525:       u=(*cx)+GOLD*(*cx-*bx); 
                   2526:       fu=(*func)(u); 
1.224     brouard  2527: #ifdef DEBUG
                   2528:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2529:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2530: #endif
1.183     brouard  2531:     } /* end tests */
1.126     brouard  2532:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2533:     SHFT(*fa,*fb,*fc,fu) 
                   2534: #ifdef DEBUG
1.224     brouard  2535:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2536:       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  2537: #endif
                   2538:   } /* 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  2539: } 
                   2540: 
                   2541: /*************** linmin ************************/
1.162     brouard  2542: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2543: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2544: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2545: the value of func at the returned location p . This is actually all accomplished by calling the
                   2546: routines mnbrak and brent .*/
1.126     brouard  2547: int ncom; 
                   2548: double *pcom,*xicom;
                   2549: double (*nrfunc)(double []); 
                   2550:  
1.224     brouard  2551: #ifdef LINMINORIGINAL
1.126     brouard  2552: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2553: #else
                   2554: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2555: #endif
1.126     brouard  2556: { 
                   2557:   double brent(double ax, double bx, double cx, 
                   2558:               double (*f)(double), double tol, double *xmin); 
                   2559:   double f1dim(double x); 
                   2560:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2561:              double *fc, double (*func)(double)); 
                   2562:   int j; 
                   2563:   double xx,xmin,bx,ax; 
                   2564:   double fx,fb,fa;
1.187     brouard  2565: 
1.203     brouard  2566: #ifdef LINMINORIGINAL
                   2567: #else
                   2568:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2569: #endif
                   2570:   
1.126     brouard  2571:   ncom=n; 
                   2572:   pcom=vector(1,n); 
                   2573:   xicom=vector(1,n); 
                   2574:   nrfunc=func; 
                   2575:   for (j=1;j<=n;j++) { 
                   2576:     pcom[j]=p[j]; 
1.202     brouard  2577:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2578:   } 
1.187     brouard  2579: 
1.203     brouard  2580: #ifdef LINMINORIGINAL
                   2581:   xx=1.;
                   2582: #else
                   2583:   axs=0.0;
                   2584:   xxs=1.;
                   2585:   do{
                   2586:     xx= xxs;
                   2587: #endif
1.187     brouard  2588:     ax=0.;
                   2589:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2590:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2591:     /* 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))   */
                   2592:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2593:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2594:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2595:     /* 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  2596: #ifdef LINMINORIGINAL
                   2597: #else
                   2598:     if (fx != fx){
1.224     brouard  2599:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2600:                        printf("|");
                   2601:                        fprintf(ficlog,"|");
1.203     brouard  2602: #ifdef DEBUGLINMIN
1.224     brouard  2603:                        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  2604: #endif
                   2605:     }
1.224     brouard  2606:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2607: #endif
                   2608:   
1.191     brouard  2609: #ifdef DEBUGLINMIN
                   2610:   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  2611:   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  2612: #endif
1.224     brouard  2613: #ifdef LINMINORIGINAL
                   2614: #else
1.317     brouard  2615:   if(fb == fx){ /* Flat function in the direction */
                   2616:     xmin=xx;
1.224     brouard  2617:     *flat=1;
1.317     brouard  2618:   }else{
1.224     brouard  2619:     *flat=0;
                   2620: #endif
                   2621:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2622:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2623:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2624:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2625:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2626:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2627: #ifdef DEBUG
1.224     brouard  2628:   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);
                   2629:   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);
                   2630: #endif
                   2631: #ifdef LINMINORIGINAL
                   2632: #else
                   2633:                        }
1.126     brouard  2634: #endif
1.191     brouard  2635: #ifdef DEBUGLINMIN
                   2636:   printf("linmin end ");
1.202     brouard  2637:   fprintf(ficlog,"linmin end ");
1.191     brouard  2638: #endif
1.126     brouard  2639:   for (j=1;j<=n;j++) { 
1.203     brouard  2640: #ifdef LINMINORIGINAL
                   2641:     xi[j] *= xmin; 
                   2642: #else
                   2643: #ifdef DEBUGLINMIN
                   2644:     if(xxs <1.0)
                   2645:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2646: #endif
                   2647:     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) */
                   2648: #ifdef DEBUGLINMIN
                   2649:     if(xxs <1.0)
                   2650:       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 );
                   2651: #endif
                   2652: #endif
1.187     brouard  2653:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2654:   } 
1.191     brouard  2655: #ifdef DEBUGLINMIN
1.203     brouard  2656:   printf("\n");
1.191     brouard  2657:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2658:   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  2659:   for (j=1;j<=n;j++) { 
1.202     brouard  2660:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2661:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2662:     if(j % ncovmodel == 0){
1.191     brouard  2663:       printf("\n");
1.202     brouard  2664:       fprintf(ficlog,"\n");
                   2665:     }
1.191     brouard  2666:   }
1.203     brouard  2667: #else
1.191     brouard  2668: #endif
1.126     brouard  2669:   free_vector(xicom,1,n); 
                   2670:   free_vector(pcom,1,n); 
                   2671: } 
                   2672: 
1.359     brouard  2673: /**** praxis gegen ****/
                   2674: 
                   2675: /* This has been tested by Visual C from Microsoft and works */
                   2676: /* meaning tha valgrind could be wrong */
                   2677: /*********************************************************************/
                   2678: /*     f u n c t i o n     p r a x i s                              */
                   2679: /*                                                                   */
                   2680: /* praxis is a general purpose routine for the minimization of a     */
                   2681: /* function in several variables. the algorithm used is a modifi-    */
                   2682: /* cation of conjugate gradient search method by powell. the changes */
                   2683: /* are due to r.p. brent, who gives an algol-w program, which served */
                   2684: /* as a basis for this function.                                     */
                   2685: /*                                                                   */
                   2686: /* references:                                                       */
                   2687: /*     - powell, m.j.d., 1964. an efficient method for finding       */
                   2688: /*       the minimum of a function in several variables without      */
                   2689: /*       calculating derivatives, computer journal, 7, 155-162       */
                   2690: /*     - brent, r.p., 1973. algorithms for minimization without      */
                   2691: /*       derivatives, prentice hall, englewood cliffs.               */
                   2692: /*                                                                   */
                   2693: /*     problems, suggestions or improvements are always wellcome     */
                   2694: /*                       karl gegenfurtner   07/08/87                */
                   2695: /*                                           c - version             */
                   2696: /*********************************************************************/
                   2697: /*                                                                   */
                   2698: /* usage: min = praxis(tol, macheps, h, n, prin, x, func)      */
                   2699: /* macheps has been suppressed because it is replaced by DBL_EPSILON */
                   2700: /* and if it was an argument of praxis (as it is in original brent)  */
                   2701: /* it should be declared external */
                   2702: /* usage: min = praxis(tol, h, n, prin, x, func)      */
                   2703: /* was    min = praxis(fun, x, n);                                   */
                   2704: /*                                                                   */
                   2705: /*  fun        the function to be minimized. fun is called from      */
                   2706: /*             praxis with x and n as arguments                      */
                   2707: /*  x          a double array containing the initial guesses for     */
                   2708: /*             the minimum, which will contain the solution on       */
                   2709: /*             return                                                */
                   2710: /*  n          an integer specifying the number of unknown           */
                   2711: /*             parameters                                            */
                   2712: /*  min        praxis returns the least calculated value of fun      */
                   2713: /*                                                                   */
                   2714: /* some additional global variables control some more aspects of     */
                   2715: /* the inner workings of praxis. setting them is optional, they      */
                   2716: /* are all set to some reasonable default values given below.        */
                   2717: /*                                                                   */
                   2718: /*   prin      controls the printed output from the routine.         */
                   2719: /*             0 -> no output                                        */
                   2720: /*             1 -> print only starting and final values             */
                   2721: /*             2 -> detailed map of the minimization process         */
                   2722: /*             3 -> print also eigenvalues and vectors of the        */
                   2723: /*                  search directions                                */
                   2724: /*             the default value is 1                                */
                   2725: /*  tol        is the tolerance allowed for the precision of the     */
                   2726: /*             solution. praxis returns if the criterion             */
                   2727: /*             2 * ||x[k]-x[k-1]|| <= sqrt(macheps) * ||x[k]|| + tol */
                   2728: /*             is fulfilled more than ktm times.                     */
                   2729: /*             the default value depends on the machine precision    */
                   2730: /*  ktm        see just above. default is 1, and a value of 4 leads  */
                   2731: /*             to a very(!) cautious stopping criterion.             */
                   2732: /*  h0 or step       is a steplength parameter and should be set equal     */
                   2733: /*             to the expected distance from the solution.           */
                   2734: /*             exceptionally small or large values of step lead to   */
                   2735: /*             slower convergence on the first few iterations        */
                   2736: /*             the default value for step is 1.0                     */
                   2737: /*  scbd       is a scaling parameter. 1.0 is the default and        */
                   2738: /*             indicates no scaling. if the scales for the different */
                   2739: /*             parameters are very different, scbd should be set to  */
                   2740: /*             a value of about 10.0.                                */
                   2741: /*  illc       should be set to true (1) if the problem is known to  */
                   2742: /*             be ill-conditioned. the default is false (0). this    */
                   2743: /*             variable is automatically set, when praxis finds      */
                   2744: /*             the problem to be ill-conditioned during iterations.  */
                   2745: /*  maxfun     is the maximum number of calls to fun allowed. praxis */
                   2746: /*             will return after maxfun calls to fun even when the   */
                   2747: /*             minimum is not yet found. the default value of 0      */
                   2748: /*             indicates no limit on the number of calls.            */
                   2749: /*             this return condition is only checked every n         */
                   2750: /*             iterations.                                           */
                   2751: /*                                                                   */
                   2752: /*********************************************************************/
                   2753: 
                   2754: #include <math.h>
                   2755: #include <stdio.h>
                   2756: #include <stdlib.h>
                   2757: #include <float.h> /* for DBL_EPSILON */
                   2758: /* #include "machine.h" */
                   2759: 
                   2760: 
                   2761: /* extern void minfit(int n, double eps, double tol, double **ab, double q[]); */
                   2762: /* extern void minfit(int n, double eps, double tol, double ab[N][N], double q[]); */
                   2763: /* control parameters */
                   2764: /* control parameters */
                   2765: #define SQREPSILON 1.0e-19
                   2766: /* #define EPSILON 1.0e-8 */ /* in main */
                   2767: 
                   2768: double tol = SQREPSILON,
                   2769:        scbd = 1.0,
                   2770:        step = 1.0;
                   2771: int    ktm = 1,
                   2772:        /* prin = 2, */
                   2773:        maxfun = 0,
                   2774:        illc = 0;
                   2775:        
                   2776: /* some global variables */
                   2777: static int i, j, k, k2, nl, nf, kl, kt;
                   2778: /* static double s; */
                   2779: double sl, dn, dmin,
                   2780:        fx, f1, lds, ldt, sf, df,
                   2781:        qf1, qd0, qd1, qa, qb, qc,
                   2782:        m2, m4, small_windows, vsmall, large, 
                   2783:        vlarge, ldfac, t2;
                   2784: /* static double d[N], y[N], z[N], */
                   2785: /*        q0[N], q1[N], v[N][N]; */
                   2786: 
                   2787: static double *d, *y, *z;
                   2788: static double  *q0, *q1, **v;
                   2789: double *tflin; /* used in flin: return (*fun)(tflin, n); */
                   2790: double *e; /* used in minfit, don't konw how to free memory and thus made global */
                   2791: /* static double s, sl, dn, dmin, */
                   2792: /*        fx, f1, lds, ldt, sf, df, */
                   2793: /*        qf1, qd0, qd1, qa, qb, qc, */
                   2794: /*        m2, m4, small, vsmall, large,  */
                   2795: /*        vlarge, ldfac, t2; */
                   2796: /* static double d[N], y[N], z[N], */
                   2797: /*        q0[N], q1[N], v[N][N]; */
                   2798: 
                   2799: /* these will be set by praxis to point to it's arguments */
                   2800: static int prin; /* added */
                   2801: static int n;
                   2802: static double *x;
1.366     brouard  2803: static double (*fun)(double *x); /* New for clang */
                   2804: /* static double (*fun)(); */
1.359     brouard  2805: /* static double (*fun)(double *x, int n); */
                   2806: 
                   2807: /* these will be set by praxis to the global control parameters */
                   2808: /* static double h, macheps, t; */
                   2809: extern double macheps;
                   2810: static double h;
                   2811: static double t;
                   2812: 
                   2813: static double 
                   2814: drandom()      /* return random no between 0 and 1 */
                   2815: {
                   2816:    return (double)(rand()%(8192*2))/(double)(8192*2);
                   2817: }
                   2818: 
                   2819: static void sort()             /* d and v in descending order */
                   2820: {
                   2821:    int k, i, j;
                   2822:    double s;
                   2823: 
                   2824:    for (i=1; i<=n-1; i++) {
                   2825:        k = i; s = d[i];
                   2826:        for (j=i+1; j<=n; j++) {
                   2827:            if (d[j] > s) {
                   2828:              k = j;
                   2829:              s = d[j];
                   2830:           }
                   2831:        }
                   2832:        if (k > i) {
                   2833:          d[k] = d[i];
                   2834:          d[i] = s;
                   2835:          for (j=1; j<=n; j++) {
                   2836:              s = v[j][i];
                   2837:              v[j][i] = v[j][k];
                   2838:              v[j][k] = s;
                   2839:          }
                   2840:        }
                   2841:    }
                   2842: }
                   2843: 
                   2844: double randbrent ( int *naught )
                   2845: {
                   2846:   double ran1, ran3[127], half;
                   2847:   int ran2, q, r, i, j;
                   2848:   int init=0; /* false */
                   2849:   double rr;
                   2850:   /* REAL*8 RAN1,RAN3(127),HALF */
                   2851: 
                   2852:   /*     INTEGER RAN2,Q,R */
                   2853:   /*     LOGICAL INIT */
                   2854:   /*     DATA INIT/.FALSE./ */
                   2855:   /*     IF (INIT) GO TO 3 */
                   2856:   if(!init){ 
                   2857: /*       R = MOD(NAUGHT,8190) + 1 *//* 1804289383 rand () */
                   2858:     r = *naught % 8190 + 1;/* printf(" naught r %d %d",*naught,r); */
                   2859:     ran2=127;
                   2860:     for(i=ran2; i>0; i--){
                   2861: /*       RAN2 = 128 */
                   2862: /*       DO 2 I=1,127 */
                   2863:       ran2 = ran2-1;
                   2864: /*          RAN2 = RAN2 - 1 */
                   2865:       ran1 = -pow(2.0,55);
                   2866: /*          RAN1 = -2.D0**55 */
                   2867: /*          DO 1 J=1,7 */
                   2868:       for(j=1; j<=7;j++){
                   2869: /*             R = MOD(1756*R,8191) */
                   2870:        r = (1756*r) % 8191;/* printf(" i=%d (1756*r)%8191=%d",j,r); */
                   2871:        q=r/32;
                   2872: /*             Q = R/32 */
                   2873: /* 1           RAN1 = (RAN1 + Q)*(1.0D0/256) */
                   2874:        ran1 =(ran1+q)*(1.0/256);
                   2875:       }
                   2876: /* 2        RAN3(RAN2) = RAN1 */
                   2877:       ran3[ran2] = ran1; /* printf(" ran2=%d ran1=%.7g \n",ran2,ran1); */ 
                   2878:     }
                   2879: /*       INIT = .TRUE. */
                   2880:     init=1;
                   2881: /* 3     IF (RAN2.EQ.1) RAN2 = 128 */
                   2882:   }
                   2883:   if(ran2 == 0) ran2 = 126;
                   2884:   else ran2 = ran2 -1;
                   2885:   /* RAN2 = RAN2 - 1 */
                   2886:   /* RAN1 = RAN1 + RAN3(RAN2) */
                   2887:   ran1 = ran1 + ran3[ran2];/* printf("BIS ran2=%d ran1=%.7g \n",ran2,ran1);  */
                   2888:   half= 0.5;
                   2889:   /* HALF = .5D0 */
                   2890:   /* IF (RAN1.GE.0.D0) HALF = -HALF */
                   2891:   if(ran1 >= 0.) half =-half;
                   2892:   ran1 = ran1 +half;
                   2893:   ran3[ran2] = ran1;
                   2894:   rr= ran1+0.5;
                   2895:   /* RAN1 = RAN1 + HALF */
                   2896:   /*   RAN3(RAN2) = RAN1 */
                   2897:   /*   RANDOM = RAN1 + .5D0 */
                   2898: /*   r = ( ( double ) ( *seed ) ) * 4.656612875E-10; */
                   2899:   return rr;
                   2900: }
                   2901: static void matprint(char *s, double **v, int m, int n)
                   2902: /* char *s; */
                   2903: /* double v[N][N]; */
                   2904: {
                   2905: #define INCX 8
                   2906:   int i;
                   2907:  
                   2908:   int i2hi;
                   2909:   int ihi;
                   2910:   int ilo;
                   2911:   int i2lo;
                   2912:   int jlo=1;
                   2913:   int j;
                   2914:   int j2hi;
                   2915:   int jhi;
                   2916:   int j2lo;
                   2917:   ilo=1;
                   2918:   ihi=n;
                   2919:   jlo=1;
                   2920:   jhi=n;
                   2921:   
                   2922:   printf ("\n" );
                   2923:   printf ("%s\n", s );
                   2924:   for ( j2lo = jlo; j2lo <= jhi; j2lo = j2lo + INCX )
                   2925:   {
                   2926:     j2hi = j2lo + INCX - 1;
                   2927:     if ( n < j2hi )
                   2928:     {
                   2929:       j2hi = n;
                   2930:     }
                   2931:     if ( jhi < j2hi )
                   2932:     {
                   2933:       j2hi = jhi;
                   2934:     }
                   2935: 
                   2936:     /* fprintf ( ficlog, "\n" ); */
                   2937:     printf ("\n" );
                   2938: /*
                   2939:   For each column J in the current range...
                   2940: 
                   2941:   Write the header.
                   2942: */
                   2943:     /* fprintf ( ficlog, "  Col:  "); */
                   2944:     printf ("Col:");
                   2945:     for ( j = j2lo; j <= j2hi; j++ )
                   2946:     {
                   2947:       /* fprintf ( ficlog, "  %7d     ", j - 1 ); */
                   2948:       /* printf (" %9d      ", j - 1 ); */
                   2949:       printf (" %9d      ", j );
                   2950:     }
                   2951:     /* fprintf ( ficlog, "\n" ); */
                   2952:     /* fprintf ( ficlog, "  Row\n" ); */
                   2953:     /* fprintf ( ficlog, "\n" ); */
                   2954:     printf ("\n" );
                   2955:     printf ("  Row\n" );
                   2956:     printf ("\n" );
                   2957: /*
                   2958:   Determine the range of the rows in this strip.
                   2959: */
                   2960:     if ( 1 < ilo ){
                   2961:       i2lo = ilo;
                   2962:     }else{
                   2963:       i2lo = 1;
                   2964:     }
                   2965:     if ( m < ihi ){
                   2966:       i2hi = m;
                   2967:     }else{
                   2968:       i2hi = ihi;
                   2969:     }
                   2970: 
                   2971:     for ( i = i2lo; i <= i2hi; i++ ){
                   2972: /*
                   2973:   Print out (up to) 5 entries in row I, that lie in the current strip.
                   2974: */
                   2975:       /* fprintf ( ficlog, "%5d:", i - 1 ); */
                   2976:       /* printf ("%5d:", i - 1 ); */
                   2977:       printf ("%5d:", i );
                   2978:       for ( j = j2lo; j <= j2hi; j++ )
                   2979:       {
                   2980:         /* fprintf ( ficlog, "  %14g", a[i-1+(j-1)*m] ); */
                   2981:         /* printf ("%14.7g  ", a[i-1+(j-1)*m] ); */
                   2982:            /* printf("%14.7f  ", v[i-1][j-1]); */
                   2983:            printf("%14.7f  ", v[i][j]);
                   2984:         /* fprintf ( stdout, "  %14g", a[i-1+(j-1)*m] ); */
                   2985:       }
                   2986:       /* fprintf ( ficlog, "\n" ); */
                   2987:       printf ("\n" );
                   2988:     }
                   2989:   }
                   2990:  
                   2991:    /* printf("%s\n", s); */
                   2992:    /* for (k=0; k<n; k++) { */
                   2993:    /*     for (i=0; i<n; i++) { */
                   2994:    /*         /\* printf("%20.10e ", v[k][i]); *\/ */
                   2995:    /*     } */
                   2996:    /*     printf("\n"); */
                   2997:    /* } */
                   2998: #undef INCX  
                   2999: }
                   3000: 
                   3001: void vecprint(char *s, double *x, int n)
                   3002: /* char *s; */
                   3003: /* double x[N]; */
                   3004: {
                   3005:    int i=0;
                   3006:    
                   3007:    printf(" %s", s);
                   3008:    /* for (i=0; i<n; i++) */
                   3009:    for (i=1; i<=n; i++)
                   3010:      printf ("  %14.7g",  x[i] );
                   3011:      /* printf("  %8d: %14g\n", i, x[i]); */
                   3012:    printf ("\n" ); 
                   3013: }
                   3014: 
                   3015: static void print()            /* print a line of traces */
                   3016: {
                   3017:  
                   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);
                   3024:    vecprint("... current values of x ...", x, n);
                   3025: }
                   3026: /* static void print2(int n, double *x, int prin, double fx, int nf, int nl) */ /* print a line of traces */
                   3027: static void print2() /* print a line of traces */
                   3028: {
1.366     brouard  3029:   int i; /* double fmin=0.; */
1.359     brouard  3030: 
                   3031:    /* printf("\n"); */
                   3032:    /* printf("... chi square reduced to ... %20.10e\n", fx); */
                   3033:    /* printf("... after %u function calls ...\n", nf); */
                   3034:    /* printf("... including %u linear searches ...\n", nl); */
                   3035:    /* printf("%10d    %10d%14.7g",nl, nf, fx); */
1.363     brouard  3036:   /* printf ( "\n" ); */
1.359     brouard  3037:   printf ( "  Linear searches      %d", nl );
1.364     brouard  3038:   fprintf (ficlog, "  Linear searches      %d", nl );
1.359     brouard  3039:   /* printf ( "  Linear searches      %d\n", nl ); */
                   3040:   /* printf ( "  Function evaluations %d\n", nf ); */
                   3041:   /* printf ( "  Function value FX = %g\n", fx ); */
                   3042:   printf ( "  Function evaluations %d", nf );
                   3043:   printf ( "  Function value FX = %.12lf\n", fx );
1.363     brouard  3044:   fprintf (ficlog, "  Function evaluations %d", nf );
                   3045:   fprintf (ficlog, "  Function value FX = %.12lf\n", fx );
1.359     brouard  3046: #ifdef DEBUGPRAX
                   3047:    printf("n=%d prin=%d\n",n,prin);
                   3048: #endif
1.363     brouard  3049:    /* if(fx <= fmin) printf(" UNDEFINED "); else  printf("%14.7g",log(fx-fmin)); */
1.359     brouard  3050:    if ( n <= 4 || 2 < prin )
                   3051:    {
                   3052:      /* for(i=1;i<=n;i++)printf("%14.7g",x[i-1]); */
1.363     brouard  3053:      for(i=1;i<=n;i++){
1.364     brouard  3054:        printf(" %14.7g",x[i]);
                   3055:        fprintf(ficlog," %14.7g",x[i]);
1.363     brouard  3056:      }
1.359     brouard  3057:      /* r8vec_print ( n, x, "  X:" ); */
                   3058:    }
                   3059:    printf("\n");
1.363     brouard  3060:    fprintf(ficlog,"\n");
1.359     brouard  3061:  }
                   3062: 
                   3063: 
                   3064: /* #ifdef MSDOS */
                   3065: /* static double tflin[N]; */
                   3066: /* #endif */
                   3067: 
                   3068: static double flin(double l, int j)
                   3069: /* double l; */
                   3070: {
                   3071:    int i;
                   3072:    /* #ifndef MSDOS */
                   3073:    /*    double tflin[N]; */
                   3074:    /* #endif    */
                   3075:    /* double *tflin; */ /* Be careful to put tflin on a vector n */
                   3076: 
                   3077:    /* j is used from 0 to n-1 and can be -1 for parabolic search */
                   3078: 
                   3079:    /* if (j != -1) {           /\* linear search *\/ */
                   3080:    if (j > 0) {                /* linear search */
                   3081:      /* for (i=0; i<n; i++){ */
                   3082:      for (i=1; i<=n; i++){
                   3083:           tflin[i] = x[i] + l *v[i][j];
                   3084: #ifdef DEBUGPRAX
                   3085:          /* 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); */
                   3086:          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);
                   3087: #endif
                   3088:      }
                   3089:    }
                   3090:    else {                      /* search along parabolic space curve */
                   3091:       qa = l*(l-qd1)/(qd0*(qd0+qd1));
                   3092:       qb = (l+qd0)*(qd1-l)/(qd0*qd1);
                   3093:       qc = l*(l+qd0)/(qd1*(qd0+qd1));
                   3094: #ifdef DEBUGPRAX      
                   3095:       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);
                   3096: #endif
                   3097:       /* for (i=0; i<n; i++){ */
                   3098:       for (i=1; i<=n; i++){
                   3099:           tflin[i] = qa*q0[i]+qb*x[i]+qc*q1[i];
                   3100: #ifdef DEBUGPRAX
                   3101:           /* 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]); */
                   3102:           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]);
                   3103: #endif
                   3104:       }
                   3105:    }
                   3106:    nf++;
                   3107: 
                   3108: #ifdef NR_SHIFT
                   3109:       return (*fun)((tflin-1), n);
                   3110: #else
                   3111:      /* return (*fun)(tflin, n);*/
                   3112:       return (*fun)(tflin);
                   3113: #endif
                   3114: }
                   3115: 
                   3116: void minny(int j, int nits, double *d2, double *x1, double f1, int fk)
                   3117: /* double *d2, *x1, f1; */
                   3118: {
                   3119: /* here j is from 0 to n-1 and can be -1 for parabolic search  */
                   3120:   /*      MINIMIZES F FROM X IN THE DIRECTION V(*,J) */
                   3121:           /*      UNLESS J<1, WHEN A QUADRATIC SEARCH IS DONE */
                   3122:           /*      IN THE PLANE DEFINED BY Q0, Q1 AND X. */
                   3123:           /*      D2 AN APPROXIMATION TO HALF F'' (OR ZERO), */
                   3124:           /*      X1 AN ESTIMATE OF DISTANCE TO MINIMUM, */
                   3125:           /*      RETURNED AS THE DISTANCE FOUND. */
                   3126:           /*       IF FK = TRUE THEN F1 IS FLIN(X1), OTHERWISE */
                   3127:           /*       X1 AND F1 ARE IGNORED ON ENTRY UNLESS FINAL */
                   3128:           /*       FX > F1. NITS CONTROLS THE NUMBER OF TIMES */
                   3129:           /*       AN ATTEMPT IS MADE TO HALVE THE INTERVAL. */
                   3130:           /* SIDE EFFECTS: USES AND ALTERS X, FX, NF, NL. */
                   3131:           /*       IF J < 1 USES VARIABLES Q... . */
                   3132:          /*       USES H, N, T, M2, M4, LDT, DMIN, MACHEPS; */
                   3133:    int k, i, dz;
                   3134:    double x2, xm, f0, f2, fm, d1, t2, sf1, sx1;
                   3135:    double s;
                   3136:    double macheps;
                   3137:    macheps=pow(16.0,-13.0);
                   3138:    sf1 = f1; sx1 = *x1;
                   3139:    k = 0; xm = 0.0; fm = f0 = fx; dz = *d2 < macheps;
                   3140:    /* h=1.0;*/ /* To be revised */
                   3141: #ifdef DEBUGPRAX
                   3142:    /* printf("min macheps=%14g h=%14g step=%14g t=%14g fx=%14g\n",macheps,h, step,t, fx);  */
                   3143:    /* Where is fx coming from */
                   3144:    printf("   min macheps=%14g h=%14g  t=%14g fx=%.9lf dirj=%d\n",macheps, h, t, fx, j);
                   3145:    matprint("  min vectors:",v,n,n);
                   3146: #endif
                   3147:    /* find step size */
                   3148:    s = 0.;
                   3149:    /* for (i=0; i<n; i++) s += x[i]*x[i]; */
                   3150:    for (i=1; i<=n; i++) s += x[i]*x[i];
                   3151:    s = sqrt(s);
                   3152:    if (dz)
                   3153:       t2 = m4*sqrt(fabs(fx)/dmin + s*ldt) + m2*ldt;
                   3154:    else
                   3155:       t2 = m4*sqrt(fabs(fx)/(*d2) + s*ldt) + m2*ldt;
                   3156:    s = s*m4 + t;
                   3157:    if (dz && t2 > s) t2 = s;
                   3158:    if (t2 < small_windows) t2 = small_windows;
                   3159:    if (t2 > 0.01*h) t2 = 0.01 * h;
                   3160:    if (fk && f1 <= fm) {
                   3161:       xm = *x1;
                   3162:       fm = f1;
                   3163:    }
                   3164: #ifdef DEBUGPRAX
                   3165:    printf("   additional flin X1=%14.7f t2=%14.7f *f1=%14.7f fm=%14.7f fk=%d\n",*x1,t2,f1,fm,fk);
                   3166: #endif   
                   3167:    if (!fk || fabs(*x1) < t2) {
                   3168:      *x1 = (*x1 >= 0 ? t2 : -t2); 
                   3169:       /* *x1 = (*x1 > 0 ? t2 : -t2); */ /* kind of error */
                   3170: #ifdef DEBUGPRAX
                   3171:      printf("    additional flin X1=%16.10e dirj=%d fk=%d\n",*x1, j, fk);
                   3172: #endif
                   3173:       f1 = flin(*x1, j);
                   3174: #ifdef DEBUGPRAX
                   3175:     printf("    after flin f1=%18.12e dirj=%d fk=%d\n",f1, j,fk);
                   3176: #endif
                   3177:    }
                   3178:    if (f1 <= fm) {
                   3179:       xm = *x1;
                   3180:       fm = f1;
                   3181:    }
                   3182: L0: /*L0 loop or next */
                   3183: /*
                   3184:   Evaluate FLIN at another point and estimate the second derivative.
                   3185: */
                   3186:    if (dz) {
                   3187:       x2 = (f0 < f1 ? -(*x1) : 2*(*x1));
                   3188: #ifdef DEBUGPRAX
                   3189:       printf("     additional second flin x2=%14.8e x1=%14.8e f0=%14.8e f1=%18.12e dirj=%d\n",x2,*x1,f0,f1,j);
                   3190: #endif
                   3191:       f2 = flin(x2, j);
                   3192: #ifdef DEBUGPRAX
                   3193:       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);
                   3194: #endif
                   3195:       if (f2 <= fm) {
                   3196:          xm = x2;
                   3197:         fm = f2;
                   3198:       }
                   3199:       /* d2 is the curvature or double difference f1 doesn't seem to be accurately computed */
                   3200:       *d2 = (x2*(f1-f0) - (*x1)*(f2-f0))/((*x1)*x2*((*x1)-x2));
                   3201: #ifdef DEBUGPRAX
                   3202:       double d11,d12;
                   3203:       d11=(f1-f0)/(*x1);d12=(f2-f0)/x2;
                   3204:       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)));
                   3205:       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);
                   3206:       double ff1=7.783920622852e+04;
                   3207:       double f1mf0=9.0344736236e-05;
                   3208:       *d2 = (f1mf0)/ (*x1)/((*x1)-x2) - (f2-f0)/x2/((*x1)-x2);
                   3209:       /* *d2 = (ff1-f0)/ (*x1)/((*x1)-x2) - (f2-f0)/x2/((*x1)-x2); */
                   3210:       printf(" simpliff computing *d2=%16.10e f1mf0=%18.12e,f1=f0+f1mf0=%18.12e\n",*d2,f1mf0,f0+f1mf0);
                   3211:       *d2 = ((f1-f0)/ (*x1) - (f2-f0)/x2)/((*x1)-x2);
                   3212:       printf(" overlifi computing *d2=%16.10e\n",*d2);
                   3213: #endif
                   3214:       *d2 = ((f1-f0)/ (*x1) - (f2-f0)/x2)/((*x1)-x2);      
                   3215:    }
                   3216: #ifdef DEBUGPRAX
                   3217:       printf("    additional second flin xm=%14.8e fm=%14.8e *d2=%14.8e\n",xm, fm,*d2);
                   3218: #endif
                   3219:    /*
                   3220:      Estimate the first derivative at 0.
                   3221:    */
                   3222:    d1 = (f1-f0)/(*x1) - *x1**d2; dz = 1;
                   3223:    /*
                   3224:       Predict the minimum.
                   3225:     */
                   3226:    if (*d2 <= small_windows) {
                   3227:      x2 = (d1 < 0 ? h : -h);
                   3228:    }
                   3229:    else {
                   3230:       x2 = - 0.5*d1/(*d2);
                   3231:    }
                   3232: #ifdef DEBUGPRAX
                   3233:     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);
                   3234: #endif
                   3235:     if (fabs(x2) > h)
                   3236:       x2 = (x2 > 0 ? h : -h);
                   3237: L1:  /* L1 or try loop */
                   3238: #ifdef DEBUGPRAX
                   3239:     printf("   AT predicted minimum flin x2=%14.8e x1=%14.8e K=%14d NITS=%14d dirj=%d\n",x2,*x1,k,nits,j);
                   3240: #endif
                   3241:    f2 = flin(x2, j); /* x[i]+x2*v[i][j] */
                   3242: #ifdef DEBUGPRAX
                   3243:    printf("   after flin f0=%14.8e f1=%14.8e f2=%14.8e fm=%14.8e\n",f0,f1,f2, fm);
                   3244: #endif
                   3245:    if ((k < nits) && (f2 > f0)) {
                   3246: #ifdef DEBUGPRAX
                   3247:      printf("  NO SUCCESS SO TRY AGAIN;\n");
                   3248: #endif
                   3249:      k++;
                   3250:      if ((f0 < f1) && (*x1*x2 > 0.0))
                   3251:        goto L0; /* or next */
                   3252:      x2 *= 0.5;
                   3253:      goto L1;
                   3254:    }
                   3255:    nl++;
                   3256: #ifdef DEBUGPRAX
                   3257:    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);
                   3258: #endif
                   3259:    if (f2 > fm) x2 = xm; else fm = f2;
                   3260:    if (fabs(x2*(x2-*x1)) > small_windows) {
                   3261:       *d2 = (x2*(f1-f0) - *x1*(fm-f0))/(*x1*x2*(*x1-x2));
                   3262:    }
                   3263:    else {
                   3264:       if (k > 0) *d2 = 0;
                   3265:    }
                   3266: #ifdef DEBUGPRAX
1.362     brouard  3267:    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  3268: #endif
                   3269:    if (*d2 <= small_windows) *d2 = small_windows;
                   3270:    *x1 = x2; fx = fm;
                   3271:    if (sf1 < fx) {
                   3272:       fx = sf1;
                   3273:       *x1 = sx1;
                   3274:    }
                   3275:   /*
                   3276:     Update X for linear search.
                   3277:   */
                   3278: #ifdef DEBUGPRAX
                   3279:    printf("  end of min x1=%14.8e fx=%14.8e d2=%14.8e\n",*x1, fx, *d2);
                   3280: #endif
                   3281:    
                   3282:    /* if (j != -1) */
                   3283:    /*    for (i=0; i<n; i++) */
                   3284:    /*        x[i] += (*x1)*v[i][j]; */
                   3285:    if (j > 0)
                   3286:       for (i=1; i<=n; i++)
                   3287:           x[i] += (*x1)*v[i][j];
                   3288: }
                   3289: 
                   3290: void quad()    /* look for a minimum along the curve q0, q1, q2        */
                   3291: {
                   3292:    int i;
                   3293:    double l, s;
                   3294: 
                   3295:    s = fx; fx = qf1; qf1 = s; qd1 = 0.0;
                   3296:    /* for (i=0; i<n; i++) { */
                   3297:    for (i=1; i<=n; i++) {
                   3298:        s = x[i]; l = q1[i]; x[i] = l; q1[i] = s;
                   3299:        qd1 = qd1 + (s-l)*(s-l);
                   3300:    }
                   3301:    s = 0.0; qd1 = sqrt(qd1); l = qd1;
                   3302: #ifdef DEBUGPRAX
                   3303:   printf("  QUAD after sqrt qd1=%14.8e \n",qd1);
                   3304: #endif
                   3305:  
                   3306:    if (qd0>0.0 && qd1>0.0 &&nl>=3*n*n) {
                   3307: #ifdef DEBUGPRAX
                   3308:      printf(" QUAD before min value=%14.8e \n",qf1);
                   3309: #endif
                   3310:       /* min(-1, 2, &s, &l, qf1, 1); */
                   3311:       minny(0, 2, &s, &l, qf1, 1);
                   3312:       qa = l*(l-qd1)/(qd0*(qd0+qd1));
                   3313:       qb = (l+qd0)*(qd1-l)/(qd0*qd1);
                   3314:       qc = l*(l+qd0)/(qd1*(qd0+qd1));
                   3315:    }
                   3316:    else {
                   3317:       fx = qf1; qa = qb = 0.0; qc = 1.0;
                   3318:    }
                   3319: #ifdef DEBUGPRAX
                   3320:   printf("after eventual min qd0=%14.8e qd1=%14.8e nl=%d\n",qd0, qd1,nl);
                   3321: #endif
                   3322:    qd0 = qd1;
                   3323:    /* for (i=0; i<n; i++) { */
                   3324:    for (i=1; i<=n; i++) {
                   3325:        s = q0[i]; q0[i] = x[i];
                   3326:        x[i] = qa*s + qb*x[i] + qc*q1[i];
                   3327:    }
                   3328: #ifdef DEBUGQUAD
                   3329:    vecprint ( " X after QUAD:" , x, n );
                   3330: #endif
                   3331: }
                   3332: 
                   3333: /* void minfit(int n, double eps, double tol, double ab[N][N], double q[]) */
                   3334: void minfit(int n, double eps, double tol, double **ab, double q[])
                   3335: /* int n; */
                   3336: /* double eps, tol, ab[N][N], q[N]; */
                   3337: {
                   3338:    int l, kt, l2, i, j, k;
                   3339:    double c, f, g, h, s, x, y, z;
                   3340:    /* double eps; */
                   3341: /* #ifndef MSDOS */
                   3342: /*    double e[N];             /\* plenty of stack on a vax *\/ */
                   3343: /* #endif */
                   3344:    /* double *e; */
                   3345:    /* e=vector(0,n-1); /\* should be freed somewhere but gotos *\/ */
                   3346:    
                   3347:    /* householder's reduction to bidiagonal form */
                   3348: 
                   3349:    if(n==1){
                   3350:      /* q[1-1]=ab[1-1][1-1]; */
                   3351:      /* ab[1-1][1-1]=1.0; */
                   3352:      q[1]=ab[1][1];
                   3353:      ab[1][1]=1.0;
                   3354:      return; /* added from hardt */
                   3355:    }
                   3356:    /* eps=macheps; */ /* added */
                   3357:    x = g = 0.0;
                   3358: #ifdef DEBUGPRAX
                   3359:    matprint (" HOUSE holder:", ab, n, n);
                   3360: #endif
                   3361: 
                   3362:    /* for (i=0; i<n; i++) {  /\* FOR I := 1 UNTIL N DO *\/ */
                   3363:    for (i=1; i<=n; i++) {  /* FOR I := 1 UNTIL N DO */
                   3364:      e[i] = g; s = 0.0; l = i+1;
                   3365:      /* for (j=i; j<n; j++)  /\* FOR J := I UNTIL N DO S := S*AB(J,I)**2; *\/ /\* not correct *\/ */
                   3366:      for (j=i; j<=n; j++)  /* FOR J := I UNTIL N DO S := S*AB(J,I)**2; */ /* not correct */
                   3367:        s += ab[j][i] * ab[j][i];
                   3368: #ifdef DEBUGPRAXFIN
                   3369:      printf("i=%d s=%d %.7g tol=%.7g",i,s,tol);
                   3370: #endif
                   3371:      if (s < tol) {
                   3372:        g = 0.0;
                   3373:      }
                   3374:      else {
                   3375:        /* f = ab[i][i]; */
                   3376:        f = ab[i][i];
                   3377:        if (f < 0.0) 
                   3378:         g = sqrt(s);
                   3379:        else
                   3380:         g = -sqrt(s);
                   3381:        /* h = f*g - s; ab[i][i] = f - g; */
                   3382:        h = f*g - s; ab[i][i] = f - g;
                   3383:        /* for (j=l; j<n; j++) { */ /* FOR J := L UNTIL N DO */ /* wrong */
                   3384:        for (j=l; j<=n; j++) {
                   3385:         f = 0.0;
                   3386:         /* for (k=i; k<n; k++) /\* FOR K := I UNTIL N DO *\/ /\* wrong *\/ */
                   3387:         for (k=i; k<=n; k++) /* FOR K := I UNTIL N DO */
                   3388:           /* f += ab[k][i] * ab[k][j]; */
                   3389:           f += ab[k][i] * ab[k][j];
                   3390:         f /= h;
                   3391:         for (k=i; k<=n; k++) /* FOR K := I UNTIL N DO */
                   3392:           /* for (k=i; k<n; k++)/\* FOR K := I UNTIL N DO *\/ /\* wrong *\/ */
                   3393:           ab[k][j] += f * ab[k][i];
                   3394:         /* ab[k][j] += f * ab[k][i]; */
                   3395: #ifdef DEBUGPRAX
                   3396:         printf("Holder J=%d F=%.7g",j,f);
                   3397: #endif
                   3398:        }
                   3399:      } /* end s */
                   3400:      /* q[i] = g; s = 0.0; */
                   3401:      q[i] = g; s = 0.0;
                   3402: #ifdef DEBUGPRAX
                   3403:      printf(" I Q=%d %.7g",i,q[i]);
                   3404: #endif   
                   3405:        
                   3406:      /* if (i < n) */
                   3407:      /* if (i <= n)  /\* I is always lower or equal to n wasn't in golub reinsch*\/ */
                   3408:      /* for (j=l; j<n; j++) */
                   3409:      for (j=l; j<=n; j++)
                   3410:        s += ab[i][j] * ab[i][j];
                   3411:      /* s += ab[i][j] * ab[i][j]; */
                   3412:      if (s < tol) {
                   3413:        g = 0.0;
                   3414:      }
                   3415:      else {
                   3416:        if(i<n)
                   3417:         /* f = ab[i][i+1]; */ /* Brent golub overflow */
                   3418:         f = ab[i][i+1];
                   3419:        if (f < 0.0)
                   3420:         g = sqrt(s);
                   3421:        else 
                   3422:         g = - sqrt(s);
                   3423:        h = f*g - s;
                   3424:        /* h = f*g - s; ab[i][i+1] = f - g; */ /* Overflow for i=n Error in Golub too but not Burkardt*/
                   3425:        /* for (j=l; j<n; j++) */
                   3426:        /*     e[j] = ab[i][j]/h; */
                   3427:        if(i<n){
                   3428:         ab[i][i+1] = f - g;
                   3429:         for (j=l; j<=n; j++)
                   3430:           e[j] = ab[i][j]/h;
                   3431:         /* for (j=l; j<n; j++) { */
                   3432:         for (j=l; j<=n; j++) {
                   3433:           s = 0.0;
                   3434:           /* for (k=l; k<n; k++) s += ab[j][k]*ab[i][k]; */
                   3435:           for (k=l; k<=n; k++) s += ab[j][k]*ab[i][k];
                   3436:           /* for (k=l; k<n; k++) ab[j][k] += s * e[k]; */
                   3437:           for (k=l; k<=n; k++) ab[j][k] += s * e[k];
                   3438:         } /* END J */
                   3439:        } /* END i <n */
                   3440:      } /* end s */
                   3441:        /* y = fabs(q[i]) + fabs(e[i]); */
                   3442:      y = fabs(q[i]) + fabs(e[i]);
                   3443:      if (y > x) x = y;
                   3444: #ifdef DEBUGPRAX
                   3445:      printf(" I Y=%d %.7g",i,y);
                   3446: #endif
                   3447: #ifdef DEBUGPRAX
                   3448:      printf(" i=%d e(i) %.7g",i,e[i]);
                   3449: #endif
                   3450:    } /* end i */
                   3451:    /*
                   3452:      Accumulation of right hand transformations */
                   3453:    /* for (i=n-1; i >= 0; i--) { */ /* FOR I := N STEP -1 UNTIL 1 DO */
                   3454:    /* We should avoid the overflow in Golub */
                   3455:    /* ab[n-1][n-1] = 1.0; */
                   3456:    /* g = e[n-1]; */
                   3457:    ab[n][n] = 1.0;
                   3458:    g = e[n];
                   3459:    l = n;
                   3460: 
                   3461:    /* for (i=n; i >= 1; i--) { */
                   3462:    for (i=n-1; i >= 1; i--) { /* n-1 loops, different from brent and golub*/
                   3463:      if (g != 0.0) {
                   3464:        /* h = ab[i-1][i]*g; */
                   3465:        h = ab[i][i+1]*g;
                   3466:        for (j=l; j<=n; j++) ab[j][i] = ab[i][j] / h;
                   3467:        for (j=l; j<=n; j++) {
                   3468:         /* h = ab[i][i+1]*g; */
                   3469:         /* for (j=l; j<n; j++) ab[j][i] = ab[i][j] / h; */
                   3470:         /* for (j=l; j<n; j++) { */
                   3471:         s = 0.0;
                   3472:         /* for (k=l; k<n; k++) s += ab[i][k] * ab[k][j]; */
                   3473:         /* for (k=l; k<n; k++) ab[k][j] += s * ab[k][i]; */
                   3474:         for (k=l; k<=n; k++) s += ab[i][k] * ab[k][j];
                   3475:         for (k=l; k<=n; k++) ab[k][j] += s * ab[k][i];
                   3476:        }/* END J */
                   3477:      }/* END G */
                   3478:      /* for (j=l; j<n; j++) */
                   3479:      /*     ab[i][j] = ab[j][i] = 0.0; */
                   3480:      /* ab[i][i] = 1.0; g = e[i]; l = i; */
                   3481:      for (j=l; j<=n; j++)
                   3482:        ab[i][j] = ab[j][i] = 0.0;
                   3483:      ab[i][i] = 1.0; g = e[i]; l = i;
                   3484:    }/* END I */
                   3485: #ifdef DEBUGPRAX
                   3486:    matprint (" HOUSE accumulation:",ab,n, n );
                   3487: #endif
                   3488: 
                   3489:    /* diagonalization to bidiagonal form */
                   3490:    eps *= x;
                   3491:    /* for (k=n-1; k>= 0; k--) { */
                   3492:    for (k=n; k>= 1; k--) {
                   3493:      kt = 0;
                   3494: TestFsplitting:
                   3495: #ifdef DEBUGPRAX
                   3496:      printf(" TestFsplitting: k=%d kt=%d\n",k,kt);
                   3497:      /* for(i=1;i<=n;i++)printf(" e(%d)=%.14f",i,e[i]);printf("\n"); */
                   3498: #endif     
                   3499:      kt = kt+1; 
                   3500: /* TestFsplitting: */
                   3501:      /* if (++kt > 30) { */
                   3502:      if (kt > 30) { 
                   3503:        e[k] = 0.0;
                   3504:        fprintf(stderr, "\n+++ MINFIT - Fatal error\n");
                   3505:        fprintf ( stderr, "  The QR algorithm failed to converge.\n" );
                   3506:      }
                   3507:      /* for (l2=k; l2>=0; l2--) { */
                   3508:      for (l2=k; l2>=1; l2--) {
                   3509:        l = l2;
                   3510: #ifdef DEBUGPRAX
                   3511:        printf(" l e(l)< eps %d %.7g %.7g ",l,e[l], eps);
                   3512: #endif
                   3513:        /* if (fabs(e[l]) <= eps) */
                   3514:        if (fabs(e[l]) <= eps)
                   3515:         goto TestFconvergence;
                   3516:        /* if (fabs(q[l-1]) <= eps)*/ /* missing if ( 1 < l ){ *//* printf(" q(l-1)< eps %d %.7g %.7g ",l-1,q[l-2], eps); */
                   3517:        if (fabs(q[l-1]) <= eps)
                   3518:         break; /* goto Cancellation; */
                   3519:      }
                   3520:    Cancellation:
                   3521: #ifdef DEBUGPRAX
                   3522:      printf(" Cancellation:\n");
                   3523: #endif     
                   3524:      c = 0.0; s = 1.0;
                   3525:      for (i=l; i<=k; i++) {
                   3526:        f = s * e[i]; e[i] *= c;
                   3527:        /* f = s * e[i]; e[i] *= c; */
                   3528:        if (fabs(f) <= eps)
                   3529:         goto TestFconvergence;
                   3530:        /* g = q[i]; */
                   3531:        g = q[i];
                   3532:        if (fabs(f) < fabs(g)) {
                   3533:         double fg = f/g;
                   3534:         h = fabs(g)*sqrt(1.0+fg*fg);
                   3535:        }
                   3536:        else {
                   3537:         double gf = g/f;
                   3538:         h = (f!=0.0 ? fabs(f)*sqrt(1.0+gf*gf) : 0.0);
                   3539:        }
                   3540:        /*    COMMENT: THE ABOVE REPLACES Q(I):=H:=LONGSQRT(G*G+F*F) */
                   3541:        /* WHICH MAY GIVE INCORRECT RESULTS IF THE */
                   3542:        /* SQUARES UNDERFLOW OR IF F = G = 0; */
                   3543:        
                   3544:        /* q[i] = h; */
                   3545:        q[i] = h;
                   3546:        if (h == 0.0) { h = 1.0; g = 1.0; }
                   3547:        c = g/h; s = -f/h;
                   3548:      }
                   3549: TestFconvergence:
                   3550:  #ifdef DEBUGPRAX
                   3551:      printf(" TestFconvergence: l=%d k=%d\n",l,k);
                   3552: #endif     
                   3553:      /* z = q[k]; */
                   3554:      z = q[k];
                   3555:      if (l == k)
                   3556:        goto Convergence;
                   3557:      /* shift from bottom 2x2 minor */
                   3558:      /* x = q[l]; y = q[k-l]; g = e[k-1]; h = e[k]; */ /* Error */
                   3559:      x = q[l]; y = q[k-1]; g = e[k-1]; h = e[k];
                   3560:      f = ((y-z)*(y+z) + (g-h)*(g+h)) / (2.0*h*y);
                   3561:      g = sqrt(f*f+1.0);
                   3562:      if (f <= 0.0)
                   3563:        f = ((x-z)*(x+z) + h*(y/(f-g)-h))/x;
                   3564:      else
                   3565:        f = ((x-z)*(x+z) + h*(y/(f+g)-h))/x;
                   3566:      /* next qr transformation */
                   3567:      s = c = 1.0;
                   3568:      for (i=l+1; i<=k; i++) {
                   3569: #ifdef DEBUGPRAXQR
                   3570:        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]);
                   3571: #endif     
                   3572:        /* g = e[i]; y = q[i]; h = s*g; g *= c; */
                   3573:        g = e[i]; y = q[i]; h = s*g; g *= c;
                   3574:        if (fabs(f) < fabs(h)) {
                   3575:         double fh = f/h;
                   3576:         z = fabs(h) * sqrt(1.0 + fh*fh);
                   3577:        }
                   3578:        else {
                   3579:         double hf = h/f;
                   3580:         z = (f!=0.0 ? fabs(f)*sqrt(1.0+hf*hf) : 0.0);
                   3581:        }
                   3582:        /* e[i-1] = z; */
                   3583:        e[i-1] = z;
                   3584: #ifdef DEBUGPRAXQR
                   3585:        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]);
                   3586: #endif     
                   3587:        if (z == 0.0) 
                   3588:         f = z = 1.0;
                   3589:        c = f/z; s = h/z;
                   3590:        f = x*c + g*s; g = - x*s + g*c; h = y*s;
                   3591:        y *= c;
                   3592:        /* for (j=0; j<n; j++) { */
                   3593:        /*     x = ab[j][i-1]; z = ab[j][i]; */
                   3594:        /*     ab[j][i-1] = x*c + z*s; */
                   3595:        /*     ab[j][i] = - x*s + z*c; */
                   3596:        /* } */
                   3597:        for (j=1; j<=n; j++) {
                   3598:         x = ab[j][i-1]; z = ab[j][i];
                   3599:         ab[j][i-1] = x*c + z*s;
                   3600:         ab[j][i] = - x*s + z*c;
                   3601:        }
                   3602:        if (fabs(f) < fabs(h)) {
                   3603:         double fh = f/h;
                   3604:         z = fabs(h) * sqrt(1.0 + fh*fh);
                   3605:        }
                   3606:        else {
                   3607:         double hf = h/f;
                   3608:         z = (f!=0.0 ? fabs(f)*sqrt(1.0+hf*hf) : 0.0);
                   3609:        }
                   3610: #ifdef DEBUGPRAXQR
                   3611:        printf(" qr transformation z f h=%.7g %.7g %.7g i=%d k=%d\n",z,f,h, i, k);
                   3612: #endif
                   3613:        q[i-1] = z;
                   3614:        if (z == 0.0)
                   3615:         z = f = 1.0;
                   3616:        c = f/z; s = h/z;
                   3617:        f = c*g + s*y;  /* f can be very small */
                   3618:        x = - s*g + c*y;
                   3619:      }
                   3620:      /* e[l] = 0.0; e[k] = f; q[k] = x; */
                   3621:      e[l] = 0.0; e[k] = f; q[k] = x;
                   3622: #ifdef DEBUGPRAXQR
                   3623:      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);
                   3624: #endif
                   3625:      goto TestFsplitting;
                   3626:    Convergence:
                   3627: #ifdef DEBUGPRAX
                   3628:      printf(" Convergence:\n");
                   3629: #endif     
                   3630:      if (z < 0.0) {
                   3631:        /* q[k] = - z; */
                   3632:        /* for (j=0; j<n; j++) ab[j][k] = - ab[j][k]; */
                   3633:        q[k] = - z;
                   3634:        for (j=1; j<=n; j++) ab[j][k] = - ab[j][k];
                   3635:      }/* END Z */
                   3636:    }/* END K */
                   3637: } /* END MINFIT */
                   3638: 
                   3639: 
                   3640: double praxis(double tol, double macheps, double h0, int _n, int _prin, double *_x, double (*_fun)(double *_x))
                   3641: /* double praxis(double tol, double macheps, double h0, int _n, int _prin, double *_x, double (*_fun)(double *_x, int _n)) */
                   3642: /* double praxis(double (*_fun)(), double _x[], int _n) */
                   3643: /* double (*_fun)(); */
                   3644: /* double _x[N]; */
                   3645: /* double (*_fun)(); */
                   3646: /* double _x[N]; */
                   3647: {
                   3648:    /* init global extern variables and parameters */
                   3649:    /* double *d, *y, *z, */
                   3650:    /*   *q0, *q1, **v; */
                   3651:    /* double *tflin; /\* used in flin: return (*fun)(tflin, n); *\/ */
                   3652:    /* double *e; /\* used in minfit, don't konw how to free memory and thus made global *\/ */
                   3653: 
                   3654:   
                   3655:   int seed; /* added */
                   3656:   int biter=0;
                   3657:   double r;
                   3658:   double randbrent( int (*));
                   3659:   double s, sf;
                   3660:   
                   3661:    h = h0; /* step; */
                   3662:    t = tol;
                   3663:    scbd = 1.0;
                   3664:    illc = 0;
                   3665:    ktm = 1;
                   3666: 
                   3667:    macheps = DBL_EPSILON;
                   3668:    /* prin=4; */
                   3669: #ifdef DEBUGPRAX
                   3670:    printf("Praxis macheps=%14g h=%14g step=%14g tol=%14g\n",macheps,h, h0,tol); 
                   3671: #endif
                   3672:    n = _n;
                   3673:    x = _x;
                   3674:    prin = _prin;
                   3675:    fun = _fun;
                   3676:    d=vector(1, n);
                   3677:    y=vector(1, n);
                   3678:    z=vector(1, n);
                   3679:    q0=vector(1, n);
                   3680:    q1=vector(1, n);
                   3681:    e=vector(1, n);
                   3682:    tflin=vector(1, n);
                   3683:    v=matrix(1, n, 1, n);
                   3684:    for(i=1;i<=n;i++){d[i]=y[i]=z[i]=q0[0]=e[i]=tflin[i]=0.;}
                   3685:    small_windows = (macheps) * (macheps); vsmall = small_windows*small_windows;
                   3686:    large = 1.0/small_windows; vlarge = 1.0/vsmall;
                   3687:    m2 = sqrt(macheps); m4 = sqrt(m2);
                   3688:    seed = 123456789; /* added */
                   3689:    ldfac = (illc ? 0.1 : 0.01);
                   3690:    for(i=1;i<=n;i++) z[i]=0.; /* Was missing in Gegenfurtner as well as Brent's algol or fortran  */
                   3691:    nl = kt = 0; nf = 1;
                   3692: #ifdef NR_SHIFT
                   3693:    fx = (*fun)((x-1), n);
                   3694: #else
                   3695:    fx = (*fun)(x);
                   3696: #endif
                   3697:    qf1 = fx;
                   3698:    t2 = small_windows + fabs(t); t = t2; dmin = small_windows;
                   3699: #ifdef DEBUGPRAX
                   3700:    printf("praxis2 macheps=%14g h=%14g step=%14g small=%14g t=%14g\n",macheps,h, h0,small_windows, t); 
                   3701: #endif
                   3702:    if (h < 100.0*t) h = 100.0*t;
                   3703: #ifdef DEBUGPRAX
                   3704:    printf("praxis3 macheps=%14g h=%14g step=%14g small=%14g t=%14g\n",macheps,h, h0,small_windows, t); 
                   3705: #endif
                   3706:    ldt = h;
                   3707:    /* for (i=0; i<n; i++) for (j=0; j<n; j++) */
                   3708:    for (i=1; i<=n; i++) for (j=1; j<=n; j++)
                   3709:        v[i][j] = (i == j ? 1.0 : 0.0);
                   3710:    d[1] = 0.0; qd0 = 0.0;
                   3711:    /* for (i=0; i<n; i++) q1[i] = x[i]; */
                   3712:    for (i=1; i<=n; i++) q1[i] = x[i];
                   3713:    if (prin > 1) {
                   3714:       printf("\n------------- enter function praxis -----------\n");
                   3715:       printf("... current parameter settings ...\n");
                   3716:       printf("... scaling ... %20.10e\n", scbd);
                   3717:       printf("...   tol   ... %20.10e\n", t);
                   3718:       printf("... maxstep ... %20.10e\n", h);
                   3719:       printf("...   illc  ... %20u\n", illc);
                   3720:       printf("...   ktm   ... %20u\n", ktm);
                   3721:       printf("... maxfun  ... %20u\n", maxfun);
                   3722:    }
                   3723:    if (prin) print2();
                   3724: 
                   3725: mloop:
                   3726:     biter++;  /* Added to count the loops */
                   3727:    /* sf = d[0]; */
                   3728:    /* s = d[0] = 0.0; */
                   3729:     printf("\n Big iteration %d \n",biter);
                   3730:     fprintf(ficlog,"\n Big iteration %d \n",biter);
                   3731:     sf = d[1];
                   3732:    s = d[1] = 0.0;
                   3733: 
                   3734:    /* minimize along first direction V(*,1) */
                   3735: #ifdef DEBUGPRAX
                   3736:    printf("  Minimize along the first direction V(*,1). illc=%d\n",illc);
                   3737:    /* fprintf(ficlog,"  Minimize along the first direction V(*,1).\n"); */
                   3738: #endif
                   3739: #ifdef DEBUGPRAX2
                   3740:    printf("praxis4 macheps=%14g h=%14g step=%14g small=%14g t=%14g\n",macheps,h, h0,small_windows, t); 
                   3741: #endif
                   3742:    /* min(0, 2, &d[0], &s, fx, 0); /\* mac heps not global *\/ */
1.362     brouard  3743:    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  3744: #ifdef DEBUGPRAX
                   3745:    printf("praxis5 macheps=%14g h=%14g looks at sign of s=%14g fx=%14g\n",macheps,h, s,fx); 
                   3746: #endif
                   3747:    if (s <= 0.0)
                   3748:       /* for (i=0; i < n; i++) */
                   3749:       for (i=1; i <= n; i++)
                   3750:           v[i][1] = -v[i][1];
                   3751:    /* if ((sf <= (0.9 * d[0])) || ((0.9 * sf) >= d[0])) */
                   3752:    if ((sf <= (0.9 * d[1])) || ((0.9 * sf) >= d[1]))
                   3753:       /* for (i=1; i<n; i++) */
                   3754:       for (i=2; i<=n; i++)
                   3755:           d[i] = 0.0;
                   3756:    /* for (k=1; k<n; k++) { */
                   3757:    for (k=2; k<=n; k++) {
                   3758:     /*
                   3759:       The inner loop starts here.
                   3760:     */
                   3761: #ifdef DEBUGPRAX
                   3762:       printf("      The inner loop  here from k=%d to n=%d.\n",k,n);
                   3763:       /* fprintf(ficlog,"      The inner loop  here from k=%d to n=%d.\n",k,n); */
                   3764: #endif
                   3765:        /* for (i=0; i<n; i++) */
                   3766:        for (i=1; i<=n; i++)
                   3767:            y[i] = x[i];
                   3768:        sf = fx;
                   3769: #ifdef DEBUGPRAX
                   3770:        printf(" illc=%d and kt=%d and ktm=%d\n", illc, kt, ktm);
                   3771: #endif
                   3772:        illc = illc || (kt > 0);
                   3773: next:
                   3774:        kl = k;
                   3775:        df = 0.0;
                   3776:        if (illc) {        /* random step to get off resolution valley */
                   3777: #ifdef DEBUGPRAX
                   3778:          printf("  A random step follows, to avoid resolution valleys.\n");
                   3779:          matprint("  before rand, vectors:",v,n,n);
                   3780: #endif
                   3781:           for (i=1; i<=n; i++) {
                   3782: #ifdef NOBRENTRAND
                   3783:            r = drandom();
                   3784: #else
                   3785:            seed=i;
                   3786:            /* seed=i+1; */
                   3787: #ifdef DEBUGRAND
                   3788:            printf(" Random seed=%d, brent i=%d",seed,i); /* YYYY i=5 j=1 vji= -0.0001170073 */
                   3789: #endif
                   3790:            r = randbrent ( &seed );
                   3791: #endif
                   3792: #ifdef DEBUGRAND
                   3793:            printf(" Random r=%.7g \n",r);
                   3794: #endif     
                   3795:             z[i] = (0.1 * ldt + t2 * pow(10.0,(double)kt)) * (r - 0.5);
                   3796:            /* z[i] = (0.1 * ldt + t2 * pow(10.0,(double)kt)) * (drandom() - 0.5); */
                   3797: 
                   3798:            s = z[i];
                   3799:               for (j=1; j <= n; j++)
                   3800:                   x[j] += s * v[j][i];
                   3801:          }
                   3802: #ifdef DEBUGRAND
                   3803:          matprint("  after rand, vectors:",v,n,n);
                   3804: #endif
                   3805: #ifdef NR_SHIFT
                   3806:           fx = (*fun)((x-1), n);
                   3807: #else
1.366     brouard  3808:           fx = (*fun)(x);
1.359     brouard  3809: #endif
                   3810:           /* fx = (*func) ( (x-1) ); *//* This for func which is computed from x[1] and not from x[0] xm1=(x-1)*/
                   3811:           nf++;
                   3812:        }
                   3813:        /* minimize along non-conjugate directions */
                   3814: #ifdef DEBUGPRAX
                   3815:        printf(" Minimize along the 'non-conjugate' directions (dots printed) V(*,%d),...,V(*,%d).\n",k,n);
                   3816:        /* fprintf(ficlog," Minimize along the 'non-conjugate' directions  (dots printed) V(*,%d),...,V(*,%d).\n",k,n); */
                   3817: #endif
                   3818:        /* for (k2=k; k2<n; k2++) {  /\* Be careful here k2 <=n ? *\/ */
                   3819:        for (k2=k; k2<=n; k2++) {  /* Be careful here k2 <=n ? */
                   3820:            sl = fx;
                   3821:            s = 0.0;
                   3822: #ifdef DEBUGPRAX
                   3823:           printf(" Minimize along the 'NON-CONJUGATE' true direction k2=%14d fx=%14.7f\n",k2, fx);
                   3824:    matprint("  before min vectors:",v,n,n);
                   3825: #endif
                   3826:            /* min(k2, 2, &d[k2], &s, fx, 0); */
                   3827:    /*    jsearch=k2-1; */
                   3828:    /* min(jsearch, 2, &d[jsearch], &s, fx, 0); */
                   3829:    minny(k2, 2, &d[k2], &s, fx, 0);
                   3830: #ifdef DEBUGPRAX
                   3831:           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);
                   3832: #endif
                   3833:           if (illc) {
                   3834:              /* double szk = s + z[k2]; */
                   3835:               /* s = d[k2] * szk*szk; */
                   3836:              double szk = s + z[k2];
                   3837:               s = d[k2] * szk*szk;
                   3838:           }
                   3839:            else 
                   3840:              s = sl - fx;
                   3841:            /* if (df < s) { */
                   3842:            if (df <= s) {
                   3843:               df = s;
                   3844:               kl = k2;
                   3845: #ifdef DEBUGPRAX
                   3846:            printf(" df=%.7g and choose kl=%d \n",df,kl); /* UUUU */
                   3847: #endif
                   3848:            }
                   3849:        } /* end loop k2 */
                   3850:         /*
                   3851:          If there was not much improvement on the first try, set
                   3852:          ILLC = true and start the inner loop again.
                   3853:        */
                   3854: #ifdef DEBUGPRAX
                   3855:        printf(" If there was not much improvement on the first try, set ILLC = true and start the inner loop again. illc=%d\n",illc);
                   3856:        /* fprintf(ficlog,"  If there was not much improvement on the first try, set ILLC = true and start the inner loop again.\n"); */
                   3857: #endif
                   3858:         if (!illc && (df < fabs(100.0 * (macheps) * fx))) {
                   3859: #ifdef DEBUGPRAX
                   3860:          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);         
                   3861: #endif
                   3862:           illc = 1;
                   3863:           goto next;
                   3864:        }
                   3865: #ifdef DEBUGPRAX
                   3866:        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);
                   3867: #endif
                   3868:        
                   3869:        /* if ((k == 1) && (prin > 1)){ /\* be careful k=2 *\/ */
                   3870:        if ((k == 2) && (prin > 1)){ /* be careful k=2 */
                   3871: #ifdef DEBUGPRAX
                   3872:         printf("  NEW D The second difference array d:\n" );
                   3873:         /* fprintf(ficlog, " NEW D The second difference array d:\n" ); */
                   3874: #endif
                   3875:         vecprint(" NEW D The second difference array d:",d,n);
                   3876:        }
                   3877:        /* minimize along conjugate directions */ 
                   3878:        /*
                   3879:         Minimize along the "conjugate" directions V(*,1),...,V(*,K-1).
                   3880:        */
                   3881: #ifdef DEBUGPRAX
                   3882:       printf("Minimize along the 'conjugate' directions V(*,1),...,V(*,K-1=%d).\n",k-1);
                   3883:       /* fprintf(ficlog,"Minimize along the 'conjugate' directions V(*,1),...,V(*,K-1=%d).\n",k-1); */
                   3884: #endif
                   3885:       /* for (k2=0; k2<=k-1; k2++) { */
                   3886:       for (k2=1; k2<=k-1; k2++) {
                   3887:            s = 0.0;
                   3888:            /* min(k2-1, 2, &d[k2-1], &s, fx, 0); */
                   3889:            minny(k2, 2, &d[k2], &s, fx, 0);
                   3890:        }
                   3891:        f1 = fx;
                   3892:        fx = sf;
                   3893:        lds = 0.0;
                   3894:        /* for (i=0; i<n; i++) { */
                   3895:        for (i=1; i<=n; i++) {
                   3896:            sl = x[i];
                   3897:            x[i] = y[i];
                   3898:            y[i] = sl - y[i];
                   3899:            sl = y[i];
                   3900:            lds = lds + sl*sl;
                   3901:        }
                   3902:        lds = sqrt(lds);
                   3903: #ifdef DEBUGPRAX
                   3904:        printf("Minimization done 'conjugate', shifted all points, computed lds=%.8f\n",lds);
                   3905: #endif      
                   3906:       /*
                   3907:        Discard direction V(*,kl).
                   3908:        
                   3909:        If no random step was taken, V(*,KL) is the "non-conjugate"
                   3910:        direction along which the greatest improvement was made.
                   3911:       */
                   3912:        if (lds > small_windows) {
                   3913: #ifdef DEBUGPRAX
                   3914:        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);
                   3915:         matprint("  before shift new conjugate vectors:",v,n,n);
                   3916: #endif
                   3917:         for (i=kl-1; i>=k; i--) {
                   3918:           /* for (j=0; j < n; j++) */
                   3919:           for (j=1; j <= n; j++)
                   3920:             /* v[j][i+1] = v[j][i]; */ /* This is v[j][i+1]=v[j][i] i=kl-1 to k */
                   3921:             v[j][i+1] = v[j][i]; /* This is v[j][i+1]=v[j][i] i=kl-1 to k */
                   3922:           /* v[j][i+1] = v[j][i]; */
                   3923:           /* d[i+1] = d[i];*/  /* last  is d[k+1]= d[k] */
                   3924:           d[i+1] = d[i];  /* last  is d[k]= d[k-1] */
                   3925:         }
                   3926: #ifdef DEBUGPRAX
                   3927:         matprint("  after shift new conjugate vectors:",v,n,n);         
                   3928: #endif  /* d[k] = 0.0; */
                   3929:         d[k] = 0.0;
                   3930:         for (i=1; i <= n; i++)
                   3931:           v[i][k] = y[i] / lds;
                   3932:         /* v[i][k] = y[i] / lds; */
                   3933: #ifdef DEBUGPRAX
                   3934:         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);
                   3935:         /* fprintf(ficlog,"Minimize along the new 'conjugate' direction V(*,k=%d), which is the normalized vector:  (new x) - (old x).\n",k); */
                   3936:     matprint("  before min new conjugate vectors:",v,n,n);      
                   3937: #endif
                   3938:         /* min(k-1, 4, &d[k-1], &lds, f1, 1); */
                   3939:         minny(k, 4, &d[k], &lds, f1, 1);
                   3940: #ifdef DEBUGPRAX
                   3941:         printf(" after min d(k)=%d %.7g lds=%14f\n",k,d[k],lds);
                   3942:    matprint("  after min vectors:",v,n,n);
                   3943: #endif
                   3944:         if (lds <= 0.0) {
                   3945:           lds = -lds;
                   3946: #ifdef DEBUGPRAX
                   3947:          printf(" lds changed sign lds=%.14f k=%d\n",lds,k);
                   3948: #endif    
                   3949:           /* for (i=0; i<n; i++) */
                   3950:           /*   v[i][k] = -v[i][k]; */
                   3951:           for (i=1; i<=n; i++)
                   3952:             v[i][k] = -v[i][k];
                   3953:         }
                   3954:        }
                   3955:        ldt = ldfac * ldt;
                   3956:        if (ldt < lds)
                   3957:           ldt = lds;
                   3958:        if (prin > 0){
                   3959: #ifdef DEBUGPRAX
                   3960:        printf(" k=%d",k);
                   3961:        /* fprintf(ficlog," k=%d",k); */
                   3962: #endif
                   3963:        print2();/* n, x, prin, fx, nf, nl ); */
                   3964:        }
                   3965:        t2 = 0.0;
                   3966:        /* for (i=0; i<n; i++) */
                   3967:        for (i=1; i<=n; i++)
                   3968:            t2 += x[i]*x[i];
                   3969:        t2 = m2 * sqrt(t2) + t;
                   3970:        /*
                   3971:        See whether the length of the step taken since starting the
                   3972:        inner loop exceeds half the tolerance.
                   3973:       */
                   3974: #ifdef DEBUGPRAX
                   3975:        printf("See if step length exceeds half the tolerance.\n"); /* ZZZZZ */
                   3976:       /* fprintf(ficlog,"See if step length exceeds half the tolerance.\n"); */
                   3977: #endif
                   3978:        if (ldt > (0.5 * t2))
                   3979:           kt = 0;
                   3980:        else 
                   3981:          kt++;
                   3982: #ifdef DEBUGPRAX
                   3983:        printf("if kt=%d >? ktm=%d gotoL2 loop\n",kt,ktm);
                   3984: #endif
                   3985:        if (kt > ktm){
                   3986:          if ( 0 < prin ){
                   3987:           /* printf("\nr8vec_print\n X:\n"); */
                   3988:           /* fprintf(ficlog,"\nr8vec_print\n X:\n"); */
                   3989:           vecprint ("END  X:", x, n );
                   3990:         }
                   3991:            goto fret;
                   3992:        }
                   3993: #ifdef DEBUGPRAX
                   3994:    matprint("  end of L2 loop vectors:",v,n,n);
                   3995: #endif
                   3996:        
                   3997:    }
                   3998:    /* printf("The inner loop ends here.\n"); */
                   3999:    /* fprintf(ficlog,"The inner loop ends here.\n"); */
                   4000:    /*
                   4001:      The inner loop ends here.
                   4002:      
                   4003:      Try quadratic extrapolation in case we are in a curved valley.
                   4004:    */
                   4005: #ifdef DEBUGPRAX
                   4006:    printf("Try QUAD ratic extrapolation in case we are in a curved valley.\n");
                   4007: #endif
                   4008:    /*  try quadratic extrapolation in case    */
                   4009:    /*  we are stuck in a curved valley        */
                   4010:    quad();
                   4011:    dn = 0.0;
                   4012:    /* for (i=0; i<n; i++) { */
                   4013:    for (i=1; i<=n; i++) {
                   4014:        d[i] = 1.0 / sqrt(d[i]);
                   4015:        if (dn < d[i])
                   4016:           dn = d[i];
                   4017:    }
                   4018:    if (prin > 2)
                   4019:      matprint("  NEW DIRECTIONS vectors:",v,n,n);
                   4020:    /* for (j=0; j<n; j++) { */
                   4021:    for (j=1; j<=n; j++) {
                   4022:        s = d[j] / dn;
                   4023:        /* for (i=0; i < n; i++) */
                   4024:        for (i=1; i <= n; i++)
                   4025:            v[i][j] *= s;
                   4026:    }
                   4027:    
                   4028:    if (scbd > 1.0) {       /* scale axis to reduce condition number */
                   4029: #ifdef DEBUGPRAX
                   4030:      printf("Scale the axes to try to reduce the condition number.\n");
                   4031: #endif
                   4032:      /* fprintf(ficlog,"Scale the axes to try to reduce the condition number.\n"); */
                   4033:       s = vlarge;
                   4034:       /* for (i=0; i<n; i++) { */
                   4035:       for (i=1; i<=n; i++) {
                   4036:           sl = 0.0;
                   4037:           /* for (j=0; j < n; j++) */
                   4038:           for (j=1; j <= n; j++)
                   4039:               sl += v[i][j]*v[i][j];
                   4040:           z[i] = sqrt(sl);
                   4041:           if (z[i] < m4)
                   4042:              z[i] = m4;
                   4043:           if (s > z[i])
                   4044:              s = z[i];
                   4045:       }
                   4046:       /* for (i=0; i<n; i++) { */
                   4047:       for (i=1; i<=n; i++) {
                   4048:           sl = s / z[i];
                   4049:           z[i] = 1.0 / sl;
                   4050:           if (z[i] > scbd) {
                   4051:              sl = 1.0 / scbd;
                   4052:              z[i] = scbd;
                   4053:           }
                   4054:       }
                   4055:    }
                   4056:    for (i=1; i<=n; i++)
                   4057:        /* for (j=0; j<=i-1; j++) { */
                   4058:        /* for (j=1; j<=i; j++) { */
                   4059:        for (j=1; j<=i-1; j++) {
                   4060:            s = v[i][j];
                   4061:            v[i][j] = v[j][i];
                   4062:            v[j][i] = s;
                   4063:        }
                   4064: #ifdef DEBUGPRAX
                   4065:     printf(" Calculate a new set of orthogonal directions before repeating  the main loop.\n  Transpose V for MINFIT:...\n");
                   4066: #endif
                   4067:       /*
                   4068:       MINFIT finds the singular value decomposition of V.
                   4069: 
                   4070:       This gives the principal values and principal directions of the
                   4071:       approximating quadratic form without squaring the condition number.
                   4072:     */
                   4073:  #ifdef DEBUGPRAX
                   4074:     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");
                   4075: #endif
                   4076: 
                   4077:    minfit(n, macheps, vsmall, v, d);
                   4078:     /* for(i=0; i<n;i++)printf(" %14.7g",d[i]); */
                   4079:     /* v is overwritten with R. */
                   4080:     /*
                   4081:       Unscale the axes.
                   4082:     */
                   4083:    if (scbd > 1.0) {
                   4084: #ifdef DEBUGPRAX
                   4085:       printf(" Unscale the axes.\n");
                   4086: #endif
                   4087:       /* for (i=0; i<n; i++) { */
                   4088:       for (i=1; i<=n; i++) {
                   4089:           s = z[i];
                   4090:           /* for (j=0; j<n; j++) */
                   4091:           for (j=1; j<=n; j++)
                   4092:               v[i][j] *= s;
                   4093:       }
                   4094:       /* for (i=0; i<n; i++) { */
                   4095:       for (i=1; i<=n; i++) {
                   4096:           s = 0.0;
                   4097:           /* for (j=0; j<n; j++) */
                   4098:           for (j=1; j<=n; j++)
                   4099:               s += v[j][i]*v[j][i];
                   4100:           s = sqrt(s);
                   4101:           d[i] *= s;
                   4102:           s = 1.0 / s;
                   4103:           /* for (j=0; j<n; j++) */
                   4104:           for (j=1; j<=n; j++)
                   4105:               v[j][i] *= s;
                   4106:       }
                   4107:    }
                   4108:    /* for (i=0; i<n; i++) { */
                   4109:    double dni; /* added for compatibility with buckhardt but not brent */
                   4110:    for (i=1; i<=n; i++) {
                   4111:      dni=dn*d[i]; /* added for compatibility with buckhardt but not brent */
                   4112:        if ((dn * d[i]) > large)
                   4113:           d[i] = vsmall;
                   4114:        else if ((dn * d[i]) < small_windows)
                   4115:           d[i] = vlarge;
                   4116:        else 
                   4117:         d[i] = 1.0 / dni / dni; /* added for compatibility with buckhardt but not brent */
                   4118:           /* d[i] = pow(dn * d[i],-2.0); */
                   4119:    }
                   4120: #ifdef DEBUGPRAX
                   4121:    vecprint ("\n Before sort Eigenvalues of a:",d,n );
                   4122: #endif
                   4123:    
                   4124:    sort();               /* the new eigenvalues and eigenvectors */
                   4125: #ifdef DEBUGPRAX
                   4126:    vecprint( " After sort the eigenvalues ....\n", d, n);
                   4127:    matprint( " After sort the eigenvectors....\n", v, n,n);
                   4128: #endif
                   4129: #ifdef DEBUGPRAX
                   4130:     printf("  Determine the smallest eigenvalue.\n");
                   4131: #endif
                   4132:    /* dmin = d[n-1]; */
                   4133:    dmin = d[n];
                   4134:    if (dmin < small_windows)
                   4135:       dmin = small_windows;
                   4136:     /*
                   4137:      The ratio of the smallest to largest eigenvalue determines whether
                   4138:      the system is ill conditioned.
                   4139:    */
                   4140:   
                   4141:    /* illc = (m2 * d[0]) > dmin; */
                   4142:    illc = (m2 * d[1]) > dmin;
                   4143: #ifdef DEBUGPRAX
                   4144:     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]);
                   4145: #endif
                   4146:    
                   4147:    if ((prin > 2) && (scbd > 1.0))
                   4148:       vecprint("\n The scale factors:",z,n);
                   4149:    if (prin > 2)
                   4150:       vecprint("  Principal values (EIGEN VALUES OF A) of the quadratic form:",d,n);
                   4151:    if (prin > 2)
                   4152:      matprint("  The principal axes (EIGEN VECTORS OF A:",v,n, n);
                   4153: 
                   4154:    if ((maxfun > 0) && (nf > maxfun)) {
                   4155:       if (prin)
                   4156:         printf("\n... maximum number of function calls reached ...\n");
                   4157:       goto fret;
                   4158:    }
                   4159: #ifdef DEBUGPRAX
                   4160:    printf("Goto main loop\n");
                   4161: #endif
                   4162:    goto mloop;          /* back to main loop */
                   4163: 
                   4164: fret:
                   4165:    if (prin > 0) {
                   4166:          vecprint("\n  X:", x, n);
                   4167:          /* printf("\n... ChiSq reduced to %20.10e ...\n", fx); */
                   4168:         /* printf("... after %20u function calls.\n", nf); */
                   4169:    }
                   4170:    free_vector(d, 1, n);
                   4171:    free_vector(y, 1, n);
                   4172:    free_vector(z, 1, n);
                   4173:    free_vector(q0, 1, n);
                   4174:    free_vector(q1, 1, n);
                   4175:    free_matrix(v, 1, n, 1, n);
                   4176:    /*   double *d, *y, *z, */
                   4177:    /* *q0, *q1, **v; */
                   4178:    free_vector(tflin, 1, n);
                   4179:    /* double *tflin; /\* used in flin: return (*fun)(tflin, n); *\/ */
                   4180:    free_vector(e, 1, n);
                   4181:    /* double *e; /\* used in minfit, don't konw how to free memory and thus made global *\/ */
                   4182:    
                   4183:    return(fx);
                   4184: }
                   4185: 
                   4186: /* end praxis gegen */
1.126     brouard  4187: 
                   4188: /*************** powell ************************/
1.162     brouard  4189: /*
1.317     brouard  4190: Minimization of a function func of n variables. Input consists in an initial starting point
                   4191: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   4192: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   4193: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  4194: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   4195: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   4196:  */
1.224     brouard  4197: #ifdef LINMINORIGINAL
                   4198: #else
                   4199:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  4200:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  4201: #endif
1.126     brouard  4202: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   4203:            double (*func)(double [])) 
                   4204: { 
1.224     brouard  4205: #ifdef LINMINORIGINAL
                   4206:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  4207:              double (*func)(double [])); 
1.224     brouard  4208: #else 
1.241     brouard  4209:  void linmin(double p[], double xi[], int n, double *fret,
                   4210:             double (*func)(double []),int *flat); 
1.224     brouard  4211: #endif
1.239     brouard  4212:  int i,ibig,j,jk,k; 
1.126     brouard  4213:   double del,t,*pt,*ptt,*xit;
1.181     brouard  4214:   double directest;
1.126     brouard  4215:   double fp,fptt;
                   4216:   double *xits;
                   4217:   int niterf, itmp;
1.349     brouard  4218:   int Bigter=0, nBigterf=1;
                   4219:   
1.126     brouard  4220:   pt=vector(1,n); 
                   4221:   ptt=vector(1,n); 
                   4222:   xit=vector(1,n); 
                   4223:   xits=vector(1,n); 
                   4224:   *fret=(*func)(p); 
                   4225:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.338     brouard  4226:   rcurr_time = time(NULL);
                   4227:   fp=(*fret); /* Initialisation */
1.126     brouard  4228:   for (*iter=1;;++(*iter)) { 
                   4229:     ibig=0; 
                   4230:     del=0.0; 
1.157     brouard  4231:     rlast_time=rcurr_time;
1.349     brouard  4232:     rlast_btime=rcurr_time;
1.157     brouard  4233:     /* (void) gettimeofday(&curr_time,&tzp); */
                   4234:     rcurr_time = time(NULL);  
                   4235:     curr_time = *localtime(&rcurr_time);
1.337     brouard  4236:     /* 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); */
                   4237:     /* 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  4238:     /* Bigter=(*iter - *iter % ncovmodel)/ncovmodel +1; /\* Big iteration, i.e on ncovmodel cycle *\/ */
                   4239:     Bigter=(*iter - (*iter-1) % n)/n +1; /* Big iteration, i.e on ncovmodel cycle */
1.349     brouard  4240:     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);
                   4241:     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);
                   4242:     fprintf(ficrespow,"%d %d %.12f %d",*iter,Bigter, *fret,curr_time.tm_sec-start_time.tm_sec);
1.324     brouard  4243:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  4244:     for (i=1;i<=n;i++) {
1.126     brouard  4245:       fprintf(ficrespow," %.12lf", p[i]);
                   4246:     }
1.239     brouard  4247:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   4248:     printf("\n#model=  1      +     age ");
                   4249:     fprintf(ficlog,"\n#model=  1      +     age ");
                   4250:     if(nagesqr==1){
1.241     brouard  4251:        printf("  + age*age  ");
                   4252:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  4253:     }
1.362     brouard  4254:     for(j=1;j <=ncovmodel-2-nagesqr;j++){
1.239     brouard  4255:       if(Typevar[j]==0) {
                   4256:        printf("  +      V%d  ",Tvar[j]);
                   4257:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   4258:       }else if(Typevar[j]==1) {
                   4259:        printf("  +    V%d*age ",Tvar[j]);
                   4260:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   4261:       }else if(Typevar[j]==2) {
                   4262:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   4263:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  4264:       }else if(Typevar[j]==3) {
                   4265:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   4266:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.239     brouard  4267:       }
                   4268:     }
1.126     brouard  4269:     printf("\n");
1.239     brouard  4270: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   4271: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  4272:     fprintf(ficlog,"\n");
1.239     brouard  4273:     for(i=1,jk=1; i <=nlstate; i++){
                   4274:       for(k=1; k <=(nlstate+ndeath); k++){
                   4275:        if (k != i) {
                   4276:          printf("%d%d ",i,k);
                   4277:          fprintf(ficlog,"%d%d ",i,k);
                   4278:          for(j=1; j <=ncovmodel; j++){
                   4279:            printf("%12.7f ",p[jk]);
                   4280:            fprintf(ficlog,"%12.7f ",p[jk]);
                   4281:            jk++; 
                   4282:          }
                   4283:          printf("\n");
                   4284:          fprintf(ficlog,"\n");
                   4285:        }
                   4286:       }
                   4287:     }
1.241     brouard  4288:     if(*iter <=3 && *iter >1){
1.157     brouard  4289:       tml = *localtime(&rcurr_time);
                   4290:       strcpy(strcurr,asctime(&tml));
                   4291:       rforecast_time=rcurr_time; 
1.126     brouard  4292:       itmp = strlen(strcurr);
                   4293:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  4294:        strcurr[itmp-1]='\0';
1.162     brouard  4295:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  4296:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.349     brouard  4297:       for(nBigterf=1;nBigterf<=31;nBigterf+=10){
                   4298:        niterf=nBigterf*ncovmodel;
                   4299:        /* rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time); */
1.241     brouard  4300:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   4301:        forecast_time = *localtime(&rforecast_time);
                   4302:        strcpy(strfor,asctime(&forecast_time));
                   4303:        itmp = strlen(strfor);
                   4304:        if(strfor[itmp-1]=='\n')
                   4305:          strfor[itmp-1]='\0';
1.349     brouard  4306:        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);
                   4307:        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  4308:       }
                   4309:     }
1.359     brouard  4310:     for (i=1;i<=n;i++) { /* For each direction i, maximisation after loading directions */
                   4311:       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  */
                   4312: 
                   4313:       fptt=(*fret); /* Computes likelihood for parameters xit */
1.126     brouard  4314: #ifdef DEBUG
1.203     brouard  4315:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   4316:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  4317: #endif
1.203     brouard  4318:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  4319:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  4320: #ifdef LINMINORIGINAL
1.359     brouard  4321:       linmin(p,xit,n,fret,func); /* New point i minimizing in direction xit, i has coordinates p[j].*/
1.357     brouard  4322:       /* xit[j] gives the n coordinates of direction i as input.*/
                   4323:       /* *fret gives the maximum value on direction xit */
1.224     brouard  4324: #else
                   4325:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.359     brouard  4326:       flatdir[i]=flat; /* Function is vanishing in that direction i */
1.224     brouard  4327: #endif
1.359     brouard  4328:       /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  4329:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.359     brouard  4330:        /* because that direction will be replaced unless the gain del is small */
                   4331:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   4332:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   4333:        /* with the new direction. */
                   4334:        del=fabs(fptt-(*fret)); 
                   4335:        ibig=i; 
1.126     brouard  4336:       } 
                   4337: #ifdef DEBUG
                   4338:       printf("%d %.12e",i,(*fret));
                   4339:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   4340:       for (j=1;j<=n;j++) {
1.359     brouard  4341:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   4342:        printf(" x(%d)=%.12e",j,xit[j]);
                   4343:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  4344:       }
                   4345:       for(j=1;j<=n;j++) {
1.359     brouard  4346:        printf(" p(%d)=%.12e",j,p[j]);
                   4347:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  4348:       }
                   4349:       printf("\n");
                   4350:       fprintf(ficlog,"\n");
                   4351: #endif
1.187     brouard  4352:     } /* end loop on each direction i */
1.357     brouard  4353:     /* Convergence test will use last linmin estimation (fret) and compare to former iteration (fp) */ 
1.188     brouard  4354:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.359     brouard  4355:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  4356:     for(j=1;j<=n;j++) {
                   4357:       if(flatdir[j] >0){
                   4358:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   4359:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  4360:       }
1.319     brouard  4361:       /* printf("\n"); */
                   4362:       /* fprintf(ficlog,"\n"); */
                   4363:     }
1.243     brouard  4364:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   4365:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  4366:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   4367:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   4368:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   4369:       /* decreased of more than 3.84  */
                   4370:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   4371:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   4372:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  4373:                        
1.188     brouard  4374:       /* Starting the program with initial values given by a former maximization will simply change */
                   4375:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   4376:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   4377:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  4378: #ifdef DEBUG
                   4379:       int k[2],l;
                   4380:       k[0]=1;
                   4381:       k[1]=-1;
                   4382:       printf("Max: %.12e",(*func)(p));
                   4383:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   4384:       for (j=1;j<=n;j++) {
                   4385:        printf(" %.12e",p[j]);
                   4386:        fprintf(ficlog," %.12e",p[j]);
                   4387:       }
                   4388:       printf("\n");
                   4389:       fprintf(ficlog,"\n");
                   4390:       for(l=0;l<=1;l++) {
                   4391:        for (j=1;j<=n;j++) {
                   4392:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   4393:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   4394:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   4395:        }
                   4396:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   4397:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   4398:       }
                   4399: #endif
                   4400: 
                   4401:       free_vector(xit,1,n); 
                   4402:       free_vector(xits,1,n); 
                   4403:       free_vector(ptt,1,n); 
                   4404:       free_vector(pt,1,n); 
                   4405:       return; 
1.192     brouard  4406:     } /* enough precision */ 
1.240     brouard  4407:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.359     brouard  4408:     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  4409:       ptt[j]=2.0*p[j]-pt[j]; 
1.359     brouard  4410:       xit[j]=p[j]-pt[j]; /* Coordinate j of last direction xi_n=P_n-P_0 */
                   4411: #ifdef DEBUG
                   4412:       printf("\n %d xit=%12.7g p=%12.7g pt=%12.7g ",j,xit[j],p[j],pt[j]);
                   4413: #endif
                   4414:       pt[j]=p[j]; /* New P0 is Pn */
                   4415:     }
                   4416: #ifdef DEBUG
                   4417:     printf("\n");
                   4418: #endif
1.181     brouard  4419:     fptt=(*func)(ptt); /* f_3 */
1.359     brouard  4420: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in directions until some iterations are done */
1.224     brouard  4421:                if (*iter <=4) {
1.225     brouard  4422: #else
                   4423: #endif
1.224     brouard  4424: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  4425: #else
1.161     brouard  4426:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  4427: #endif
1.162     brouard  4428:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  4429:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  4430:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   4431:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   4432:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  4433:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   4434:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   4435:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  4436:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  4437:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   4438:       /* mu² and del² are equal when f3=f1 */
1.359     brouard  4439:       /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   4440:       /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   4441:       /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   4442:       /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  4443: #ifdef NRCORIGINAL
                   4444:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   4445: #else
                   4446:       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  4447:       t= t- del*SQR(fp-fptt);
1.183     brouard  4448: #endif
1.202     brouard  4449:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  4450: #ifdef DEBUG
1.181     brouard  4451:       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);
                   4452:       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  4453:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   4454:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   4455:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   4456:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   4457:       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);
                   4458:       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);
                   4459: #endif
1.183     brouard  4460: #ifdef POWELLORIGINAL
                   4461:       if (t < 0.0) { /* Then we use it for new direction */
1.361     brouard  4462: #else  /* Not POWELLOriginal but Brouard's */
1.182     brouard  4463:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.359     brouard  4464:        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  4465:         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  4466:         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  4467:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   4468:       } 
1.361     brouard  4469:       if (directest < 0.0) { /* Then we use (P0, Pn) for new direction Xi_n or Xi_iBig */
1.181     brouard  4470: #endif
1.191     brouard  4471: #ifdef DEBUGLINMIN
1.234     brouard  4472:        printf("Before linmin in direction P%d-P0\n",n);
                   4473:        for (j=1;j<=n;j++) {
                   4474:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   4475:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   4476:          if(j % ncovmodel == 0){
                   4477:            printf("\n");
                   4478:            fprintf(ficlog,"\n");
                   4479:          }
                   4480:        }
1.224     brouard  4481: #endif
                   4482: #ifdef LINMINORIGINAL
1.234     brouard  4483:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  4484: #else
1.234     brouard  4485:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   4486:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  4487: #endif
1.234     brouard  4488:        
1.191     brouard  4489: #ifdef DEBUGLINMIN
1.234     brouard  4490:        for (j=1;j<=n;j++) { 
                   4491:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   4492:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   4493:          if(j % ncovmodel == 0){
                   4494:            printf("\n");
                   4495:            fprintf(ficlog,"\n");
                   4496:          }
                   4497:        }
1.224     brouard  4498: #endif
1.234     brouard  4499:        for (j=1;j<=n;j++) { 
                   4500:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   4501:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   4502:        }
1.361     brouard  4503: 
                   4504: /* #else */
                   4505: /*     for (i=1;i<=n-1;i++) {  */
                   4506: /*       for (j=1;j<=n;j++) {  */
                   4507: /*         xi[j][i]=xi[j][i+1]; /\* Standard method of conjugate directions, not Powell who changes the nth direction by p0 pn . *\/ */
                   4508: /*       } */
                   4509: /*     } */
                   4510: /*     for (j=1;j<=n;j++) {  */
                   4511: /*       xi[j][n]=xit[j];      /\* and this nth direction by the by the average p_0 p_n *\/ */
                   4512: /*     } */
                   4513: /*     /\* for (j=1;j<=n-1;j++) {  *\/ */
                   4514: /*     /\*   xi[j][1]=xi[j][j+1]; /\\* Standard method of conjugate directions *\\/ *\/ */
                   4515: /*     /\*   xi[j][n]=xit[j];      /\\* and this nth direction by the by the average p_0 p_n *\\/ *\/ */
                   4516: /*     /\* } *\/ */
                   4517: /* #endif */
1.224     brouard  4518: #ifdef LINMINORIGINAL
                   4519: #else
1.234     brouard  4520:        for (j=1, flatd=0;j<=n;j++) {
                   4521:          if(flatdir[j]>0)
                   4522:            flatd++;
                   4523:        }
                   4524:        if(flatd >0){
1.255     brouard  4525:          printf("%d flat directions: ",flatd);
                   4526:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  4527:          for (j=1;j<=n;j++) { 
                   4528:            if(flatdir[j]>0){
                   4529:              printf("%d ",j);
                   4530:              fprintf(ficlog,"%d ",j);
                   4531:            }
                   4532:          }
                   4533:          printf("\n");
                   4534:          fprintf(ficlog,"\n");
1.319     brouard  4535: #ifdef FLATSUP
                   4536:           free_vector(xit,1,n); 
                   4537:           free_vector(xits,1,n); 
                   4538:           free_vector(ptt,1,n); 
                   4539:           free_vector(pt,1,n); 
                   4540:           return;
                   4541: #endif
1.361     brouard  4542:        }  /* endif(flatd >0) */
                   4543: #endif /* LINMINORIGINAL */
1.234     brouard  4544:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   4545:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   4546:        
1.126     brouard  4547: #ifdef DEBUG
1.234     brouard  4548:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   4549:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   4550:        for(j=1;j<=n;j++){
                   4551:          printf(" %lf",xit[j]);
                   4552:          fprintf(ficlog," %lf",xit[j]);
                   4553:        }
                   4554:        printf("\n");
                   4555:        fprintf(ficlog,"\n");
1.126     brouard  4556: #endif
1.192     brouard  4557:       } /* end of t or directest negative */
1.359     brouard  4558:       printf(" Directest is positive, P_n-P_0 does not increase the conjugacy. n=%d\n",n);
                   4559:       fprintf(ficlog," Directest is positive, P_n-P_0 does not increase the conjugacy. n=%d\n",n);
1.224     brouard  4560: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  4561: #else
1.234     brouard  4562:       } /* end if (fptt < fp)  */
1.192     brouard  4563: #endif
1.225     brouard  4564: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  4565:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  4566: #else
1.224     brouard  4567: #endif
1.234     brouard  4568:                } /* loop iteration */ 
1.126     brouard  4569: } 
1.234     brouard  4570:   
1.126     brouard  4571: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  4572:   
1.235     brouard  4573:   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  4574:   {
1.338     brouard  4575:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
1.279     brouard  4576:      *   (and selected quantitative values in nres)
                   4577:      *  by left multiplying the unit
                   4578:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   4579:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   4580:      * Wx is row vector: population in state 1, population in state 2, population dead
                   4581:      * or prevalence in state 1, prevalence in state 2, 0
                   4582:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   4583:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   4584:      * Output is prlim.
                   4585:      * Initial matrix pimij 
                   4586:      */
1.206     brouard  4587:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   4588:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   4589:   /*  0,                   0                  , 1} */
                   4590:   /*
                   4591:    * and after some iteration: */
                   4592:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   4593:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   4594:   /*  0,                   0                  , 1} */
                   4595:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   4596:   /* {0.51571254859325999, 0.4842874514067399, */
                   4597:   /*  0.51326036147820708, 0.48673963852179264} */
                   4598:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  4599:     
1.332     brouard  4600:     int i, ii,j,k, k1;
1.209     brouard  4601:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.366     brouard  4602:   double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b); /* test */ /* for clang */
                   4603: /* double **matprod2(); */ /* test */
                   4604:   /* double **out, cov[NCOVMAX+1], **pmij(); */ /* **pmmij is a global variable feeded with oldms etc */
                   4605:   double **out, cov[NCOVMAX+1], **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  4606:   double **newm;
1.209     brouard  4607:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  4608:   int ncvloop=0;
1.288     brouard  4609:   int first=0;
1.169     brouard  4610:   
1.209     brouard  4611:   min=vector(1,nlstate);
                   4612:   max=vector(1,nlstate);
                   4613:   meandiff=vector(1,nlstate);
                   4614: 
1.218     brouard  4615:        /* Starting with matrix unity */
1.126     brouard  4616:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   4617:     for (j=1;j<=nlstate+ndeath;j++){
                   4618:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4619:     }
1.169     brouard  4620:   
                   4621:   cov[1]=1.;
                   4622:   
                   4623:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  4624:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  4625:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  4626:     ncvloop++;
1.126     brouard  4627:     newm=savm;
                   4628:     /* Covariates have to be included here again */
1.138     brouard  4629:     cov[2]=agefin;
1.319     brouard  4630:      if(nagesqr==1){
                   4631:       cov[3]= agefin*agefin;
                   4632:      }
1.332     brouard  4633:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   4634:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   4635:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  4636:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  4637:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   4638:        }else{
                   4639:         cov[2+nagesqr+k1]=precov[nres][k1];
                   4640:        }
                   4641:      }/* End of loop on model equation */
                   4642:      
                   4643: /* Start of old code (replaced by a loop on position in the model equation */
                   4644:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   4645:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   4646:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   4647:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   4648:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   4649:     /*    * k                  1        2      3    4      5      6     7        8 */
                   4650:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   4651:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   4652:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   4653:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   4654:     /*    *nsd=3                              (1)  (2)           (3) */
                   4655:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   4656:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   4657:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   4658:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   4659:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   4660:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   4661:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   4662:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   4663:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   4664:     /*    *TvarsDpType */
                   4665:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   4666:     /*    * nsd=1              (1)           (2) */
                   4667:     /*    *TvarsD[nsd]          3             2 */
                   4668:     /*    *TnsdVar           (3)=1          (2)=2 */
                   4669:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   4670:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   4671:     /*    *\/ */
                   4672:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   4673:     /*   /\* 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)); *\/ */
                   4674:     /* } */
                   4675:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   4676:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   4677:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   4678:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   4679:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   4680:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   4681:     /*   /\* 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]); *\/ */
                   4682:     /* } */
                   4683:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   4684:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   4685:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   4686:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   4687:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   4688:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   4689:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   4690:     /*   } */
                   4691:     /*   /\* 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]); *\/ */
                   4692:     /* } */
                   4693:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   4694:     /*   /\* 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]); *\/ */
                   4695:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   4696:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   4697:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   4698:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   4699:     /*         }else{ */
                   4700:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   4701:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   4702:     /*         } */
                   4703:     /*   }else{ */
                   4704:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   4705:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   4706:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   4707:     /*         }else{ */
                   4708:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   4709:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   4710:     /*         } */
                   4711:     /*   } */
                   4712:     /* } /\* End product without age *\/ */
                   4713: /* ENd of old code */
1.138     brouard  4714:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   4715:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   4716:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  4717:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4718:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  4719:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  4720:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  4721:     
1.126     brouard  4722:     savm=oldm;
                   4723:     oldm=newm;
1.209     brouard  4724: 
                   4725:     for(j=1; j<=nlstate; j++){
                   4726:       max[j]=0.;
                   4727:       min[j]=1.;
                   4728:     }
                   4729:     for(i=1;i<=nlstate;i++){
                   4730:       sumnew=0;
                   4731:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   4732:       for(j=1; j<=nlstate; j++){ 
                   4733:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   4734:        max[j]=FMAX(max[j],prlim[i][j]);
                   4735:        min[j]=FMIN(min[j],prlim[i][j]);
                   4736:       }
                   4737:     }
                   4738: 
1.126     brouard  4739:     maxmax=0.;
1.209     brouard  4740:     for(j=1; j<=nlstate; j++){
                   4741:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   4742:       maxmax=FMAX(maxmax,meandiff[j]);
                   4743:       /* 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  4744:     } /* j loop */
1.203     brouard  4745:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  4746:     /* 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  4747:     if(maxmax < ftolpl){
1.209     brouard  4748:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   4749:       free_vector(min,1,nlstate);
                   4750:       free_vector(max,1,nlstate);
                   4751:       free_vector(meandiff,1,nlstate);
1.126     brouard  4752:       return prlim;
                   4753:     }
1.288     brouard  4754:   } /* agefin loop */
1.208     brouard  4755:     /* After some age loop it doesn't converge */
1.288     brouard  4756:   if(!first){
                   4757:     first=1;
                   4758:     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  4759:     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);
                   4760:   }else if (first >=1 && first <10){
                   4761:     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);
                   4762:     first++;
                   4763:   }else if (first ==10){
                   4764:     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);
                   4765:     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");
                   4766:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   4767:     first++;
1.288     brouard  4768:   }
                   4769: 
1.359     brouard  4770:   /* Try to lower 'ftol', for example from 1.e-8 to 6.e-9.\n", ftolpl,
                   4771:    * (int)age, (int)delaymax, (int)agefin, ncvloop,
                   4772:    * (int)age-(int)agefin); */
1.209     brouard  4773:   free_vector(min,1,nlstate);
                   4774:   free_vector(max,1,nlstate);
                   4775:   free_vector(meandiff,1,nlstate);
1.208     brouard  4776:   
1.169     brouard  4777:   return prlim; /* should not reach here */
1.126     brouard  4778: }
                   4779: 
1.217     brouard  4780: 
                   4781:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   4782: 
1.218     brouard  4783:  /* 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) */
                   4784:  /* 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  4785:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  4786: {
1.264     brouard  4787:   /* 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  4788:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   4789:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   4790:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   4791:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   4792:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   4793:   /* Initial matrix pimij */
                   4794:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   4795:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   4796:   /*  0,                   0                  , 1} */
                   4797:   /*
                   4798:    * and after some iteration: */
                   4799:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   4800:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   4801:   /*  0,                   0                  , 1} */
                   4802:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   4803:   /* {0.51571254859325999, 0.4842874514067399, */
                   4804:   /*  0.51326036147820708, 0.48673963852179264} */
                   4805:   /* If we start from prlim again, prlim tends to a constant matrix */
                   4806: 
1.359     brouard  4807:   int i, ii,j, k1;
1.247     brouard  4808:   int first=0;
1.217     brouard  4809:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   4810:   /* double **matprod2(); */ /* test */
1.366     brouard  4811:   double **out, cov[NCOVMAX+1], **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij);
                   4812:   /* double **out, cov[NCOVMAX+1], **bmij(); */ /* Deprecated in clang */
1.217     brouard  4813:   double **newm;
1.218     brouard  4814:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   4815:   double        **oldm, **savm;  /* for use */
                   4816: 
1.217     brouard  4817:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   4818:   int ncvloop=0;
                   4819:   
                   4820:   min=vector(1,nlstate);
                   4821:   max=vector(1,nlstate);
                   4822:   meandiff=vector(1,nlstate);
                   4823: 
1.266     brouard  4824:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   4825:   oldm=oldms; savm=savms;
                   4826:   
                   4827:   /* Starting with matrix unity */
                   4828:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   4829:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  4830:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4831:     }
                   4832:   
                   4833:   cov[1]=1.;
                   4834:   
                   4835:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   4836:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  4837:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  4838:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   4839:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  4840:     ncvloop++;
1.218     brouard  4841:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   4842:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  4843:     /* Covariates have to be included here again */
                   4844:     cov[2]=agefin;
1.319     brouard  4845:     if(nagesqr==1){
1.217     brouard  4846:       cov[3]= agefin*agefin;;
1.319     brouard  4847:     }
1.332     brouard  4848:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  4849:       if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  4850:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  4851:       }else{
1.332     brouard  4852:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  4853:       }
1.332     brouard  4854:     }/* End of loop on model equation */
                   4855: 
                   4856: /* Old code */ 
                   4857: 
                   4858:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   4859:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   4860:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   4861:     /*   /\* 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)); *\/ */
                   4862:     /* } */
                   4863:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   4864:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   4865:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   4866:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   4867:     /* /\* } *\/ */
                   4868:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   4869:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   4870:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   4871:     /*   /\* 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]); *\/ */
                   4872:     /* } */
                   4873:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   4874:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   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:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   4877:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   4878:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   4879:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   4880:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   4881:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   4882:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   4883:     /*   } */
                   4884:     /*   /\* 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]); *\/ */
                   4885:     /* } */
                   4886:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   4887:     /*   /\* 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]); *\/ */
                   4888:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   4889:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   4890:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   4891:     /*         }else{ */
                   4892:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   4893:     /*         } */
                   4894:     /*   }else{ */
                   4895:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   4896:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   4897:     /*         }else{ */
                   4898:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   4899:     /*         } */
                   4900:     /*   } */
                   4901:     /* } */
1.217     brouard  4902:     
                   4903:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   4904:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   4905:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   4906:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4907:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  4908:                /* ij should be linked to the correct index of cov */
                   4909:                /* age and covariate values ij are in 'cov', but we need to pass
                   4910:                 * ij for the observed prevalence at age and status and covariate
                   4911:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   4912:                 */
                   4913:     /* 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 *\/ */
                   4914:     /* 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 *\/ */
                   4915:     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  4916:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  4917:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   4918:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   4919:     /*         printf("%d newm= ",i); */
                   4920:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   4921:     /*           printf("%f ",newm[i][j]); */
                   4922:     /*         } */
                   4923:     /*         printf("oldm * "); */
                   4924:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   4925:     /*           printf("%f ",oldm[i][j]); */
                   4926:     /*         } */
1.268     brouard  4927:     /*         printf(" bmmij "); */
1.266     brouard  4928:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   4929:     /*           printf("%f ",pmmij[i][j]); */
                   4930:     /*         } */
                   4931:     /*         printf("\n"); */
                   4932:     /*   } */
                   4933:     /* } */
1.217     brouard  4934:     savm=oldm;
                   4935:     oldm=newm;
1.266     brouard  4936: 
1.217     brouard  4937:     for(j=1; j<=nlstate; j++){
                   4938:       max[j]=0.;
                   4939:       min[j]=1.;
                   4940:     }
                   4941:     for(j=1; j<=nlstate; j++){ 
                   4942:       for(i=1;i<=nlstate;i++){
1.234     brouard  4943:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   4944:        bprlim[i][j]= newm[i][j];
                   4945:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   4946:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  4947:       }
                   4948:     }
1.218     brouard  4949:                
1.217     brouard  4950:     maxmax=0.;
                   4951:     for(i=1; i<=nlstate; i++){
1.318     brouard  4952:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  4953:       maxmax=FMAX(maxmax,meandiff[i]);
                   4954:       /* 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  4955:     } /* i loop */
1.217     brouard  4956:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  4957:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  4958:     if(maxmax < ftolpl){
1.220     brouard  4959:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  4960:       free_vector(min,1,nlstate);
                   4961:       free_vector(max,1,nlstate);
                   4962:       free_vector(meandiff,1,nlstate);
                   4963:       return bprlim;
                   4964:     }
1.288     brouard  4965:   } /* agefin loop */
1.217     brouard  4966:     /* After some age loop it doesn't converge */
1.288     brouard  4967:   if(!first){
1.247     brouard  4968:     first=1;
                   4969:     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\
                   4970: 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);
                   4971:   }
                   4972:   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  4973: 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);
                   4974:   /* 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); */
                   4975:   free_vector(min,1,nlstate);
                   4976:   free_vector(max,1,nlstate);
                   4977:   free_vector(meandiff,1,nlstate);
                   4978:   
                   4979:   return bprlim; /* should not reach here */
                   4980: }
                   4981: 
1.126     brouard  4982: /*************** transition probabilities ***************/ 
                   4983: 
                   4984: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   4985: {
1.138     brouard  4986:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  4987:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  4988:      model to the ncovmodel covariates (including constant and age).
                   4989:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   4990:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   4991:      ncth covariate in the global vector x is given by the formula:
                   4992:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   4993:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   4994:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   4995:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  4996:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  4997:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  4998:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  4999:   */
                   5000:   double s1, lnpijopii;
1.126     brouard  5001:   /*double t34;*/
1.164     brouard  5002:   int i,j, nc, ii, jj;
1.126     brouard  5003: 
1.223     brouard  5004:   for(i=1; i<= nlstate; i++){
                   5005:     for(j=1; j<i;j++){
                   5006:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   5007:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   5008:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   5009:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   5010:       }
                   5011:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  5012:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  5013:     }
                   5014:     for(j=i+1; j<=nlstate+ndeath;j++){
                   5015:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   5016:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   5017:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   5018:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   5019:       }
                   5020:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  5021:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  5022:     }
                   5023:   }
1.218     brouard  5024:   
1.223     brouard  5025:   for(i=1; i<= nlstate; i++){
                   5026:     s1=0;
                   5027:     for(j=1; j<i; j++){
1.339     brouard  5028:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  5029:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   5030:     }
                   5031:     for(j=i+1; j<=nlstate+ndeath; j++){
1.339     brouard  5032:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  5033:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   5034:     }
                   5035:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   5036:     ps[i][i]=1./(s1+1.);
                   5037:     /* Computing other pijs */
                   5038:     for(j=1; j<i; j++)
1.325     brouard  5039:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  5040:     for(j=i+1; j<=nlstate+ndeath; j++)
                   5041:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   5042:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   5043:   } /* end i */
1.218     brouard  5044:   
1.223     brouard  5045:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   5046:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   5047:       ps[ii][jj]=0;
                   5048:       ps[ii][ii]=1;
                   5049:     }
                   5050:   }
1.294     brouard  5051: 
                   5052: 
1.223     brouard  5053:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   5054:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   5055:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   5056:   /*   } */
                   5057:   /*   printf("\n "); */
                   5058:   /* } */
                   5059:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   5060:   /*
                   5061:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  5062:                goto end;*/
1.266     brouard  5063:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  5064: }
                   5065: 
1.218     brouard  5066: /*************** backward transition probabilities ***************/ 
                   5067: 
                   5068:  /* 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 ) */
                   5069: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   5070:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   5071: {
1.302     brouard  5072:   /* 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  5073:    * 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  5074:    */
1.359     brouard  5075:   int ii, j;
1.222     brouard  5076:   
1.366     brouard  5077:   double  **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate);
                   5078:   /* double  **pmij(); */ /* No more for clang */
1.222     brouard  5079:   double sumnew=0.;
1.218     brouard  5080:   double agefin;
1.292     brouard  5081:   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  5082:   double **dnewm, **dsavm, **doldm;
                   5083:   double **bbmij;
                   5084:   
1.218     brouard  5085:   doldm=ddoldms; /* global pointers */
1.222     brouard  5086:   dnewm=ddnewms;
                   5087:   dsavm=ddsavms;
1.318     brouard  5088: 
                   5089:   /* Debug */
                   5090:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  5091:   agefin=cov[2];
1.268     brouard  5092:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  5093:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  5094:      the observed prevalence (with this covariate ij) at beginning of transition */
                   5095:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  5096: 
                   5097:   /* P_x */
1.325     brouard  5098:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  5099:   /* outputs pmmij which is a stochastic matrix in row */
                   5100: 
                   5101:   /* Diag(w_x) */
1.292     brouard  5102:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  5103:   sumnew=0.;
1.269     brouard  5104:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  5105:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  5106:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  5107:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   5108:   }
                   5109:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   5110:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   5111:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  5112:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  5113:     }
                   5114:   }else{
                   5115:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   5116:       for (j=1;j<=nlstate+ndeath;j++)
                   5117:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   5118:     }
                   5119:     /* if(sumnew <0.9){ */
                   5120:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   5121:     /* } */
                   5122:   }
                   5123:   k3=0.0;  /* We put the last diagonal to 0 */
                   5124:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   5125:       doldm[ii][ii]= k3;
                   5126:   }
                   5127:   /* End doldm, At the end doldm is diag[(w_i)] */
                   5128:   
1.292     brouard  5129:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   5130:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  5131: 
1.292     brouard  5132:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  5133:   /* 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  5134:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  5135:     sumnew=0.;
1.222     brouard  5136:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  5137:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  5138:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  5139:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  5140:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  5141:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  5142:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  5143:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  5144:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  5145:        /* }else */
1.268     brouard  5146:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   5147:     } /*End ii */
                   5148:   } /* 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 */
                   5149: 
1.292     brouard  5150:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  5151:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  5152:   /* end bmij */
1.266     brouard  5153:   return ps; /*pointer is unchanged */
1.218     brouard  5154: }
1.217     brouard  5155: /*************** transition probabilities ***************/ 
                   5156: 
1.218     brouard  5157: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  5158: {
                   5159:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   5160:      computes the probability to be observed in state j being in state i by appying the
                   5161:      model to the ncovmodel covariates (including constant and age).
                   5162:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   5163:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   5164:      ncth covariate in the global vector x is given by the formula:
                   5165:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   5166:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   5167:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   5168:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   5169:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   5170:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   5171:   */
                   5172:   double s1, lnpijopii;
                   5173:   /*double t34;*/
                   5174:   int i,j, nc, ii, jj;
                   5175: 
1.234     brouard  5176:   for(i=1; i<= nlstate; i++){
                   5177:     for(j=1; j<i;j++){
                   5178:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   5179:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   5180:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   5181:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   5182:       }
                   5183:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   5184:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   5185:     }
                   5186:     for(j=i+1; j<=nlstate+ndeath;j++){
                   5187:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   5188:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   5189:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   5190:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   5191:       }
                   5192:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   5193:     }
                   5194:   }
                   5195:   
                   5196:   for(i=1; i<= nlstate; i++){
                   5197:     s1=0;
                   5198:     for(j=1; j<i; j++){
                   5199:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   5200:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   5201:     }
                   5202:     for(j=i+1; j<=nlstate+ndeath; j++){
                   5203:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   5204:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   5205:     }
                   5206:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   5207:     ps[i][i]=1./(s1+1.);
                   5208:     /* Computing other pijs */
                   5209:     for(j=1; j<i; j++)
                   5210:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   5211:     for(j=i+1; j<=nlstate+ndeath; j++)
                   5212:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   5213:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   5214:   } /* end i */
                   5215:   
                   5216:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   5217:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   5218:       ps[ii][jj]=0;
                   5219:       ps[ii][ii]=1;
                   5220:     }
                   5221:   }
1.296     brouard  5222:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  5223:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   5224:     s1=0.;
                   5225:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   5226:       s1+=ps[ii][jj];
                   5227:     }
                   5228:     for(ii=1; ii<= nlstate; ii++){
                   5229:       ps[ii][jj]=ps[ii][jj]/s1;
                   5230:     }
                   5231:   }
                   5232:   /* Transposition */
                   5233:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   5234:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   5235:       s1=ps[ii][jj];
                   5236:       ps[ii][jj]=ps[jj][ii];
                   5237:       ps[jj][ii]=s1;
                   5238:     }
                   5239:   }
                   5240:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   5241:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   5242:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   5243:   /*   } */
                   5244:   /*   printf("\n "); */
                   5245:   /* } */
                   5246:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   5247:   /*
                   5248:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   5249:     goto end;*/
                   5250:   return ps;
1.217     brouard  5251: }
                   5252: 
                   5253: 
1.126     brouard  5254: /**************** Product of 2 matrices ******************/
                   5255: 
1.145     brouard  5256: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  5257: {
                   5258:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   5259:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   5260:   /* in, b, out are matrice of pointers which should have been initialized 
                   5261:      before: only the contents of out is modified. The function returns
                   5262:      a pointer to pointers identical to out */
1.145     brouard  5263:   int i, j, k;
1.126     brouard  5264:   for(i=nrl; i<= nrh; i++)
1.145     brouard  5265:     for(k=ncolol; k<=ncoloh; k++){
                   5266:       out[i][k]=0.;
                   5267:       for(j=ncl; j<=nch; j++)
                   5268:        out[i][k] +=in[i][j]*b[j][k];
                   5269:     }
1.126     brouard  5270:   return out;
                   5271: }
                   5272: 
                   5273: 
                   5274: /************* Higher Matrix Product ***************/
                   5275: 
1.235     brouard  5276: 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  5277: {
1.336     brouard  5278:   /* Already optimized with precov.
                   5279:      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  5280:      'nhstepm*hstepm*stepm' months (i.e. until
                   5281:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   5282:      nhstepm*hstepm matrices. 
                   5283:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   5284:      (typically every 2 years instead of every month which is too big 
                   5285:      for the memory).
                   5286:      Model is determined by parameters x and covariates have to be 
                   5287:      included manually here. 
                   5288: 
                   5289:      */
                   5290: 
1.359     brouard  5291:   int i, j, d, h, k1;
1.131     brouard  5292:   double **out, cov[NCOVMAX+1];
1.126     brouard  5293:   double **newm;
1.187     brouard  5294:   double agexact;
1.359     brouard  5295:   /*double agebegin, ageend;*/
1.126     brouard  5296: 
                   5297:   /* Hstepm could be zero and should return the unit matrix */
                   5298:   for (i=1;i<=nlstate+ndeath;i++)
                   5299:     for (j=1;j<=nlstate+ndeath;j++){
                   5300:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   5301:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   5302:     }
                   5303:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   5304:   for(h=1; h <=nhstepm; h++){
                   5305:     for(d=1; d <=hstepm; d++){
                   5306:       newm=savm;
                   5307:       /* Covariates have to be included here again */
                   5308:       cov[1]=1.;
1.214     brouard  5309:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  5310:       cov[2]=agexact;
1.319     brouard  5311:       if(nagesqr==1){
1.227     brouard  5312:        cov[3]= agexact*agexact;
1.319     brouard  5313:       }
1.330     brouard  5314:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   5315:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   5316:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  5317:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  5318:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   5319:        }else{
                   5320:          cov[2+nagesqr+k1]=precov[nres][k1];
                   5321:        }
                   5322:       }/* End of loop on model equation */
                   5323:        /* Old code */ 
                   5324: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   5325: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   5326: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   5327: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   5328: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   5329: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   5330: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   5331: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   5332: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   5333: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   5334: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   5335: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   5336: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   5337: /*       /\* 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]])); *\/ */
                   5338: /*       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); */
                   5339: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   5340: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   5341: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   5342: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   5343: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   5344: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   5345: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   5346: /*       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]]); */
                   5347: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   5348: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   5349: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   5350: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   5351: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   5352: /*       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]); */
                   5353: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   5354: 
                   5355: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   5356: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   5357: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   5358: /*       /\* *\/ */
1.330     brouard  5359: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   5360: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   5361: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  5362: /* /\*cptcovage=2                   1               2      *\/ */
                   5363: /* /\*Tage[k]=                      5               8      *\/  */
                   5364: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   5365: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   5366: /*       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]]); */
                   5367: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   5368: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   5369: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   5370: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   5371: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   5372: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   5373: /*       /\*   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); *\/ */
                   5374: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   5375: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   5376: /*       /\* } *\/ */
                   5377: /*       /\* 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]); *\/ */
                   5378: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   5379: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   5380: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   5381: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   5382: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   5383: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   5384: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   5385: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   5386: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  5387:          
1.332     brouard  5388: /*       /\* 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])]); *\/ */
                   5389: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   5390: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   5391: /*       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]]); */
                   5392: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   5393: 
                   5394: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   5395: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   5396: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   5397: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   5398: /*           /\* 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]])]; *\/ */
                   5399: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   5400: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   5401: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   5402: /*       /\*   } *\/ */
                   5403: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   5404: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   5405: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   5406: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   5407: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   5408: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   5409: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   5410: /*       /\*   } *\/ */
                   5411: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   5412: /*     }/\*end of products *\/ */
                   5413:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  5414:       /* for (k=1; k<=cptcovn;k++)  */
                   5415:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   5416:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   5417:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   5418:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   5419:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  5420:       
                   5421:       
1.126     brouard  5422:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   5423:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  5424:       /* right multiplication of oldm by the current matrix */
1.126     brouard  5425:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   5426:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  5427:       /* if((int)age == 70){ */
                   5428:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   5429:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   5430:       /*         printf("%d pmmij ",i); */
                   5431:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   5432:       /*           printf("%f ",pmmij[i][j]); */
                   5433:       /*         } */
                   5434:       /*         printf(" oldm "); */
                   5435:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   5436:       /*           printf("%f ",oldm[i][j]); */
                   5437:       /*         } */
                   5438:       /*         printf("\n"); */
                   5439:       /*       } */
                   5440:       /* } */
1.126     brouard  5441:       savm=oldm;
                   5442:       oldm=newm;
                   5443:     }
                   5444:     for(i=1; i<=nlstate+ndeath; i++)
                   5445:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  5446:        po[i][j][h]=newm[i][j];
                   5447:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  5448:       }
1.128     brouard  5449:     /*printf("h=%d ",h);*/
1.126     brouard  5450:   } /* end h */
1.267     brouard  5451:   /*     printf("\n H=%d \n",h); */
1.126     brouard  5452:   return po;
                   5453: }
                   5454: 
1.217     brouard  5455: /************* Higher Back Matrix Product ***************/
1.218     brouard  5456: /* 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  5457: 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  5458: {
1.332     brouard  5459:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   5460:      computes the transition matrix starting at age 'age' over
1.217     brouard  5461:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  5462:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   5463:      nhstepm*hstepm matrices.
                   5464:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   5465:      (typically every 2 years instead of every month which is too big
1.217     brouard  5466:      for the memory).
1.218     brouard  5467:      Model is determined by parameters x and covariates have to be
1.266     brouard  5468:      included manually here. Then we use a call to bmij(x and cov)
                   5469:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  5470:   */
1.217     brouard  5471: 
1.359     brouard  5472:   int i, j, d, h, k1;
1.366     brouard  5473:   double **out, cov[NCOVMAX+1], **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij);
                   5474:   /* double **out, cov[NCOVMAX+1], **bmij(); */ /* No more for clang */
1.266     brouard  5475:   double **newm, ***newmm;
1.217     brouard  5476:   double agexact;
1.359     brouard  5477:   /*double agebegin, ageend;*/
1.222     brouard  5478:   double **oldm, **savm;
1.217     brouard  5479: 
1.266     brouard  5480:   newmm=po; /* To be saved */
                   5481:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  5482:   /* Hstepm could be zero and should return the unit matrix */
                   5483:   for (i=1;i<=nlstate+ndeath;i++)
                   5484:     for (j=1;j<=nlstate+ndeath;j++){
                   5485:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   5486:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   5487:     }
                   5488:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   5489:   for(h=1; h <=nhstepm; h++){
                   5490:     for(d=1; d <=hstepm; d++){
                   5491:       newm=savm;
                   5492:       /* Covariates have to be included here again */
                   5493:       cov[1]=1.;
1.271     brouard  5494:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  5495:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  5496:         /* Debug */
                   5497:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  5498:       cov[2]=agexact;
1.332     brouard  5499:       if(nagesqr==1){
1.222     brouard  5500:        cov[3]= agexact*agexact;
1.332     brouard  5501:       }
                   5502:       /** New code */
                   5503:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  5504:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  5505:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  5506:        }else{
1.332     brouard  5507:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  5508:        }
1.332     brouard  5509:       }/* End of loop on model equation */
                   5510:       /** End of new code */
                   5511:   /** This was old code */
                   5512:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   5513:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   5514:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   5515:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   5516:       /*   /\* 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)); *\/ */
                   5517:       /* } */
                   5518:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   5519:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   5520:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   5521:       /*       /\* 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]); *\/ */
                   5522:       /* } */
                   5523:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   5524:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   5525:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   5526:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   5527:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   5528:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   5529:       /*       } */
                   5530:       /*       /\* 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]); *\/ */
                   5531:       /* } */
                   5532:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   5533:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   5534:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   5535:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   5536:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   5537:       /*         }else{ */
                   5538:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   5539:       /*         } */
                   5540:       /*       }else{ */
                   5541:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   5542:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   5543:       /*         }else{ */
                   5544:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   5545:       /*         } */
                   5546:       /*       } */
                   5547:       /* }                      */
                   5548:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   5549:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   5550: /** End of old code */
                   5551:       
1.218     brouard  5552:       /* Careful transposed matrix */
1.266     brouard  5553:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  5554:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  5555:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  5556:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  5557:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  5558:       /* if((int)age == 70){ */
                   5559:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   5560:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   5561:       /*         printf("%d pmmij ",i); */
                   5562:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   5563:       /*           printf("%f ",pmmij[i][j]); */
                   5564:       /*         } */
                   5565:       /*         printf(" oldm "); */
                   5566:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   5567:       /*           printf("%f ",oldm[i][j]); */
                   5568:       /*         } */
                   5569:       /*         printf("\n"); */
                   5570:       /*       } */
                   5571:       /* } */
                   5572:       savm=oldm;
                   5573:       oldm=newm;
                   5574:     }
                   5575:     for(i=1; i<=nlstate+ndeath; i++)
                   5576:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  5577:        po[i][j][h]=newm[i][j];
1.268     brouard  5578:        /* if(h==nhstepm) */
                   5579:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  5580:       }
1.268     brouard  5581:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  5582:   } /* end h */
1.268     brouard  5583:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  5584:   return po;
                   5585: }
                   5586: 
                   5587: 
1.162     brouard  5588: #ifdef NLOPT
                   5589:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   5590:   double fret;
                   5591:   double *xt;
                   5592:   int j;
                   5593:   myfunc_data *d2 = (myfunc_data *) pd;
                   5594: /* xt = (p1-1); */
                   5595:   xt=vector(1,n); 
                   5596:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   5597: 
                   5598:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   5599:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   5600:   printf("Function = %.12lf ",fret);
                   5601:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   5602:   printf("\n");
                   5603:  free_vector(xt,1,n);
                   5604:   return fret;
                   5605: }
                   5606: #endif
1.126     brouard  5607: 
                   5608: /*************** log-likelihood *************/
                   5609: double func( double *x)
                   5610: {
1.336     brouard  5611:   int i, ii, j, k, mi, d, kk, kf=0;
1.226     brouard  5612:   int ioffset=0;
1.339     brouard  5613:   int ipos=0,iposold=0,ncovv=0;
                   5614: 
1.340     brouard  5615:   double cotvarv, cotvarvold;
1.226     brouard  5616:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   5617:   double **out;
                   5618:   double lli; /* Individual log likelihood */
                   5619:   int s1, s2;
1.228     brouard  5620:   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  5621: 
1.226     brouard  5622:   double bbh, survp;
                   5623:   double agexact;
1.336     brouard  5624:   double agebegin, ageend;
1.226     brouard  5625:   /*extern weight */
                   5626:   /* We are differentiating ll according to initial status */
                   5627:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   5628:   /*for(i=1;i<imx;i++) 
                   5629:     printf(" %d\n",s[4][i]);
                   5630:   */
1.162     brouard  5631: 
1.226     brouard  5632:   ++countcallfunc;
1.162     brouard  5633: 
1.226     brouard  5634:   cov[1]=1.;
1.126     brouard  5635: 
1.226     brouard  5636:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  5637:   ioffset=0;
1.226     brouard  5638:   if(mle==1){
                   5639:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   5640:       /* Computes the values of the ncovmodel covariates of the model
                   5641:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   5642:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   5643:         to be observed in j being in i according to the model.
                   5644:       */
1.243     brouard  5645:       ioffset=2+nagesqr ;
1.233     brouard  5646:    /* Fixed */
1.345     brouard  5647:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummy or quant or prod */
1.319     brouard  5648:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   5649:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   5650:        /*  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  5651:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.336     brouard  5652:        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  5653:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  5654:       }
1.226     brouard  5655:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  5656:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  5657:         has been calculated etc */
                   5658:       /* For an individual i, wav[i] gives the number of effective waves */
                   5659:       /* We compute the contribution to Likelihood of each effective transition
                   5660:         mw[mi][i] is real wave of the mi th effectve wave */
                   5661:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   5662:         s2=s[mw[mi+1][i]][i];
1.341     brouard  5663:         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  5664:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   5665:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   5666:       */
1.336     brouard  5667:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   5668:       /* Wave varying (but not age varying) */
1.339     brouard  5669:        /* 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*\/ */
                   5670:        /*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
                   5671:        /*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   5672:        /* } */
1.340     brouard  5673:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
                   5674:          itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   5675:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  5676:          if(FixedV[itv]!=0){ /* Not a fixed covariate */
1.341     brouard  5677:            cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* cotvar[wav][ncovcol+nqv+iv][i] */
1.340     brouard  5678:          }else{ /* fixed covariate */
1.345     brouard  5679:            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  5680:          }
1.339     brouard  5681:          if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  5682:            cotvarvold=cotvarv;
                   5683:          }else{ /* A second product */
                   5684:            cotvarv=cotvarv*cotvarvold;
1.339     brouard  5685:          }
                   5686:          iposold=ipos;
1.340     brouard  5687:          cov[ioffset+ipos]=cotvarv;
1.234     brouard  5688:        }
1.339     brouard  5689:        /* for products of time varying to be done */
1.234     brouard  5690:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5691:          for (j=1;j<=nlstate+ndeath;j++){
                   5692:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5693:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5694:          }
1.336     brouard  5695: 
                   5696:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   5697:        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  5698:        for(d=0; d<dh[mi][i]; d++){
                   5699:          newm=savm;
                   5700:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5701:          cov[2]=agexact;
                   5702:          if(nagesqr==1)
                   5703:            cov[3]= agexact*agexact;  /* Should be changed here */
1.349     brouard  5704:          /* for (kk=1; kk<=cptcovage;kk++) { */
                   5705:          /*   if(!FixedV[Tvar[Tage[kk]]]) */
                   5706:          /*     cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /\* Tage[kk] gives the data-covariate associated with age *\/ */
                   5707:          /*   else */
                   5708:          /*     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) *\/  */
                   5709:          /* } */
                   5710:          for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   5711:            itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   5712:            ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   5713:            if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   5714:              cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   5715:            }else{ /* fixed covariate */
                   5716:              cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   5717:            }
                   5718:            if(ipos!=iposold){ /* Not a product or first of a product */
                   5719:              cotvarvold=cotvarv;
                   5720:            }else{ /* A second product */
                   5721:              cotvarv=cotvarv*cotvarvold;
                   5722:            }
                   5723:            iposold=ipos;
                   5724:            cov[ioffset+ipos]=cotvarv*agexact;
                   5725:            /* For products */
1.234     brouard  5726:          }
1.349     brouard  5727:          
1.234     brouard  5728:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5729:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5730:          savm=oldm;
                   5731:          oldm=newm;
                   5732:        } /* end mult */
                   5733:        
                   5734:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   5735:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   5736:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   5737:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   5738:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   5739:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   5740:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   5741:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  5742:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   5743:                                 * -stepm/2 to stepm/2 .
                   5744:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   5745:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   5746:                                 */
1.234     brouard  5747:        s1=s[mw[mi][i]][i];
                   5748:        s2=s[mw[mi+1][i]][i];
                   5749:        bbh=(double)bh[mi][i]/(double)stepm; 
                   5750:        /* bias bh is positive if real duration
                   5751:         * is higher than the multiple of stepm and negative otherwise.
                   5752:         */
                   5753:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   5754:        if( s2 > nlstate){ 
                   5755:          /* i.e. if s2 is a death state and if the date of death is known 
                   5756:             then the contribution to the likelihood is the probability to 
                   5757:             die between last step unit time and current  step unit time, 
                   5758:             which is also equal to probability to die before dh 
                   5759:             minus probability to die before dh-stepm . 
                   5760:             In version up to 0.92 likelihood was computed
                   5761:             as if date of death was unknown. Death was treated as any other
                   5762:             health state: the date of the interview describes the actual state
                   5763:             and not the date of a change in health state. The former idea was
                   5764:             to consider that at each interview the state was recorded
                   5765:             (healthy, disable or death) and IMaCh was corrected; but when we
                   5766:             introduced the exact date of death then we should have modified
                   5767:             the contribution of an exact death to the likelihood. This new
                   5768:             contribution is smaller and very dependent of the step unit
                   5769:             stepm. It is no more the probability to die between last interview
                   5770:             and month of death but the probability to survive from last
                   5771:             interview up to one month before death multiplied by the
                   5772:             probability to die within a month. Thanks to Chris
                   5773:             Jackson for correcting this bug.  Former versions increased
                   5774:             mortality artificially. The bad side is that we add another loop
                   5775:             which slows down the processing. The difference can be up to 10%
                   5776:             lower mortality.
                   5777:          */
                   5778:          /* If, at the beginning of the maximization mostly, the
                   5779:             cumulative probability or probability to be dead is
                   5780:             constant (ie = 1) over time d, the difference is equal to
                   5781:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   5782:             s1 at precedent wave, to be dead a month before current
                   5783:             wave is equal to probability, being at state s1 at
                   5784:             precedent wave, to be dead at mont of the current
                   5785:             wave. Then the observed probability (that this person died)
                   5786:             is null according to current estimated parameter. In fact,
                   5787:             it should be very low but not zero otherwise the log go to
                   5788:             infinity.
                   5789:          */
1.183     brouard  5790: /* #ifdef INFINITYORIGINAL */
                   5791: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   5792: /* #else */
                   5793: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   5794: /*         lli=log(mytinydouble); */
                   5795: /*       else */
                   5796: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   5797: /* #endif */
1.226     brouard  5798:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  5799:          
1.226     brouard  5800:        } else if  ( s2==-1 ) { /* alive */
                   5801:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   5802:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   5803:          /*survp += out[s1][j]; */
                   5804:          lli= log(survp);
                   5805:        }
1.336     brouard  5806:        /* else if  (s2==-4) {  */
                   5807:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
                   5808:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   5809:        /*   lli= log(survp);  */
                   5810:        /* }  */
                   5811:        /* else if  (s2==-5) {  */
                   5812:        /*   for (j=1,survp=0. ; j<=2; j++)   */
                   5813:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   5814:        /*   lli= log(survp);  */
                   5815:        /* }  */
1.226     brouard  5816:        else{
                   5817:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   5818:          /*  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 */
                   5819:        } 
                   5820:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   5821:        /*if(lli ==000.0)*/
1.340     brouard  5822:        /* 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  5823:        ipmx +=1;
                   5824:        sw += weight[i];
                   5825:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   5826:        /* if (lli < log(mytinydouble)){ */
                   5827:        /*   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); */
                   5828:        /*   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]); */
                   5829:        /* } */
                   5830:       } /* end of wave */
                   5831:     } /* end of individual */
                   5832:   }  else if(mle==2){
                   5833:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  5834:       ioffset=2+nagesqr ;
                   5835:       for (k=1; k<=ncovf;k++)
                   5836:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  5837:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  5838:        for(k=1; k <= ncovv ; k++){
1.341     brouard  5839:          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  5840:        }
1.226     brouard  5841:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5842:          for (j=1;j<=nlstate+ndeath;j++){
                   5843:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5844:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5845:          }
                   5846:        for(d=0; d<=dh[mi][i]; d++){
                   5847:          newm=savm;
                   5848:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5849:          cov[2]=agexact;
                   5850:          if(nagesqr==1)
                   5851:            cov[3]= agexact*agexact;
                   5852:          for (kk=1; kk<=cptcovage;kk++) {
                   5853:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   5854:          }
                   5855:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5856:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5857:          savm=oldm;
                   5858:          oldm=newm;
                   5859:        } /* end mult */
                   5860:       
                   5861:        s1=s[mw[mi][i]][i];
                   5862:        s2=s[mw[mi+1][i]][i];
                   5863:        bbh=(double)bh[mi][i]/(double)stepm; 
                   5864:        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 */
                   5865:        ipmx +=1;
                   5866:        sw += weight[i];
                   5867:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   5868:       } /* end of wave */
                   5869:     } /* end of individual */
                   5870:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   5871:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   5872:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   5873:       for(mi=1; mi<= wav[i]-1; mi++){
                   5874:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5875:          for (j=1;j<=nlstate+ndeath;j++){
                   5876:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5877:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5878:          }
                   5879:        for(d=0; d<dh[mi][i]; d++){
                   5880:          newm=savm;
                   5881:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5882:          cov[2]=agexact;
                   5883:          if(nagesqr==1)
                   5884:            cov[3]= agexact*agexact;
                   5885:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  5886:            if(!FixedV[Tvar[Tage[kk]]])
                   5887:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   5888:            else
1.341     brouard  5889:              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  5890:          }
                   5891:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5892:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5893:          savm=oldm;
                   5894:          oldm=newm;
                   5895:        } /* end mult */
                   5896:       
                   5897:        s1=s[mw[mi][i]][i];
                   5898:        s2=s[mw[mi+1][i]][i];
                   5899:        bbh=(double)bh[mi][i]/(double)stepm; 
                   5900:        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 */
                   5901:        ipmx +=1;
                   5902:        sw += weight[i];
                   5903:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   5904:       } /* end of wave */
                   5905:     } /* end of individual */
                   5906:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   5907:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   5908:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   5909:       for(mi=1; mi<= wav[i]-1; mi++){
                   5910:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5911:          for (j=1;j<=nlstate+ndeath;j++){
                   5912:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5913:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5914:          }
                   5915:        for(d=0; d<dh[mi][i]; d++){
                   5916:          newm=savm;
                   5917:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5918:          cov[2]=agexact;
                   5919:          if(nagesqr==1)
                   5920:            cov[3]= agexact*agexact;
                   5921:          for (kk=1; kk<=cptcovage;kk++) {
                   5922:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   5923:          }
1.126     brouard  5924:        
1.226     brouard  5925:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5926:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5927:          savm=oldm;
                   5928:          oldm=newm;
                   5929:        } /* end mult */
                   5930:       
                   5931:        s1=s[mw[mi][i]][i];
                   5932:        s2=s[mw[mi+1][i]][i];
                   5933:        if( s2 > nlstate){ 
                   5934:          lli=log(out[s1][s2] - savm[s1][s2]);
                   5935:        } else if  ( s2==-1 ) { /* alive */
                   5936:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   5937:            survp += out[s1][j];
                   5938:          lli= log(survp);
                   5939:        }else{
                   5940:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   5941:        }
                   5942:        ipmx +=1;
                   5943:        sw += weight[i];
                   5944:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.343     brouard  5945:        /* 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  5946:       } /* end of wave */
                   5947:     } /* end of individual */
                   5948:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   5949:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   5950:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   5951:       for(mi=1; mi<= wav[i]-1; mi++){
                   5952:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5953:          for (j=1;j<=nlstate+ndeath;j++){
                   5954:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5955:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5956:          }
                   5957:        for(d=0; d<dh[mi][i]; d++){
                   5958:          newm=savm;
                   5959:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5960:          cov[2]=agexact;
                   5961:          if(nagesqr==1)
                   5962:            cov[3]= agexact*agexact;
                   5963:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  5964:            if(!FixedV[Tvar[Tage[kk]]])
                   5965:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   5966:            else
1.341     brouard  5967:              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  5968:          }
1.126     brouard  5969:        
1.226     brouard  5970:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5971:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5972:          savm=oldm;
                   5973:          oldm=newm;
                   5974:        } /* end mult */
                   5975:       
                   5976:        s1=s[mw[mi][i]][i];
                   5977:        s2=s[mw[mi+1][i]][i];
                   5978:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   5979:        ipmx +=1;
                   5980:        sw += weight[i];
                   5981:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   5982:        /*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]);*/
                   5983:       } /* end of wave */
                   5984:     } /* end of individual */
                   5985:   } /* End of if */
                   5986:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   5987:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   5988:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   5989:   return -l;
1.126     brouard  5990: }
                   5991: 
                   5992: /*************** log-likelihood *************/
                   5993: double funcone( double *x)
                   5994: {
1.228     brouard  5995:   /* Same as func but slower because of a lot of printf and if */
1.359     brouard  5996:   int i, ii, j, k, mi, d, kv=0, kf=0;
1.228     brouard  5997:   int ioffset=0;
1.339     brouard  5998:   int ipos=0,iposold=0,ncovv=0;
                   5999: 
1.340     brouard  6000:   double cotvarv, cotvarvold;
1.131     brouard  6001:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  6002:   double **out;
                   6003:   double lli; /* Individual log likelihood */
                   6004:   double llt;
                   6005:   int s1, s2;
1.228     brouard  6006:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   6007: 
1.126     brouard  6008:   double bbh, survp;
1.187     brouard  6009:   double agexact;
1.214     brouard  6010:   double agebegin, ageend;
1.126     brouard  6011:   /*extern weight */
                   6012:   /* We are differentiating ll according to initial status */
                   6013:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   6014:   /*for(i=1;i<imx;i++) 
                   6015:     printf(" %d\n",s[4][i]);
                   6016:   */
                   6017:   cov[1]=1.;
                   6018: 
                   6019:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  6020:   ioffset=0;
                   6021:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.336     brouard  6022:     /* Computes the values of the ncovmodel covariates of the model
                   6023:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   6024:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   6025:        to be observed in j being in i according to the model.
                   6026:     */
1.243     brouard  6027:     /* ioffset=2+nagesqr+cptcovage; */
                   6028:     ioffset=2+nagesqr;
1.232     brouard  6029:     /* Fixed */
1.224     brouard  6030:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  6031:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.349     brouard  6032:     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  6033:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
                   6034:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
                   6035:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
1.335     brouard  6036:       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  6037: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   6038: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   6039: /*    cov[2+6]=covar[2][i]; V2  */
                   6040: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   6041: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   6042: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   6043: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   6044: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   6045: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  6046:     }
1.336     brouard  6047:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   6048:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   6049:         has been calculated etc */
                   6050:       /* For an individual i, wav[i] gives the number of effective waves */
                   6051:       /* We compute the contribution to Likelihood of each effective transition
                   6052:         mw[mi][i] is real wave of the mi th effectve wave */
                   6053:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   6054:         s2=s[mw[mi+1][i]][i];
1.341     brouard  6055:         And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][ncovcol+nqv+iv][i]
1.336     brouard  6056:       */
                   6057:     /* This part may be useless now because everythin should be in covar */
1.232     brouard  6058:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   6059:     /*   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?)*\/ */
                   6060:     /* } */
1.231     brouard  6061:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   6062:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   6063:     /* } */
1.225     brouard  6064:     
1.233     brouard  6065: 
                   6066:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.339     brouard  6067:       /* 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 */
                   6068:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
                   6069:       /*       /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
                   6070:       /*       cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   6071:       /* } */
                   6072:       
                   6073:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   6074:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   6075:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   6076:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
                   6077:       /* We need the position of the time varying or product in the model */
                   6078:       /* 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 */            
                   6079:       /* TvarVV gives the variable name */
1.340     brouard  6080:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   6081:       *      k=         1   2     3     4         5        6        7       8        9
                   6082:       *  varying            1     2                                 3       4        5
                   6083:       *  ncovv              1     2                                3 4     5 6      7 8
1.343     brouard  6084:       * TvarVV[ncovv]      V3     5                                1 3     3 5      1 5
1.340     brouard  6085:       * TvarVVind           2     3                                7 7     8 8      9 9
                   6086:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
                   6087:       */
1.345     brouard  6088:       /* Other model ncovcol=5 nqv=0 ntv=3 nqtv=0 nlstate=3
1.349     brouard  6089:        * 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  6090:        * FixedV[ncovcol+qv+ntv+nqtv]       V5
1.349     brouard  6091:        * 3           V1  V2     V3    V4   V5 V6     V7  V8 V3*V2 V7*V2  V6*V3 V7*V3 V6*V4 V7*V4
                   6092:        *             0   0      0      0    0  1      1   1  0, 0, 1,1,   1, 0, 1, 0, 1, 0, 1, 0}
                   6093:        * 3           0   0      0      0    0  1      1   1  0,     1      1    1      1    1}
                   6094:        * model=          V2  +  V3  +  V4  +  V6  +  V7  +  V6*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   6095:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   6096:         *                +age*V6*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   6097:        * model2=          V2  +  V3  +  V4  +  V6  +  V7  +  V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   6098:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   6099:         *                +age*V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   6100:        * model3=          V2  +  V3  +  V4  +  V6  +  V7  + age*V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   6101:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   6102:         *                +V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   6103:        * kmodel           1     2      3      4      5        6         7         8         9        10        11    
                   6104:        *                  12       13      14      15       16
                   6105:        *                    17        18         19        20         21
                   6106:        * Tvar[kmodel]     2     3      4      6      7        9        10        11        12        13        14
                   6107:        *                   2       3        4       6        7
                   6108:        *                     9         11          12        13         14            
                   6109:        * cptcovage=5+5 total of covariates with age 
                   6110:        * Tage[cptcovage] age*V2=12      13      14      15       16
                   6111:        *1                   17            18         19        20         21 gives the position in model of covariates associated with age
                   6112:        *3 Tage[cptcovage] age*V3*V2=6  
                   6113:        *3                age*V2=12         13      14      15       16
                   6114:        *3                age*V6*V3=18      19    20   21
                   6115:        * Tvar[Tage[cptcovage]]    Tvar[12]=2      3      4       6         Tvar[16]=7(age*V7)
                   6116:        *     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
                   6117:        * 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
                   6118:        * 3 Tvar[Tage[cptcovage]]    Tvar[6]=9      Tvar[12]=2      3     4       6         Tvar[16]=7(age*V7)
                   6119:        * 3     Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
                   6120:        * 3 Tage[cptcovage] age*V3*V2=6   age*V2=12 age*V3 13    14      15       16
                   6121:        *                    age*V6*V3=18         19        20         21 gives the position in model of covariates associated with age
                   6122:        * 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
                   6123:        * Tvar=                {2, 3, 4, 6, 7,
                   6124:        *                       9, 10, 11, 12, 13, 14,
                   6125:        *              Tvar[12]=2, 3, 4, 6, 7,
                   6126:        *              Tvar[17]=9, 11, 12, 13, 14}
                   6127:        * Typevar[1]@21 = {0, 0, 0, 0, 0,
                   6128:        *                  2, 2, 2, 2, 2, 2,
                   6129:        * 3                3, 2, 2, 2, 2, 2,
                   6130:        *                  1, 1, 1, 1, 1, 
                   6131:        *                  3, 3, 3, 3, 3}
                   6132:        * 3                 2, 3, 3, 3, 3}
                   6133:        * 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
                   6134:        * p Tprod[1]@21 {6, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   6135:        * 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}
                   6136:        * 3 Tprod[1]@21 {17, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   6137:        * cptcovprod=11 (6+5)
                   6138:        * FixedV[Tvar[Tage[cptcovage]]]]  FixedV[2]=0      FixedV[3]=0      0      1          (age*V7)Tvar[16]=1 FixedV[absolute] not [kmodel]
                   6139:        *   FixedV[Tvar[17]=FixedV[age*V6*V2]=FixedV[9]=1        1         1          1         1  
                   6140:        * 3 FixedV[Tvar[17]=FixedV[age*V3*V2]=FixedV[9]=0        [11]=1         1          1         1  
                   6141:        * FixedV[]          V1=0     V2=0   V3=0  v4=0    V5=0  V6=1    V7=1 v8=1  OK then model dependent
                   6142:        *                   9=1  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   6143:        * 3                 9=0  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   6144:        * cptcovdageprod=5  for gnuplot printing
                   6145:        * cptcovprodvage=6 
                   6146:        * ncova=15           1        2       3       4       5
                   6147:        *                      6 7        8 9      10 11        12 13     14 15
                   6148:        * TvarA              2        3       4       6       7
                   6149:        *                      6 2        6 7       7 3          6 4       7 4
                   6150:        * TvaAind             12 12      13 13     14 14      15 15       16 16        
1.345     brouard  6151:        * ncovf            1     2      3
1.349     brouard  6152:        *                                    V6       V7      V6*V2     V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   6153:        * ncovvt=14                            1      2        3 4       5 6       7 8       9 10     11 12     13 14     
                   6154:        * TvarVV[1]@14 = itv               {V6=6,     7, V6*V2=6, 2,     7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   6155:        * TvarVVind[1]@14=                    {4,     5,       6, 6,     7, 7,     8, 8,      9, 9,   10, 10,   11, 11}
                   6156:        * 3 ncovvt=12                        V6       V7      V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   6157:        * 3 TvarVV[1]@12 = itv                {6,     7, V7*V2=7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   6158:        * 3                                    1      2        3  4      5  6      7  8      9 10     11 12
                   6159:        * TvarVVind[1]@12=         {V6 is in k=4,     5,  7,(4isV2)=7,   8, 8,      9, 9,   10,10,    11,11}TvarVVind[12]=k=11
                   6160:        * TvarV              6, 7, 9, 10, 11, 12, 13, 14
                   6161:        * 3 cptcovprodvage=6
                   6162:        * 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
                   6163:        * 3 TvarAVVA[1]@15= itva 3 2    2      3    4        6       7        6 3         7 3         6 4         7 4 
                   6164:        * 3 ncovta             1 2      3      4    5        6       7        8 9       10 11       12 13        14 15
1.354     brouard  6165:        *?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  6166:        * TvarAVVAind[1]@15= V3 is in k=6 6 12  13   14      15      16       18 18       19,19,     20,20        21,21}TvarVVAind[]
                   6167:        * 3 ncovvta=10     +age*V6 + age*V7 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   6168:        * 3 we want to compute =cotvar[mw[mi][i]][TvarVVA[ncovva]][i] at position TvarVVAind[ncovva]
                   6169:        * 3 TvarVVA[1]@10= itva   6       7        6 3         7 3         6 4         7 4 
                   6170:        * 3 ncovva                1       2        3 4         5 6         7 8         9 10
                   6171:        * TvarVVAind[1]@10= V6 is in k=4  5        8,8         9, 9,      10,10        11 11}TvarVVAind[]
                   6172:        * TvarVVAind[1]@10=       15       16     18,18        19,19,      20,20        21 21}TvarVVAind[]
                   6173:        * TvarVA              V3*V2=6 6 , 1, 2, 11, 12, 13, 14
1.345     brouard  6174:        * TvarFind[1]@14= {1,    2,     3,     0 <repeats 12 times>}
1.349     brouard  6175:        * Tvar[1]@21=     {2,    3,     4,    6,      7,      9,      10,        11,       12,      13,       14,
                   6176:        *                   2, 3, 4, 6, 7,
                   6177:        *                     6, 8, 9, 10, 11}
1.345     brouard  6178:        * TvarFind[itv]                        0      0       0
                   6179:        * FixedV[itv]                          1      1       1  0      1 0       1 0       1 0       0
1.354     brouard  6180:        *? FixedV[itv]                          1      1       1  0      1 0       1 0       1 0      1 0     1 0
1.345     brouard  6181:        * Tvar[TvarFind[ncovf]]=[1]=2 [2]=3 [4]=4
                   6182:        * Tvar[TvarFind[itv]]                [0]=?      ?ncovv 1 à ncovvt]
                   6183:        *   Not a fixed cotvar[mw][itv][i]     6       7      6  2      7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
1.349     brouard  6184:        *   fixed covar[itv]                  [6]     [7]    [6][2] 
1.345     brouard  6185:        */
                   6186: 
1.349     brouard  6187:       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 */
                   6188:        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  6189:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  6190:        /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   6191:        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  6192:          /* printf("DEBUG ncovv=%d, Varying TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
1.345     brouard  6193:          cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
1.354     brouard  6194:          /* printf("DEBUG Varying cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
1.340     brouard  6195:        }else{ /* fixed covariate */
1.345     brouard  6196:          /* 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  6197:          /* printf("DEBUG ncovv=%d, Fixed TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
1.349     brouard  6198:          cotvarv=covar[itv][i];  /* Good: In V6*V3, 3 is fixed at position of the data */
1.354     brouard  6199:          /* printf("DEBUG Fixed cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
1.340     brouard  6200:        }
1.339     brouard  6201:        if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  6202:          cotvarvold=cotvarv;
                   6203:        }else{ /* A second product */
                   6204:          cotvarv=cotvarv*cotvarvold;
1.339     brouard  6205:        }
                   6206:        iposold=ipos;
1.340     brouard  6207:        cov[ioffset+ipos]=cotvarv;
1.354     brouard  6208:        /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
1.339     brouard  6209:        /* For products */
                   6210:       }
                   6211:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
                   6212:       /*       iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
                   6213:       /*       /\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
                   6214:       /*       /\*           1  2   3      4      5                         *\/ */
                   6215:       /*       /\*itv           1                                           *\/ */
                   6216:       /*       /\* TvarVInd[1]= 2                                           *\/ */
                   6217:       /*       /\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
                   6218:       /*       /\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
                   6219:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
                   6220:       /*       /\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
                   6221:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
                   6222:       /*       cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
                   6223:       /*       /\* 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]); *\/ */
                   6224:       /* } */
1.232     brouard  6225:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  6226:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   6227:       /*       /\* 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]); *\/ */
                   6228:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  6229:       /* } */
1.126     brouard  6230:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  6231:        for (j=1;j<=nlstate+ndeath;j++){
                   6232:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   6233:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   6234:        }
1.214     brouard  6235:       
                   6236:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   6237:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   6238:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  6239:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  6240:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   6241:          and mw[mi+1][i]. dh depends on stepm.*/
                   6242:        newm=savm;
1.247     brouard  6243:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  6244:        cov[2]=agexact;
                   6245:        if(nagesqr==1)
                   6246:          cov[3]= agexact*agexact;
1.349     brouard  6247:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   6248:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   6249:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   6250:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   6251:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   6252:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   6253:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   6254:          }else{ /* fixed covariate */
                   6255:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   6256:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   6257:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   6258:          }
                   6259:          if(ipos!=iposold){ /* Not a product or first of a product */
                   6260:            cotvarvold=cotvarv;
                   6261:          }else{ /* A second product */
                   6262:            /* printf("DEBUG * \n"); */
                   6263:            cotvarv=cotvarv*cotvarvold;
                   6264:          }
                   6265:          iposold=ipos;
                   6266:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   6267:          cov[ioffset+ipos]=cotvarv*agexact;
                   6268:          /* For products */
1.242     brouard  6269:        }
1.349     brouard  6270: 
1.242     brouard  6271:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   6272:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   6273:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   6274:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   6275:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   6276:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   6277:        savm=oldm;
                   6278:        oldm=newm;
1.126     brouard  6279:       } /* end mult */
1.336     brouard  6280:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   6281:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   6282:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   6283:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   6284:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   6285:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   6286:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   6287:         * probability in order to take into account the bias as a fraction of the way
                   6288:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   6289:                                 * -stepm/2 to stepm/2 .
                   6290:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   6291:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   6292:                                 */
1.126     brouard  6293:       s1=s[mw[mi][i]][i];
                   6294:       s2=s[mw[mi+1][i]][i];
1.217     brouard  6295:       /* if(s2==-1){ */
1.268     brouard  6296:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  6297:       /*       /\* exit(1); *\/ */
                   6298:       /* } */
1.126     brouard  6299:       bbh=(double)bh[mi][i]/(double)stepm; 
                   6300:       /* bias is positive if real duration
                   6301:        * is higher than the multiple of stepm and negative otherwise.
                   6302:        */
                   6303:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  6304:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  6305:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  6306:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   6307:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   6308:        lli= log(survp);
1.126     brouard  6309:       }else if (mle==1){
1.242     brouard  6310:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  6311:       } else if(mle==2){
1.242     brouard  6312:        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  6313:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  6314:        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  6315:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  6316:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  6317:       } else{  /* mle=0 back to 1 */
1.242     brouard  6318:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   6319:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  6320:       } /* End of if */
                   6321:       ipmx +=1;
                   6322:       sw += weight[i];
                   6323:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.342     brouard  6324:       /* Printing covariates values for each contribution for checking */
1.343     brouard  6325:       /* 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  6326:       if(globpr){
1.246     brouard  6327:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  6328:  %11.6f %11.6f %11.6f ", \
1.242     brouard  6329:                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  6330:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.343     brouard  6331:        /*      printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
                   6332:        /* %11.6f %11.6f %11.6f ", \ */
                   6333:        /*              num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   6334:        /*              2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  6335:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   6336:          llt +=ll[k]*gipmx/gsw;
                   6337:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335     brouard  6338:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  6339:        }
1.343     brouard  6340:        fprintf(ficresilk," %10.6f ", -llt);
1.335     brouard  6341:        /* printf(" %10.6f\n", -llt); */
1.342     brouard  6342:        /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
1.343     brouard  6343:        /* fprintf(ficresilk,"%09ld ", num[i]); */ /* not necessary */
                   6344:        for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
                   6345:          fprintf(ficresilk," %g",covar[Tvar[TvarFind[kf]]][i]);
                   6346:        }
                   6347:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
                   6348:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   6349:          if(ipos!=iposold){ /* Not a product or first of a product */
                   6350:            fprintf(ficresilk," %g",cov[ioffset+ipos]);
                   6351:            /* printf(" %g",cov[ioffset+ipos]); */
                   6352:          }else{
                   6353:            fprintf(ficresilk,"*");
                   6354:            /* printf("*"); */
1.342     brouard  6355:          }
1.343     brouard  6356:          iposold=ipos;
                   6357:        }
1.349     brouard  6358:        /* for (kk=1; kk<=cptcovage;kk++) { */
                   6359:        /*   if(!FixedV[Tvar[Tage[kk]]]){ */
                   6360:        /*     fprintf(ficresilk," %g*age",covar[Tvar[Tage[kk]]][i]); */
                   6361:        /*     /\* printf(" %g*age",covar[Tvar[Tage[kk]]][i]); *\/ */
                   6362:        /*   }else{ */
                   6363:        /*     fprintf(ficresilk," %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   6364:        /*     /\* printf(" %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\\/  *\/ */
                   6365:        /*   } */
                   6366:        /* } */
                   6367:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   6368:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   6369:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   6370:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   6371:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   6372:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   6373:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   6374:          }else{ /* fixed covariate */
                   6375:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   6376:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   6377:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   6378:          }
                   6379:          if(ipos!=iposold){ /* Not a product or first of a product */
                   6380:            cotvarvold=cotvarv;
                   6381:          }else{ /* A second product */
                   6382:            /* printf("DEBUG * \n"); */
                   6383:            cotvarv=cotvarv*cotvarvold;
1.342     brouard  6384:          }
1.349     brouard  6385:          cotvarv=cotvarv*agexact;
                   6386:          fprintf(ficresilk," %g*age",cotvarv);
                   6387:          iposold=ipos;
                   6388:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   6389:          cov[ioffset+ipos]=cotvarv;
                   6390:          /* For products */
1.343     brouard  6391:        }
                   6392:        /* printf("\n"); */
1.342     brouard  6393:        /* } /\*  End debugILK *\/ */
                   6394:        fprintf(ficresilk,"\n");
                   6395:       } /* End if globpr */
1.335     brouard  6396:     } /* end of wave */
                   6397:   } /* end of individual */
                   6398:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  6399: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335     brouard  6400:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   6401:   if(globpr==0){ /* First time we count the contributions and weights */
                   6402:     gipmx=ipmx;
                   6403:     gsw=sw;
                   6404:   }
1.343     brouard  6405:   return -l;
1.126     brouard  6406: }
                   6407: 
                   6408: 
                   6409: /*************** function likelione ***********/
1.292     brouard  6410: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  6411: {
                   6412:   /* This routine should help understanding what is done with 
                   6413:      the selection of individuals/waves and
                   6414:      to check the exact contribution to the likelihood.
                   6415:      Plotting could be done.
1.342     brouard  6416:   */
                   6417:   void pstamp(FILE *ficres);
1.343     brouard  6418:   int k, kf, kk, kvar, ncovv, iposold, ipos;
1.126     brouard  6419: 
                   6420:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  6421:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  6422:     strcat(fileresilk,fileresu);
1.126     brouard  6423:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   6424:       printf("Problem with resultfile: %s\n", fileresilk);
                   6425:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   6426:     }
1.342     brouard  6427:     pstamp(ficresilk);fprintf(ficresilk,"# model=1+age+%s\n",model);
1.214     brouard  6428:     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");
                   6429:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  6430:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   6431:     for(k=1; k<=nlstate; k++) 
                   6432:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
1.342     brouard  6433:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total) ");
                   6434: 
                   6435:     /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
                   6436:       for(kf=1;kf <= ncovf; kf++){
                   6437:        fprintf(ficresilk,"V%d",Tvar[TvarFind[kf]]);
                   6438:        /* printf("V%d",Tvar[TvarFind[kf]]); */
                   6439:       }
                   6440:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){
1.343     brouard  6441:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
1.342     brouard  6442:        if(ipos!=iposold){ /* Not a product or first of a product */
                   6443:          /* printf(" %d",ipos); */
                   6444:          fprintf(ficresilk," V%d",TvarVV[ncovv]);
                   6445:        }else{
                   6446:          /* printf("*"); */
                   6447:          fprintf(ficresilk,"*");
1.343     brouard  6448:        }
1.342     brouard  6449:        iposold=ipos;
                   6450:       }
                   6451:       for (kk=1; kk<=cptcovage;kk++) {
                   6452:        if(!FixedV[Tvar[Tage[kk]]]){
                   6453:          /* printf(" %d*age(Fixed)",Tvar[Tage[kk]]); */
                   6454:          fprintf(ficresilk," %d*age(Fixed)",Tvar[Tage[kk]]);
                   6455:        }else{
                   6456:          fprintf(ficresilk," %d*age(Varying)",Tvar[Tage[kk]]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   6457:          /* printf(" %d*age(Varying)",Tvar[Tage[kk]]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   6458:        }
                   6459:       }
                   6460:     /* } /\* End if debugILK *\/ */
                   6461:     /* printf("\n"); */
                   6462:     fprintf(ficresilk,"\n");
                   6463:   } /* End glogpri */
1.126     brouard  6464: 
1.292     brouard  6465:   *fretone=(*func)(p);
1.126     brouard  6466:   if(*globpri !=0){
                   6467:     fclose(ficresilk);
1.205     brouard  6468:     if (mle ==0)
                   6469:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   6470:     else if(mle >=1)
                   6471:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   6472:     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  6473:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  6474:       
1.207     brouard  6475:     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  6476: <img src=\"%s-ori.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  6477:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.343     brouard  6478: <img src=\"%s-dest.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
                   6479:     
                   6480:     for (k=1; k<= nlstate ; k++) {
                   6481:       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 \
                   6482: <img src=\"%s-p%dj.png\">\n",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   6483:       for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.350     brouard  6484:         kvar=Tvar[TvarFind[kf]];  /* variable */
                   6485:         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]]);
                   6486:         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);
                   6487:         fprintf(fichtm,"<img src=\"%s-p%dj-%d.png\">",subdirf2(optionfilefiname,"ILK_"),k,Tvar[TvarFind[kf]]);
1.343     brouard  6488:       }
                   6489:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Loop on the time varying extended covariates (with extension of Vn*Vm */
                   6490:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   6491:        kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   6492:        /* 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]); */
                   6493:        if(ipos!=iposold){ /* Not a product or first of a product */
                   6494:          /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   6495:          /* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); */
                   6496:          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)  */
                   6497:            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> \
                   6498: <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);
                   6499:          } /* End only for dummies time varying (single?) */
                   6500:        }else{ /* Useless product */
                   6501:          /* printf("*"); */
                   6502:          /* fprintf(ficresilk,"*"); */ 
                   6503:        }
                   6504:        iposold=ipos;
                   6505:       } /* For each time varying covariate */
                   6506:     } /* End loop on states */
                   6507: 
                   6508: /*     if(debugILK){ */
                   6509: /*       for(kf=1; kf <= ncovf; kf++){ /\* For each simple dummy covariate of the model *\/ */
                   6510: /*     /\* kvar=Tvar[TvarFind[kf]]; *\/ /\* variable *\/ */
                   6511: /*     for (k=1; k<= nlstate ; k++) { */
                   6512: /*       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> \ */
                   6513: /* <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]]); */
                   6514: /*     } */
                   6515: /*       } */
                   6516: /*       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /\* Loop on the time varying extended covariates (with extension of Vn*Vm *\/ */
                   6517: /*     ipos=TvarVVind[ncovv]; /\* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate *\/ */
                   6518: /*     kvar=TvarVV[ncovv]; /\*  TvarVV={3, 1, 3} gives the name of each varying covariate *\/ */
                   6519: /*     /\* 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]); *\/ */
                   6520: /*     if(ipos!=iposold){ /\* Not a product or first of a product *\/ */
                   6521: /*       /\* fprintf(ficresilk," V%d",TvarVV[ncovv]); *\/ */
                   6522: /*       /\* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); *\/ */
                   6523: /*       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)  *\/ */
                   6524: /*         for (k=1; k<= nlstate ; k++) { */
                   6525: /*           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> \ */
                   6526: /* <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar); */
                   6527: /*         } /\* End state *\/ */
                   6528: /*       } /\* End only for dummies time varying (single?) *\/ */
                   6529: /*     }else{ /\* Useless product *\/ */
                   6530: /*       /\* printf("*"); *\/ */
                   6531: /*       /\* fprintf(ficresilk,"*"); *\/  */
                   6532: /*     } */
                   6533: /*     iposold=ipos; */
                   6534: /*       } /\* For each time varying covariate *\/ */
                   6535: /*     }/\* End debugILK *\/ */
1.207     brouard  6536:     fflush(fichtm);
1.343     brouard  6537:   }/* End globpri */
1.126     brouard  6538:   return;
                   6539: }
                   6540: 
                   6541: 
                   6542: /*********** Maximum Likelihood Estimation ***************/
                   6543: 
                   6544: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   6545: {
1.359     brouard  6546:   int i,j,  jkk=0, iter=0;
1.126     brouard  6547:   double **xi;
1.359     brouard  6548:   /*double fret;*/
                   6549:   /*double fretone;*/ /* Only one call to likelihood */
1.126     brouard  6550:   /*  char filerespow[FILENAMELENGTH];*/
1.354     brouard  6551:   
1.359     brouard  6552:   /*double * p1;*/ /* Shifted parameters from 0 instead of 1 */
1.162     brouard  6553: #ifdef NLOPT
                   6554:   int creturn;
                   6555:   nlopt_opt opt;
                   6556:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   6557:   double *lb;
                   6558:   double minf; /* the minimum objective value, upon return */
1.354     brouard  6559: 
1.162     brouard  6560:   myfunc_data dinst, *d = &dinst;
                   6561: #endif
                   6562: 
                   6563: 
1.126     brouard  6564:   xi=matrix(1,npar,1,npar);
1.357     brouard  6565:   for (i=1;i<=npar;i++)  /* Starting with canonical directions j=1,n xi[i=1,n][j] */
1.126     brouard  6566:     for (j=1;j<=npar;j++)
                   6567:       xi[i][j]=(i==j ? 1.0 : 0.0);
1.359     brouard  6568:   printf("Powell-prax\n");  fprintf(ficlog,"Powell-prax\n");
1.201     brouard  6569:   strcpy(filerespow,"POW_"); 
1.126     brouard  6570:   strcat(filerespow,fileres);
                   6571:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   6572:     printf("Problem with resultfile: %s\n", filerespow);
                   6573:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   6574:   }
                   6575:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   6576:   for (i=1;i<=nlstate;i++)
                   6577:     for(j=1;j<=nlstate+ndeath;j++)
                   6578:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   6579:   fprintf(ficrespow,"\n");
1.162     brouard  6580: #ifdef POWELL
1.319     brouard  6581: #ifdef LINMINORIGINAL
                   6582: #else /* LINMINORIGINAL */
                   6583:   
                   6584:   flatdir=ivector(1,npar); 
                   6585:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   6586: #endif /*LINMINORIGINAL */
                   6587: 
                   6588: #ifdef FLATSUP
                   6589:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   6590:   /* reorganizing p by suppressing flat directions */
                   6591:   for(i=1, jk=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 ",i,k,jk, flatdir[jk]);
                   6597:         }
                   6598:         for(j=1; j <=ncovmodel; j++){
                   6599:           printf("%12.7f ",p[jk]);
                   6600:           jk++; 
                   6601:         }
                   6602:         printf("\n");
                   6603:       }
                   6604:     }
                   6605:   }
                   6606: /* skipping */
                   6607:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   6608:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   6609:     for(k=1; k <=(nlstate+ndeath); k++){
                   6610:       if (k != i) {
                   6611:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   6612:         if(flatdir[jk]==1){
                   6613:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   6614:           for(j=1; j <=ncovmodel;  jk++,j++){
                   6615:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   6616:             /*q[jjk]=p[jk];*/
                   6617:           }
                   6618:         }else{
                   6619:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   6620:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   6621:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   6622:             /*q[jjk]=p[jk];*/
                   6623:           }
                   6624:         }
                   6625:         printf("\n");
                   6626:       }
                   6627:       fflush(stdout);
                   6628:     }
                   6629:   }
                   6630:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   6631: #else  /* FLATSUP */
1.359     brouard  6632: /*  powell(p,xi,npar,ftol,&iter,&fret,func);*/
                   6633: /*   praxis ( t0, h0, n, prin, x, beale_f ); */
1.364     brouard  6634:  int prin=4;
1.362     brouard  6635:   /* double h0=0.25; */
                   6636:   /* double macheps; */
                   6637:   /* double fmin; */
1.359     brouard  6638:   macheps=pow(16.0,-13.0);
                   6639: /* #include "praxis.h" */
                   6640:   /* Be careful that praxis start at x[0] and powell start at p[1] */
                   6641:    /* praxis ( ftol, h0, npar, prin, p, func ); */
                   6642: /* p1= (p+1); */ /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   6643: printf("Praxis Gegenfurtner \n");
                   6644: fprintf(ficlog, "Praxis  Gegenfurtner\n");fflush(ficlog);
                   6645: /* praxis ( ftol, h0, npar, prin, p1, func ); */
                   6646:   /* fmin = praxis(1.e-5,macheps, h, n, prin, x, func); */
1.362     brouard  6647:   ffmin = praxis(ftol,macheps, h0, npar, prin, p, func);
1.359     brouard  6648: printf("End Praxis\n");
1.319     brouard  6649: #endif  /* FLATSUP */
                   6650: 
                   6651: #ifdef LINMINORIGINAL
                   6652: #else
                   6653:       free_ivector(flatdir,1,npar); 
                   6654: #endif  /* LINMINORIGINAL*/
                   6655: #endif /* POWELL */
1.126     brouard  6656: 
1.162     brouard  6657: #ifdef NLOPT
                   6658: #ifdef NEWUOA
                   6659:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   6660: #else
                   6661:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   6662: #endif
                   6663:   lb=vector(0,npar-1);
                   6664:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   6665:   nlopt_set_lower_bounds(opt, lb);
                   6666:   nlopt_set_initial_step1(opt, 0.1);
                   6667:   
                   6668:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   6669:   d->function = func;
                   6670:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   6671:   nlopt_set_min_objective(opt, myfunc, d);
                   6672:   nlopt_set_xtol_rel(opt, ftol);
                   6673:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   6674:     printf("nlopt failed! %d\n",creturn); 
                   6675:   }
                   6676:   else {
                   6677:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   6678:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   6679:     iter=1; /* not equal */
                   6680:   }
                   6681:   nlopt_destroy(opt);
                   6682: #endif
1.319     brouard  6683: #ifdef FLATSUP
                   6684:   /* npared = npar -flatd/ncovmodel; */
                   6685:   /* xired= matrix(1,npared,1,npared); */
                   6686:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   6687:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   6688:   /* free_matrix(xire,1,npared,1,npared); */
                   6689: #else  /* FLATSUP */
                   6690: #endif /* FLATSUP */
1.126     brouard  6691:   free_matrix(xi,1,npar,1,npar);
                   6692:   fclose(ficrespow);
1.203     brouard  6693:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   6694:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  6695:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  6696: 
                   6697: }
                   6698: 
                   6699: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  6700: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  6701: {
                   6702:   double  **a,**y,*x,pd;
1.203     brouard  6703:   /* double **hess; */
1.164     brouard  6704:   int i, j;
1.126     brouard  6705:   int *indx;
                   6706: 
                   6707:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  6708:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  6709:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   6710:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   6711:   double gompertz(double p[]);
1.203     brouard  6712:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  6713: 
                   6714:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   6715:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   6716:   for (i=1;i<=npar;i++){
1.203     brouard  6717:     printf("%d-",i);fflush(stdout);
                   6718:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  6719:    
                   6720:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   6721:     
                   6722:     /*  printf(" %f ",p[i]);
                   6723:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   6724:   }
                   6725:   
                   6726:   for (i=1;i<=npar;i++) {
                   6727:     for (j=1;j<=npar;j++)  {
                   6728:       if (j>i) { 
1.203     brouard  6729:        printf(".%d-%d",i,j);fflush(stdout);
                   6730:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   6731:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  6732:        
                   6733:        hess[j][i]=hess[i][j];    
                   6734:        /*printf(" %lf ",hess[i][j]);*/
                   6735:       }
                   6736:     }
                   6737:   }
                   6738:   printf("\n");
                   6739:   fprintf(ficlog,"\n");
                   6740: 
                   6741:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   6742:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   6743:   
                   6744:   a=matrix(1,npar,1,npar);
                   6745:   y=matrix(1,npar,1,npar);
                   6746:   x=vector(1,npar);
                   6747:   indx=ivector(1,npar);
                   6748:   for (i=1;i<=npar;i++)
                   6749:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   6750:   ludcmp(a,npar,indx,&pd);
                   6751: 
                   6752:   for (j=1;j<=npar;j++) {
                   6753:     for (i=1;i<=npar;i++) x[i]=0;
                   6754:     x[j]=1;
                   6755:     lubksb(a,npar,indx,x);
                   6756:     for (i=1;i<=npar;i++){ 
                   6757:       matcov[i][j]=x[i];
                   6758:     }
                   6759:   }
                   6760: 
                   6761:   printf("\n#Hessian matrix#\n");
                   6762:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   6763:   for (i=1;i<=npar;i++) { 
                   6764:     for (j=1;j<=npar;j++) { 
1.203     brouard  6765:       printf("%.6e ",hess[i][j]);
                   6766:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  6767:     }
                   6768:     printf("\n");
                   6769:     fprintf(ficlog,"\n");
                   6770:   }
                   6771: 
1.203     brouard  6772:   /* printf("\n#Covariance matrix#\n"); */
                   6773:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   6774:   /* for (i=1;i<=npar;i++) {  */
                   6775:   /*   for (j=1;j<=npar;j++) {  */
                   6776:   /*     printf("%.6e ",matcov[i][j]); */
                   6777:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   6778:   /*   } */
                   6779:   /*   printf("\n"); */
                   6780:   /*   fprintf(ficlog,"\n"); */
                   6781:   /* } */
                   6782: 
1.126     brouard  6783:   /* Recompute Inverse */
1.203     brouard  6784:   /* for (i=1;i<=npar;i++) */
                   6785:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   6786:   /* ludcmp(a,npar,indx,&pd); */
                   6787: 
                   6788:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   6789: 
                   6790:   /* for (j=1;j<=npar;j++) { */
                   6791:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   6792:   /*   x[j]=1; */
                   6793:   /*   lubksb(a,npar,indx,x); */
                   6794:   /*   for (i=1;i<=npar;i++){  */
                   6795:   /*     y[i][j]=x[i]; */
                   6796:   /*     printf("%.3e ",y[i][j]); */
                   6797:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   6798:   /*   } */
                   6799:   /*   printf("\n"); */
                   6800:   /*   fprintf(ficlog,"\n"); */
                   6801:   /* } */
                   6802: 
                   6803:   /* Verifying the inverse matrix */
                   6804: #ifdef DEBUGHESS
                   6805:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  6806: 
1.203     brouard  6807:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   6808:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  6809: 
                   6810:   for (j=1;j<=npar;j++) {
                   6811:     for (i=1;i<=npar;i++){ 
1.203     brouard  6812:       printf("%.2f ",y[i][j]);
                   6813:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  6814:     }
                   6815:     printf("\n");
                   6816:     fprintf(ficlog,"\n");
                   6817:   }
1.203     brouard  6818: #endif
1.126     brouard  6819: 
                   6820:   free_matrix(a,1,npar,1,npar);
                   6821:   free_matrix(y,1,npar,1,npar);
                   6822:   free_vector(x,1,npar);
                   6823:   free_ivector(indx,1,npar);
1.203     brouard  6824:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  6825: 
                   6826: 
                   6827: }
                   6828: 
                   6829: /*************** hessian matrix ****************/
                   6830: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  6831: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  6832:   int i;
                   6833:   int l=1, lmax=20;
1.203     brouard  6834:   double k1,k2, res, fx;
1.132     brouard  6835:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  6836:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   6837:   int k=0,kmax=10;
                   6838:   double l1;
                   6839: 
                   6840:   fx=func(x);
                   6841:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  6842:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  6843:     l1=pow(10,l);
                   6844:     delts=delt;
                   6845:     for(k=1 ; k <kmax; k=k+1){
                   6846:       delt = delta*(l1*k);
                   6847:       p2[theta]=x[theta] +delt;
1.145     brouard  6848:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  6849:       p2[theta]=x[theta]-delt;
                   6850:       k2=func(p2)-fx;
                   6851:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  6852:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  6853:       
1.203     brouard  6854: #ifdef DEBUGHESSII
1.126     brouard  6855:       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);
                   6856:       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);
                   6857: #endif
                   6858:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   6859:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   6860:        k=kmax;
                   6861:       }
                   6862:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  6863:        k=kmax; l=lmax*10;
1.126     brouard  6864:       }
                   6865:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   6866:        delts=delt;
                   6867:       }
1.203     brouard  6868:     } /* End loop k */
1.126     brouard  6869:   }
                   6870:   delti[theta]=delts;
                   6871:   return res; 
                   6872:   
                   6873: }
                   6874: 
1.203     brouard  6875: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  6876: {
                   6877:   int i;
1.164     brouard  6878:   int l=1, lmax=20;
1.126     brouard  6879:   double k1,k2,k3,k4,res,fx;
1.132     brouard  6880:   double p2[MAXPARM+1];
1.203     brouard  6881:   int k, kmax=1;
                   6882:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  6883: 
                   6884:   int firstime=0;
1.203     brouard  6885:   
1.126     brouard  6886:   fx=func(x);
1.203     brouard  6887:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  6888:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  6889:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   6890:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  6891:     k1=func(p2)-fx;
                   6892:   
1.203     brouard  6893:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   6894:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  6895:     k2=func(p2)-fx;
                   6896:   
1.203     brouard  6897:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   6898:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  6899:     k3=func(p2)-fx;
                   6900:   
1.203     brouard  6901:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   6902:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  6903:     k4=func(p2)-fx;
1.203     brouard  6904:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   6905:     if(k1*k2*k3*k4 <0.){
1.208     brouard  6906:       firstime=1;
1.203     brouard  6907:       kmax=kmax+10;
1.208     brouard  6908:     }
                   6909:     if(kmax >=10 || firstime ==1){
1.354     brouard  6910:       /* What are the thetai and thetaj? thetai/ncovmodel thetai=(thetai-thetai%ncovmodel)/ncovmodel +thetai%ncovmodel=(line,pos)  */
1.246     brouard  6911:       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);
                   6912:       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  6913:       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);
                   6914:       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);
                   6915:     }
                   6916: #ifdef DEBUGHESSIJ
                   6917:     v1=hess[thetai][thetai];
                   6918:     v2=hess[thetaj][thetaj];
                   6919:     cv12=res;
                   6920:     /* Computing eigen value of Hessian matrix */
                   6921:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6922:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6923:     if ((lc2 <0) || (lc1 <0) ){
                   6924:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   6925:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   6926:       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);
                   6927:       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);
                   6928:     }
1.126     brouard  6929: #endif
                   6930:   }
                   6931:   return res;
                   6932: }
                   6933: 
1.203     brouard  6934:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   6935: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   6936: /* { */
                   6937: /*   int i; */
                   6938: /*   int l=1, lmax=20; */
                   6939: /*   double k1,k2,k3,k4,res,fx; */
                   6940: /*   double p2[MAXPARM+1]; */
                   6941: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   6942: /*   int k=0,kmax=10; */
                   6943: /*   double l1; */
                   6944:   
                   6945: /*   fx=func(x); */
                   6946: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   6947: /*     l1=pow(10,l); */
                   6948: /*     delts=delt; */
                   6949: /*     for(k=1 ; k <kmax; k=k+1){ */
                   6950: /*       delt = delti*(l1*k); */
                   6951: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   6952: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   6953: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   6954: /*       k1=func(p2)-fx; */
                   6955:       
                   6956: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   6957: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   6958: /*       k2=func(p2)-fx; */
                   6959:       
                   6960: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   6961: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   6962: /*       k3=func(p2)-fx; */
                   6963:       
                   6964: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   6965: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   6966: /*       k4=func(p2)-fx; */
                   6967: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   6968: /* #ifdef DEBUGHESSIJ */
                   6969: /*       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); */
                   6970: /*       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); */
                   6971: /* #endif */
                   6972: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   6973: /*     k=kmax; */
                   6974: /*       } */
                   6975: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   6976: /*     k=kmax; l=lmax*10; */
                   6977: /*       } */
                   6978: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   6979: /*     delts=delt; */
                   6980: /*       } */
                   6981: /*     } /\* End loop k *\/ */
                   6982: /*   } */
                   6983: /*   delti[theta]=delts; */
                   6984: /*   return res;  */
                   6985: /* } */
                   6986: 
                   6987: 
1.126     brouard  6988: /************** Inverse of matrix **************/
                   6989: void ludcmp(double **a, int n, int *indx, double *d) 
                   6990: { 
                   6991:   int i,imax,j,k; 
                   6992:   double big,dum,sum,temp; 
                   6993:   double *vv; 
                   6994:  
                   6995:   vv=vector(1,n); 
                   6996:   *d=1.0; 
                   6997:   for (i=1;i<=n;i++) { 
                   6998:     big=0.0; 
                   6999:     for (j=1;j<=n;j++) 
                   7000:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  7001:     if (big == 0.0){
                   7002:       printf(" Singular Hessian matrix at row %d:\n",i);
                   7003:       for (j=1;j<=n;j++) {
                   7004:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   7005:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   7006:       }
                   7007:       fflush(ficlog);
                   7008:       fclose(ficlog);
                   7009:       nrerror("Singular matrix in routine ludcmp"); 
                   7010:     }
1.126     brouard  7011:     vv[i]=1.0/big; 
                   7012:   } 
                   7013:   for (j=1;j<=n;j++) { 
                   7014:     for (i=1;i<j;i++) { 
                   7015:       sum=a[i][j]; 
                   7016:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   7017:       a[i][j]=sum; 
                   7018:     } 
                   7019:     big=0.0; 
                   7020:     for (i=j;i<=n;i++) { 
                   7021:       sum=a[i][j]; 
                   7022:       for (k=1;k<j;k++) 
                   7023:        sum -= a[i][k]*a[k][j]; 
                   7024:       a[i][j]=sum; 
                   7025:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   7026:        big=dum; 
                   7027:        imax=i; 
                   7028:       } 
                   7029:     } 
                   7030:     if (j != imax) { 
                   7031:       for (k=1;k<=n;k++) { 
                   7032:        dum=a[imax][k]; 
                   7033:        a[imax][k]=a[j][k]; 
                   7034:        a[j][k]=dum; 
                   7035:       } 
                   7036:       *d = -(*d); 
                   7037:       vv[imax]=vv[j]; 
                   7038:     } 
                   7039:     indx[j]=imax; 
                   7040:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   7041:     if (j != n) { 
                   7042:       dum=1.0/(a[j][j]); 
                   7043:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   7044:     } 
                   7045:   } 
                   7046:   free_vector(vv,1,n);  /* Doesn't work */
                   7047: ;
                   7048: } 
                   7049: 
                   7050: void lubksb(double **a, int n, int *indx, double b[]) 
                   7051: { 
                   7052:   int i,ii=0,ip,j; 
                   7053:   double sum; 
                   7054:  
                   7055:   for (i=1;i<=n;i++) { 
                   7056:     ip=indx[i]; 
                   7057:     sum=b[ip]; 
                   7058:     b[ip]=b[i]; 
                   7059:     if (ii) 
                   7060:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   7061:     else if (sum) ii=i; 
                   7062:     b[i]=sum; 
                   7063:   } 
                   7064:   for (i=n;i>=1;i--) { 
                   7065:     sum=b[i]; 
                   7066:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   7067:     b[i]=sum/a[i][i]; 
                   7068:   } 
                   7069: } 
                   7070: 
                   7071: void pstamp(FILE *fichier)
                   7072: {
1.196     brouard  7073:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  7074: }
                   7075: 
1.297     brouard  7076: void date2dmy(double date,double *day, double *month, double *year){
                   7077:   double yp=0., yp1=0., yp2=0.;
                   7078:   
                   7079:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   7080:                        fractional in yp1 */
                   7081:   *year=yp;
                   7082:   yp2=modf((yp1*12),&yp);
                   7083:   *month=yp;
                   7084:   yp1=modf((yp2*30.5),&yp);
                   7085:   *day=yp;
                   7086:   if(*day==0) *day=1;
                   7087:   if(*month==0) *month=1;
                   7088: }
                   7089: 
1.253     brouard  7090: 
                   7091: 
1.126     brouard  7092: /************ Frequencies ********************/
1.251     brouard  7093: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  7094:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   7095:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  7096: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  7097:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  7098:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  7099:   int iind=0, iage=0;
                   7100:   int mi; /* Effective wave */
                   7101:   int first;
                   7102:   double ***freq; /* Frequencies */
1.268     brouard  7103:   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 */
                   7104:   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  7105:   double *meanq, *stdq, *idq;
1.226     brouard  7106:   double **meanqt;
                   7107:   double *pp, **prop, *posprop, *pospropt;
                   7108:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   7109:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   7110:   double agebegin, ageend;
                   7111:     
                   7112:   pp=vector(1,nlstate);
1.251     brouard  7113:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  7114:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   7115:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   7116:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   7117:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  7118:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  7119:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  7120:   meanqt=matrix(1,lastpass,1,nqtveff);
                   7121:   strcpy(fileresp,"P_");
                   7122:   strcat(fileresp,fileresu);
                   7123:   /*strcat(fileresphtm,fileresu);*/
                   7124:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   7125:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   7126:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   7127:     exit(0);
                   7128:   }
1.240     brouard  7129:   
1.226     brouard  7130:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   7131:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   7132:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   7133:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   7134:     fflush(ficlog);
                   7135:     exit(70); 
                   7136:   }
                   7137:   else{
                   7138:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  7139: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  7140: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  7141:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   7142:   }
1.319     brouard  7143:   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  7144:   
1.226     brouard  7145:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   7146:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   7147:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   7148:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   7149:     fflush(ficlog);
                   7150:     exit(70); 
1.240     brouard  7151:   } else{
1.226     brouard  7152:     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  7153: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  7154: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  7155:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   7156:   }
1.319     brouard  7157:   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  7158:   
1.253     brouard  7159:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   7160:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  7161:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  7162:   j1=0;
1.126     brouard  7163:   
1.227     brouard  7164:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335     brouard  7165:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  7166:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  7167:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  7168:   
                   7169:   
1.226     brouard  7170:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   7171:      reference=low_education V1=0,V2=0
                   7172:      med_educ                V1=1 V2=0, 
                   7173:      high_educ               V1=0 V2=1
1.330     brouard  7174:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  7175:   */
1.249     brouard  7176:   dateintsum=0;
                   7177:   k2cpt=0;
                   7178: 
1.253     brouard  7179:   if(cptcoveff == 0 )
1.265     brouard  7180:     nl=1;  /* Constant and age model only */
1.253     brouard  7181:   else
                   7182:     nl=2;
1.265     brouard  7183: 
                   7184:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   7185:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335     brouard  7186:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  7187:    *     freq[s1][s2][iage] =0.
                   7188:    *     Loop on iind
                   7189:    *       ++freq[s1][s2][iage] weighted
                   7190:    *     end iind
                   7191:    *     if covariate and j!0
                   7192:    *       headers Variable on one line
                   7193:    *     endif cov j!=0
                   7194:    *     header of frequency table by age
                   7195:    *     Loop on age
                   7196:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   7197:    *       pos+=freq[s1][s2][iage] weighted
                   7198:    *       Loop on s1 initial state
                   7199:    *         fprintf(ficresp
                   7200:    *       end s1
                   7201:    *     end age
                   7202:    *     if j!=0 computes starting values
                   7203:    *     end compute starting values
                   7204:    *   end j1
                   7205:    * end nl 
                   7206:    */
1.253     brouard  7207:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   7208:     if(nj==1)
                   7209:       j=0;  /* First pass for the constant */
1.265     brouard  7210:     else{
1.335     brouard  7211:       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  7212:     }
1.251     brouard  7213:     first=1;
1.332     brouard  7214:     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  7215:       posproptt=0.;
1.330     brouard  7216:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  7217:        scanf("%d", i);*/
                   7218:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  7219:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  7220:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  7221:            freq[i][s2][m]=0;
1.251     brouard  7222:       
                   7223:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  7224:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  7225:          prop[i][m]=0;
                   7226:        posprop[i]=0;
                   7227:        pospropt[i]=0;
                   7228:       }
1.283     brouard  7229:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  7230:         idq[z1]=0.;
                   7231:         meanq[z1]=0.;
                   7232:         stdq[z1]=0.;
1.283     brouard  7233:       }
                   7234:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  7235:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  7236:       /*         meanqt[m][z1]=0.; */
                   7237:       /*       } */
                   7238:       /* }       */
1.251     brouard  7239:       /* dateintsum=0; */
                   7240:       /* k2cpt=0; */
                   7241:       
1.265     brouard  7242:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  7243:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   7244:        bool=1;
                   7245:        if(j !=0){
                   7246:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335     brouard  7247:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   7248:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  7249:                /* if(Tvaraff[z1] ==-20){ */
                   7250:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   7251:                /* }else  if(Tvaraff[z1] ==-10){ */
                   7252:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  7253:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335     brouard  7254:                /* 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); */
                   7255:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
1.338     brouard  7256:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  7257:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  7258:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  7259:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  7260:                  /* 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", */
                   7261:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   7262:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  7263:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   7264:                } /* Onlyf fixed */
                   7265:              } /* end z1 */
1.335     brouard  7266:            } /* cptcoveff > 0 */
1.251     brouard  7267:          } /* end any */
                   7268:        }/* end j==0 */
1.265     brouard  7269:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  7270:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  7271:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  7272:            m=mw[mi][iind];
                   7273:            if(j!=0){
                   7274:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335     brouard  7275:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  7276:                  if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  7277:                    /* iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /\* Good *\/ */
                   7278:                    iv= Tvar[Tmodelind[z1]]; /* Good *//* because cotvar starts now at first at ncovcol+nqv+ntv */ 
1.332     brouard  7279:                    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  7280:                                                                                      value is -1, we don't select. It differs from the 
                   7281:                                                                                      constant and age model which counts them. */
                   7282:                      bool=0; /* not selected */
                   7283:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  7284:                    /* i1=Tvaraff[z1]; */
                   7285:                    /* i2=TnsdVar[i1]; */
                   7286:                    /* i3=nbcode[i1][i2]; */
                   7287:                    /* i4=covar[i1][iind]; */
                   7288:                    /* if(i4 != i3){ */
                   7289:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  7290:                      bool=0;
                   7291:                    }
                   7292:                  }
                   7293:                }
                   7294:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   7295:            } /* end j==0 */
                   7296:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  7297:            if(bool==1){ /*Selected */
1.251     brouard  7298:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   7299:                 and mw[mi+1][iind]. dh depends on stepm. */
                   7300:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   7301:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   7302:              if(m >=firstpass && m <=lastpass){
                   7303:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   7304:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   7305:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   7306:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   7307:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   7308:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   7309:                if (m<lastpass) {
                   7310:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   7311:                  /*   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]); */
                   7312:                  if(s[m][iind]==-1)
                   7313:                    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.));
                   7314:                  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  7315:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   7316:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  7317:                      idq[z1]=idq[z1]+weight[iind];
                   7318:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   7319:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   7320:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  7321:                    }
1.284     brouard  7322:                  }
1.251     brouard  7323:                  /* if((int)agev[m][iind] == 55) */
                   7324:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   7325:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   7326:                  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  7327:                }
1.251     brouard  7328:              } /* end if between passes */  
                   7329:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   7330:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   7331:                k2cpt++;
                   7332:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  7333:              }
1.251     brouard  7334:            }else{
                   7335:              bool=1;
                   7336:            }/* end bool 2 */
                   7337:          } /* end m */
1.284     brouard  7338:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   7339:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   7340:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   7341:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   7342:          /* } */
1.251     brouard  7343:        } /* end bool */
                   7344:       } /* end iind = 1 to imx */
1.319     brouard  7345:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  7346:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   7347:       
                   7348:       
                   7349:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335     brouard  7350:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  7351:         pstamp(ficresp);
1.335     brouard  7352:       if  (cptcoveff>0 && j!=0){
1.265     brouard  7353:         pstamp(ficresp);
1.251     brouard  7354:        printf( "\n#********** Variable "); 
                   7355:        fprintf(ficresp, "\n#********** Variable "); 
                   7356:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   7357:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   7358:        fprintf(ficlog, "\n#********** Variable "); 
1.340     brouard  7359:        for (z1=1; z1<=cptcoveff; z1++){
1.251     brouard  7360:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  7361:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7362:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7363:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7364:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7365:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  7366:          }else{
1.330     brouard  7367:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7368:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7369:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7370:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7371:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  7372:          }
                   7373:        }
                   7374:        printf( "**********\n#");
                   7375:        fprintf(ficresp, "**********\n#");
                   7376:        fprintf(ficresphtm, "**********</h3>\n");
                   7377:        fprintf(ficresphtmfr, "**********</h3>\n");
                   7378:        fprintf(ficlog, "**********\n");
                   7379:       }
1.284     brouard  7380:       /*
                   7381:        Printing means of quantitative variables if any
                   7382:       */
                   7383:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  7384:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  7385:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  7386:        if(weightopt==1){
                   7387:          printf(" Weighted mean and standard deviation of");
                   7388:          fprintf(ficlog," Weighted mean and standard deviation of");
                   7389:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   7390:        }
1.311     brouard  7391:        /* mu = \frac{w x}{\sum w}
                   7392:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   7393:        */
                   7394:        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]));
                   7395:        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]));
                   7396:        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  7397:       }
                   7398:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   7399:       /*       for(m=1;m<=lastpass;m++){ */
                   7400:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   7401:       /*   } */
                   7402:       /* } */
1.283     brouard  7403: 
1.251     brouard  7404:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335     brouard  7405:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  7406:         fprintf(ficresp, " Age");
1.335     brouard  7407:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   7408:          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]]);
                   7409:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7410:        }
1.251     brouard  7411:       for(i=1; i<=nlstate;i++) {
1.335     brouard  7412:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  7413:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   7414:       }
1.335     brouard  7415:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  7416:       fprintf(ficresphtm, "\n");
                   7417:       
                   7418:       /* Header of frequency table by age */
                   7419:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   7420:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  7421:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  7422:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  7423:          if(s2!=0 && m!=0)
                   7424:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  7425:        }
1.226     brouard  7426:       }
1.251     brouard  7427:       fprintf(ficresphtmfr, "\n");
                   7428:     
                   7429:       /* For each age */
                   7430:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   7431:        fprintf(ficresphtm,"<tr>");
                   7432:        if(iage==iagemax+1){
                   7433:          fprintf(ficlog,"1");
                   7434:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   7435:        }else if(iage==iagemax+2){
                   7436:          fprintf(ficlog,"0");
                   7437:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   7438:        }else if(iage==iagemax+3){
                   7439:          fprintf(ficlog,"Total");
                   7440:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   7441:        }else{
1.240     brouard  7442:          if(first==1){
1.251     brouard  7443:            first=0;
                   7444:            printf("See log file for details...\n");
                   7445:          }
                   7446:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   7447:          fprintf(ficlog,"Age %d", iage);
                   7448:        }
1.265     brouard  7449:        for(s1=1; s1 <=nlstate ; s1++){
                   7450:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   7451:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  7452:        }
1.265     brouard  7453:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  7454:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  7455:            pos += freq[s1][m][iage];
                   7456:          if(pp[s1]>=1.e-10){
1.251     brouard  7457:            if(first==1){
1.265     brouard  7458:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  7459:            }
1.265     brouard  7460:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  7461:          }else{
                   7462:            if(first==1)
1.265     brouard  7463:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   7464:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  7465:          }
                   7466:        }
                   7467:       
1.265     brouard  7468:        for(s1=1; s1 <=nlstate ; s1++){ 
                   7469:          /* posprop[s1]=0; */
                   7470:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   7471:            pp[s1] += freq[s1][m][iage];
                   7472:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   7473:       
                   7474:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   7475:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   7476:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   7477:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   7478:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   7479:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   7480:        }
                   7481:        
                   7482:        /* Writing ficresp */
1.335     brouard  7483:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  7484:           if( iage <= iagemax){
                   7485:            fprintf(ficresp," %d",iage);
                   7486:           }
                   7487:         }else if( nj==2){
                   7488:           if( iage <= iagemax){
                   7489:            fprintf(ficresp," %d",iage);
1.335     brouard  7490:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  7491:           }
1.240     brouard  7492:        }
1.265     brouard  7493:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  7494:          if(pos>=1.e-5){
1.251     brouard  7495:            if(first==1)
1.265     brouard  7496:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   7497:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  7498:          }else{
                   7499:            if(first==1)
1.265     brouard  7500:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   7501:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  7502:          }
                   7503:          if( iage <= iagemax){
                   7504:            if(pos>=1.e-5){
1.335     brouard  7505:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  7506:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   7507:               }else if( nj==2){
                   7508:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   7509:               }
                   7510:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   7511:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   7512:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   7513:            } else{
1.335     brouard  7514:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  7515:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  7516:            }
1.240     brouard  7517:          }
1.265     brouard  7518:          pospropt[s1] +=posprop[s1];
                   7519:        } /* end loop s1 */
1.251     brouard  7520:        /* pospropt=0.; */
1.265     brouard  7521:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  7522:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  7523:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  7524:              if(first==1){
1.265     brouard  7525:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  7526:              }
1.265     brouard  7527:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   7528:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  7529:            }
1.265     brouard  7530:            if(s1!=0 && m!=0)
                   7531:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  7532:          }
1.265     brouard  7533:        } /* end loop s1 */
1.251     brouard  7534:        posproptt=0.; 
1.265     brouard  7535:        for(s1=1; s1 <=nlstate; s1++){
                   7536:          posproptt += pospropt[s1];
1.251     brouard  7537:        }
                   7538:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  7539:        fprintf(ficresphtm,"</tr>\n");
1.335     brouard  7540:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  7541:          if(iage <= iagemax)
                   7542:            fprintf(ficresp,"\n");
1.240     brouard  7543:        }
1.251     brouard  7544:        if(first==1)
                   7545:          printf("Others in log...\n");
                   7546:        fprintf(ficlog,"\n");
                   7547:       } /* end loop age iage */
1.265     brouard  7548:       
1.251     brouard  7549:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  7550:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  7551:        if(posproptt < 1.e-5){
1.265     brouard  7552:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  7553:        }else{
1.265     brouard  7554:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  7555:        }
1.226     brouard  7556:       }
1.251     brouard  7557:       fprintf(ficresphtm,"</tr>\n");
                   7558:       fprintf(ficresphtm,"</table>\n");
                   7559:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  7560:       if(posproptt < 1.e-5){
1.251     brouard  7561:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   7562:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  7563:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   7564:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  7565:        invalidvarcomb[j1]=1;
1.226     brouard  7566:       }else{
1.338     brouard  7567:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
1.251     brouard  7568:        invalidvarcomb[j1]=0;
1.226     brouard  7569:       }
1.251     brouard  7570:       fprintf(ficresphtmfr,"</table>\n");
                   7571:       fprintf(ficlog,"\n");
                   7572:       if(j!=0){
                   7573:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  7574:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  7575:          for(k=1; k <=(nlstate+ndeath); k++){
                   7576:            if (k != i) {
1.265     brouard  7577:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  7578:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  7579:                  if(j1==1){ /* All dummy covariates to zero */
                   7580:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   7581:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  7582:                    printf("%d%d ",i,k);
                   7583:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  7584:                    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]));
                   7585:                    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]));
                   7586:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  7587:                  }
1.253     brouard  7588:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   7589:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   7590:                    x[iage]= (double)iage;
                   7591:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  7592:                    /* 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  7593:                  }
1.268     brouard  7594:                  /* Some are not finite, but linreg will ignore these ages */
                   7595:                  no=0;
1.253     brouard  7596:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  7597:                  pstart[s1]=b;
                   7598:                  pstart[s1-1]=a;
1.252     brouard  7599:                }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 */ 
                   7600:                  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]);
                   7601:                  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  7602:                  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  7603:                  printf("%d%d ",i,k);
                   7604:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  7605:                  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  7606:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   7607:                  ;
                   7608:                }
                   7609:                /* printf("%12.7f )", param[i][jj][k]); */
                   7610:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  7611:                s1++; 
1.251     brouard  7612:              } /* end jj */
                   7613:            } /* end k!= i */
                   7614:          } /* end k */
1.265     brouard  7615:        } /* end i, s1 */
1.251     brouard  7616:       } /* end j !=0 */
                   7617:     } /* end selected combination of covariate j1 */
                   7618:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   7619:       printf("#Freqsummary: Starting values for the constants:\n");
                   7620:       fprintf(ficlog,"\n");
1.265     brouard  7621:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  7622:        for(k=1; k <=(nlstate+ndeath); k++){
                   7623:          if (k != i) {
                   7624:            printf("%d%d ",i,k);
                   7625:            fprintf(ficlog,"%d%d ",i,k);
                   7626:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  7627:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  7628:              if(jj==1){ /* Age has to be done */
1.265     brouard  7629:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   7630:                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]));
                   7631:                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  7632:              }
                   7633:              /* printf("%12.7f )", param[i][jj][k]); */
                   7634:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  7635:              s1++; 
1.250     brouard  7636:            }
1.251     brouard  7637:            printf("\n");
                   7638:            fprintf(ficlog,"\n");
1.250     brouard  7639:          }
                   7640:        }
1.284     brouard  7641:       } /* end of state i */
1.251     brouard  7642:       printf("#Freqsummary\n");
                   7643:       fprintf(ficlog,"\n");
1.265     brouard  7644:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   7645:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   7646:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   7647:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   7648:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   7649:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   7650:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   7651:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  7652:          /* } */
                   7653:        }
1.265     brouard  7654:       } /* end loop s1 */
1.251     brouard  7655:       
                   7656:       printf("\n");
                   7657:       fprintf(ficlog,"\n");
                   7658:     } /* end j=0 */
1.249     brouard  7659:   } /* end j */
1.252     brouard  7660: 
1.253     brouard  7661:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  7662:     for(i=1, jk=1; i <=nlstate; i++){
                   7663:       for(j=1; j <=nlstate+ndeath; j++){
                   7664:        if(j!=i){
                   7665:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   7666:          printf("%1d%1d",i,j);
                   7667:          fprintf(ficparo,"%1d%1d",i,j);
                   7668:          for(k=1; k<=ncovmodel;k++){
                   7669:            /*    printf(" %lf",param[i][j][k]); */
                   7670:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   7671:            p[jk]=pstart[jk];
                   7672:            printf(" %f ",pstart[jk]);
                   7673:            fprintf(ficparo," %f ",pstart[jk]);
                   7674:            jk++;
                   7675:          }
                   7676:          printf("\n");
                   7677:          fprintf(ficparo,"\n");
                   7678:        }
                   7679:       }
                   7680:     }
                   7681:   } /* end mle=-2 */
1.226     brouard  7682:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  7683:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  7684:   
1.226     brouard  7685:   fclose(ficresp);
                   7686:   fclose(ficresphtm);
                   7687:   fclose(ficresphtmfr);
1.283     brouard  7688:   free_vector(idq,1,nqfveff);
1.226     brouard  7689:   free_vector(meanq,1,nqfveff);
1.284     brouard  7690:   free_vector(stdq,1,nqfveff);
1.226     brouard  7691:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  7692:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   7693:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  7694:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  7695:   free_vector(pospropt,1,nlstate);
                   7696:   free_vector(posprop,1,nlstate);
1.251     brouard  7697:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  7698:   free_vector(pp,1,nlstate);
                   7699:   /* End of freqsummary */
                   7700: }
1.126     brouard  7701: 
1.268     brouard  7702: /* Simple linear regression */
                   7703: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   7704: 
                   7705:   /* y=a+bx regression */
                   7706:   double   sumx = 0.0;                        /* sum of x                      */
                   7707:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   7708:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   7709:   double   sumy = 0.0;                        /* sum of y                      */
                   7710:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   7711:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   7712:   double yhat;
                   7713:   
                   7714:   double denom=0;
                   7715:   int i;
                   7716:   int ne=*no;
                   7717:   
                   7718:   for ( i=ifi, ne=0;i<=ila;i++) {
                   7719:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   7720:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   7721:       continue;
                   7722:     }
                   7723:     ne=ne+1;
                   7724:     sumx  += x[i];       
                   7725:     sumx2 += x[i]*x[i];  
                   7726:     sumxy += x[i] * y[i];
                   7727:     sumy  += y[i];      
                   7728:     sumy2 += y[i]*y[i]; 
                   7729:     denom = (ne * sumx2 - sumx*sumx);
                   7730:     /* 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); */
                   7731:   } 
                   7732:   
                   7733:   denom = (ne * sumx2 - sumx*sumx);
                   7734:   if (denom == 0) {
                   7735:     // vertical, slope m is infinity
                   7736:     *b = INFINITY;
                   7737:     *a = 0;
                   7738:     if (r) *r = 0;
                   7739:     return 1;
                   7740:   }
                   7741:   
                   7742:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   7743:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   7744:   if (r!=NULL) {
                   7745:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   7746:       sqrt((sumx2 - sumx*sumx/ne) *
                   7747:           (sumy2 - sumy*sumy/ne));
                   7748:   }
                   7749:   *no=ne;
                   7750:   for ( i=ifi, ne=0;i<=ila;i++) {
                   7751:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   7752:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   7753:       continue;
                   7754:     }
                   7755:     ne=ne+1;
                   7756:     yhat = y[i] - *a -*b* x[i];
                   7757:     sume2  += yhat * yhat ;       
                   7758:     
                   7759:     denom = (ne * sumx2 - sumx*sumx);
                   7760:     /* 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); */
                   7761:   } 
                   7762:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   7763:   *sa= *sb * sqrt(sumx2/ne);
                   7764:   
                   7765:   return 0; 
                   7766: }
                   7767: 
1.126     brouard  7768: /************ Prevalence ********************/
1.227     brouard  7769: 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)
                   7770: {  
                   7771:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   7772:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   7773:      We still use firstpass and lastpass as another selection.
                   7774:   */
1.126     brouard  7775:  
1.227     brouard  7776:   int i, m, jk, j1, bool, z1,j, iv;
                   7777:   int mi; /* Effective wave */
                   7778:   int iage;
1.359     brouard  7779:   double agebegin; /*, ageend;*/
1.227     brouard  7780: 
                   7781:   double **prop;
                   7782:   double posprop; 
                   7783:   double  y2; /* in fractional years */
                   7784:   int iagemin, iagemax;
                   7785:   int first; /** to stop verbosity which is redirected to log file */
                   7786: 
                   7787:   iagemin= (int) agemin;
                   7788:   iagemax= (int) agemax;
                   7789:   /*pp=vector(1,nlstate);*/
1.251     brouard  7790:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  7791:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   7792:   j1=0;
1.222     brouard  7793:   
1.227     brouard  7794:   /*j=cptcoveff;*/
                   7795:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  7796:   
1.288     brouard  7797:   first=0;
1.335     brouard  7798:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  7799:     for (i=1; i<=nlstate; i++)  
1.251     brouard  7800:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  7801:        prop[i][iage]=0.0;
                   7802:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   7803:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   7804:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   7805:     
                   7806:     for (i=1; i<=imx; i++) { /* Each individual */
                   7807:       bool=1;
                   7808:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   7809:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   7810:        m=mw[mi][i];
                   7811:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   7812:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   7813:        for (z1=1; z1<=cptcoveff; z1++){
                   7814:          if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  7815:            iv= Tvar[Tmodelind[z1]];/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.332     brouard  7816:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  7817:              bool=0;
                   7818:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  7819:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  7820:              bool=0;
                   7821:            }
                   7822:        }
                   7823:        if(bool==1){ /* Otherwise we skip that wave/person */
                   7824:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   7825:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   7826:          if(m >=firstpass && m <=lastpass){
                   7827:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   7828:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   7829:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   7830:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  7831:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  7832:                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); 
                   7833:                exit(1);
                   7834:              }
                   7835:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   7836:                /*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]]);*/
                   7837:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   7838:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   7839:              } /* end valid statuses */ 
                   7840:            } /* end selection of dates */
                   7841:          } /* end selection of waves */
                   7842:        } /* end bool */
                   7843:       } /* end wave */
                   7844:     } /* end individual */
                   7845:     for(i=iagemin; i <= iagemax+3; i++){  
                   7846:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   7847:        posprop += prop[jk][i]; 
                   7848:       } 
                   7849:       
                   7850:       for(jk=1; jk <=nlstate ; jk++){      
                   7851:        if( i <=  iagemax){ 
                   7852:          if(posprop>=1.e-5){ 
                   7853:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   7854:          } else{
1.288     brouard  7855:            if(!first){
                   7856:              first=1;
1.266     brouard  7857:              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]);
                   7858:            }else{
1.288     brouard  7859:              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  7860:            }
                   7861:          }
                   7862:        } 
                   7863:       }/* end jk */ 
                   7864:     }/* end i */ 
1.222     brouard  7865:      /*} *//* end i1 */
1.227     brouard  7866:   } /* end j1 */
1.222     brouard  7867:   
1.227     brouard  7868:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   7869:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  7870:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  7871: }  /* End of prevalence */
1.126     brouard  7872: 
                   7873: /************* Waves Concatenation ***************/
                   7874: 
                   7875: 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)
                   7876: {
1.298     brouard  7877:   /* 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  7878:      Death is a valid wave (if date is known).
                   7879:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   7880:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  7881:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  7882:   */
1.126     brouard  7883: 
1.224     brouard  7884:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  7885:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   7886:      double sum=0., jmean=0.;*/
1.224     brouard  7887:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  7888:   int j, k=0,jk, ju, jl;
                   7889:   double sum=0.;
                   7890:   first=0;
1.214     brouard  7891:   firstwo=0;
1.217     brouard  7892:   firsthree=0;
1.218     brouard  7893:   firstfour=0;
1.164     brouard  7894:   jmin=100000;
1.126     brouard  7895:   jmax=-1;
                   7896:   jmean=0.;
1.224     brouard  7897: 
                   7898: /* Treating live states */
1.214     brouard  7899:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  7900:     mi=0;  /* First valid wave */
1.227     brouard  7901:     mli=0; /* Last valid wave */
1.309     brouard  7902:     m=firstpass;  /* Loop on waves */
                   7903:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  7904:       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 */
                   7905:        mli=m-1;/* mw[++mi][i]=m-1; */
                   7906:       }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  7907:        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  7908:        mli=m;
1.224     brouard  7909:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   7910:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  7911:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  7912:       }
1.309     brouard  7913:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  7914: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  7915:        break;
1.224     brouard  7916: #else
1.317     brouard  7917:        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  7918:          if(firsthree == 0){
1.302     brouard  7919:            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  7920:            firsthree=1;
1.317     brouard  7921:          }else if(firsthree >=1 && firsthree < 10){
                   7922:            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);
                   7923:            firsthree++;
                   7924:          }else if(firsthree == 10){
                   7925:            printf("Information, too many Information flags: no more reported to log either\n");
                   7926:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   7927:            firsthree++;
                   7928:          }else{
                   7929:            firsthree++;
1.227     brouard  7930:          }
1.309     brouard  7931:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  7932:          mli=m;
                   7933:        }
                   7934:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   7935:          nbwarn++;
1.309     brouard  7936:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  7937:            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);
                   7938:            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);
                   7939:          }
                   7940:          break;
                   7941:        }
                   7942:        break;
1.224     brouard  7943: #endif
1.227     brouard  7944:       }/* End m >= lastpass */
1.126     brouard  7945:     }/* end while */
1.224     brouard  7946: 
1.227     brouard  7947:     /* 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  7948:     /* After last pass */
1.224     brouard  7949: /* Treating death states */
1.214     brouard  7950:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  7951:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   7952:       /* } */
1.126     brouard  7953:       mi++;    /* Death is another wave */
                   7954:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  7955:       /* Only death is a correct wave */
1.126     brouard  7956:       mw[mi][i]=m;
1.257     brouard  7957:     } /* else not in a death state */
1.224     brouard  7958: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  7959:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  7960:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  7961:        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  7962:          nbwarn++;
                   7963:          if(firstfiv==0){
1.309     brouard  7964:            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  7965:            firstfiv=1;
                   7966:          }else{
1.309     brouard  7967:            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  7968:          }
1.309     brouard  7969:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   7970:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  7971:          nberr++;
                   7972:          if(firstwo==0){
1.309     brouard  7973:            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  7974:            firstwo=1;
                   7975:          }
1.309     brouard  7976:          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  7977:        }
1.257     brouard  7978:       }else{ /* if date of interview is unknown */
1.227     brouard  7979:        /* death is known but not confirmed by death status at any wave */
                   7980:        if(firstfour==0){
1.309     brouard  7981:          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  7982:          firstfour=1;
                   7983:        }
1.309     brouard  7984:        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  7985:       }
1.224     brouard  7986:     } /* end if date of death is known */
                   7987: #endif
1.309     brouard  7988:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   7989:     /* wav[i]=mw[mi][i];   */
1.126     brouard  7990:     if(mi==0){
                   7991:       nbwarn++;
                   7992:       if(first==0){
1.227     brouard  7993:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   7994:        first=1;
1.126     brouard  7995:       }
                   7996:       if(first==1){
1.227     brouard  7997:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  7998:       }
                   7999:     } /* end mi==0 */
                   8000:   } /* End individuals */
1.214     brouard  8001:   /* wav and mw are no more changed */
1.223     brouard  8002:        
1.317     brouard  8003:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   8004:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   8005: 
                   8006: 
1.126     brouard  8007:   for(i=1; i<=imx; i++){
                   8008:     for(mi=1; mi<wav[i];mi++){
                   8009:       if (stepm <=0)
1.227     brouard  8010:        dh[mi][i]=1;
1.126     brouard  8011:       else{
1.260     brouard  8012:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  8013:          if (agedc[i] < 2*AGESUP) {
                   8014:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   8015:            if(j==0) j=1;  /* Survives at least one month after exam */
                   8016:            else if(j<0){
                   8017:              nberr++;
1.359     brouard  8018:              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  8019:              j=1; /* Temporary Dangerous patch */
                   8020:              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  8021:              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  8022:              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);
                   8023:            }
                   8024:            k=k+1;
                   8025:            if (j >= jmax){
                   8026:              jmax=j;
                   8027:              ijmax=i;
                   8028:            }
                   8029:            if (j <= jmin){
                   8030:              jmin=j;
                   8031:              ijmin=i;
                   8032:            }
                   8033:            sum=sum+j;
                   8034:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   8035:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   8036:          }
                   8037:        }
                   8038:        else{
                   8039:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  8040: /*       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  8041:                                        
1.227     brouard  8042:          k=k+1;
                   8043:          if (j >= jmax) {
                   8044:            jmax=j;
                   8045:            ijmax=i;
                   8046:          }
                   8047:          else if (j <= jmin){
                   8048:            jmin=j;
                   8049:            ijmin=i;
                   8050:          }
                   8051:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   8052:          /*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]);*/
                   8053:          if(j<0){
                   8054:            nberr++;
1.359     brouard  8055:            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]);
                   8056:            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  8057:          }
                   8058:          sum=sum+j;
                   8059:        }
                   8060:        jk= j/stepm;
                   8061:        jl= j -jk*stepm;
                   8062:        ju= j -(jk+1)*stepm;
                   8063:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   8064:          if(jl==0){
                   8065:            dh[mi][i]=jk;
                   8066:            bh[mi][i]=0;
                   8067:          }else{ /* We want a negative bias in order to only have interpolation ie
                   8068:                  * to avoid the price of an extra matrix product in likelihood */
                   8069:            dh[mi][i]=jk+1;
                   8070:            bh[mi][i]=ju;
                   8071:          }
                   8072:        }else{
                   8073:          if(jl <= -ju){
                   8074:            dh[mi][i]=jk;
                   8075:            bh[mi][i]=jl;       /* bias is positive if real duration
                   8076:                                 * is higher than the multiple of stepm and negative otherwise.
                   8077:                                 */
                   8078:          }
                   8079:          else{
                   8080:            dh[mi][i]=jk+1;
                   8081:            bh[mi][i]=ju;
                   8082:          }
                   8083:          if(dh[mi][i]==0){
                   8084:            dh[mi][i]=1; /* At least one step */
                   8085:            bh[mi][i]=ju; /* At least one step */
                   8086:            /*  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);*/
                   8087:          }
                   8088:        } /* end if mle */
1.126     brouard  8089:       }
                   8090:     } /* end wave */
                   8091:   }
                   8092:   jmean=sum/k;
                   8093:   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  8094:   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  8095: }
1.126     brouard  8096: 
                   8097: /*********** Tricode ****************************/
1.220     brouard  8098:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  8099:  {
                   8100:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   8101:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   8102:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   8103:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   8104:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   8105:     */
1.130     brouard  8106: 
1.242     brouard  8107:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   8108:    int modmaxcovj=0; /* Modality max of covariates j */
                   8109:    int cptcode=0; /* Modality max of covariates j */
                   8110:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  8111: 
                   8112: 
1.242     brouard  8113:    /* cptcoveff=0;  */
                   8114:    /* *cptcov=0; */
1.126     brouard  8115:  
1.242     brouard  8116:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  8117:    for (k=1; k <= maxncov; k++)
                   8118:      for(j=1; j<=2; j++)
                   8119:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  8120: 
1.242     brouard  8121:    /* Loop on covariates without age and products and no quantitative variable */
1.335     brouard  8122:    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  8123:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
1.343     brouard  8124:      /* printf("Testing k=%d, cptcovt=%d\n",k, cptcovt); */
1.349     brouard  8125:      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  8126:        switch(Fixed[k]) {
                   8127:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  8128:         modmaxcovj=0;
                   8129:         modmincovj=0;
1.242     brouard  8130:         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  8131:           /* 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  8132:           ij=(int)(covar[Tvar[k]][i]);
                   8133:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   8134:            * If product of Vn*Vm, still boolean *:
                   8135:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   8136:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   8137:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   8138:              modality of the nth covariate of individual i. */
                   8139:           if (ij > modmaxcovj)
                   8140:             modmaxcovj=ij; 
                   8141:           else if (ij < modmincovj) 
                   8142:             modmincovj=ij; 
1.287     brouard  8143:           if (ij <0 || ij >1 ){
1.311     brouard  8144:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   8145:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   8146:             fflush(ficlog);
                   8147:             exit(1);
1.287     brouard  8148:           }
                   8149:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  8150:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   8151:             exit(1);
                   8152:           }else
                   8153:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   8154:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   8155:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   8156:           /* getting the maximum value of the modality of the covariate
                   8157:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   8158:              female ies 1, then modmaxcovj=1.
                   8159:           */
                   8160:         } /* end for loop on individuals i */
                   8161:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   8162:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   8163:         cptcode=modmaxcovj;
                   8164:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   8165:         /*for (i=0; i<=cptcode; i++) {*/
                   8166:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   8167:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   8168:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   8169:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   8170:             if( j != -1){
                   8171:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   8172:                                  covariate for which somebody answered excluding 
                   8173:                                  undefined. Usually 2: 0 and 1. */
                   8174:             }
                   8175:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   8176:                                     covariate for which somebody answered including 
                   8177:                                     undefined. Usually 3: -1, 0 and 1. */
                   8178:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   8179:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   8180:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  8181:                        
1.242     brouard  8182:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   8183:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   8184:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   8185:         /* modmincovj=3; modmaxcovj = 7; */
                   8186:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   8187:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   8188:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   8189:         /* nbcode[Tvar[j]][ij]=k; */
                   8190:         /* nbcode[Tvar[j]][1]=0; */
                   8191:         /* nbcode[Tvar[j]][2]=1; */
                   8192:         /* nbcode[Tvar[j]][3]=2; */
                   8193:         /* To be continued (not working yet). */
                   8194:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  8195: 
                   8196:         /* 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*/
                   8197:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   8198:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   8199:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   8200:         /*, could be restored in the future */
                   8201:         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  8202:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   8203:             break;
                   8204:           }
                   8205:           ij++;
1.287     brouard  8206:           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  8207:           cptcode = ij; /* New max modality for covar j */
                   8208:         } /* end of loop on modality i=-1 to 1 or more */
                   8209:         break;
                   8210:        case 1: /* Testing on varying covariate, could be simple and
                   8211:                * should look at waves or product of fixed *
                   8212:                * varying. No time to test -1, assuming 0 and 1 only */
                   8213:         ij=0;
                   8214:         for(i=0; i<=1;i++){
                   8215:           nbcode[Tvar[k]][++ij]=i;
                   8216:         }
                   8217:         break;
                   8218:        default:
                   8219:         break;
                   8220:        } /* end switch */
                   8221:      } /* end dummy test */
1.349     brouard  8222:      if(Dummy[k]==1 && Typevar[k] !=1 && Typevar[k] !=3 && Fixed ==0){ /* Fixed Quantitative covariate and not age product */ 
1.311     brouard  8223:        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  8224:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   8225:           printf("Error k=%d \n",k);
                   8226:           exit(1);
                   8227:         }
1.311     brouard  8228:         if(isnan(covar[Tvar[k]][i])){
                   8229:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   8230:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   8231:           fflush(ficlog);
                   8232:           exit(1);
                   8233:          }
                   8234:        }
1.335     brouard  8235:      } /* end Quanti */
1.287     brouard  8236:    } /* 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  8237:   
                   8238:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   8239:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   8240:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   8241:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   8242:      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 */ 
                   8243:      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 */
                   8244:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   8245:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   8246:   
                   8247:    ij=0;
                   8248:    /* 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  8249:    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 */
                   8250:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  8251:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   8252:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335     brouard  8253:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   8254:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   8255:        /* 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  8256:        /* If product not in single variable we don't print results */
                   8257:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335     brouard  8258:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   8259:        /* k=       1    2   3     4       5       6      7       8        9  */
                   8260:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   8261:        /* ij            1    2                                            3  */  
                   8262:        /* Tvaraff[ij]=  4    3                                            1  */
                   8263:        /* Tmodelind[ij]=2    3                                            9  */
                   8264:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  8265:        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*/
                   8266:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   8267:        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 */
                   8268:        if(Fixed[k]!=0)
                   8269:         anyvaryingduminmodel=1;
                   8270:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   8271:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   8272:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   8273:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   8274:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   8275:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   8276:      } 
                   8277:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   8278:    /* ij--; */
                   8279:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335     brouard  8280:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  8281:                * because they can be excluded from the model and real
                   8282:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   8283:    for(j=ij+1; j<= cptcovt; j++){
                   8284:      Tvaraff[j]=0;
                   8285:      Tmodelind[j]=0;
                   8286:    }
                   8287:    for(j=ntveff+1; j<= cptcovt; j++){
                   8288:      TmodelInvind[j]=0;
                   8289:    }
                   8290:    /* To be sorted */
                   8291:    ;
                   8292:  }
1.126     brouard  8293: 
1.145     brouard  8294: 
1.126     brouard  8295: /*********** Health Expectancies ****************/
                   8296: 
1.235     brouard  8297:  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  8298: 
                   8299: {
                   8300:   /* Health expectancies, no variances */
1.329     brouard  8301:   /* cij is the combination in the list of combination of dummy covariates */
                   8302:   /* strstart is a string of time at start of computing */
1.164     brouard  8303:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  8304:   int nhstepma, nstepma; /* Decreasing with age */
                   8305:   double age, agelim, hf;
                   8306:   double ***p3mat;
                   8307:   double eip;
                   8308: 
1.238     brouard  8309:   /* pstamp(ficreseij); */
1.126     brouard  8310:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   8311:   fprintf(ficreseij,"# Age");
                   8312:   for(i=1; i<=nlstate;i++){
                   8313:     for(j=1; j<=nlstate;j++){
                   8314:       fprintf(ficreseij," e%1d%1d ",i,j);
                   8315:     }
                   8316:     fprintf(ficreseij," e%1d. ",i);
                   8317:   }
                   8318:   fprintf(ficreseij,"\n");
                   8319: 
                   8320:   
                   8321:   if(estepm < stepm){
                   8322:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8323:   }
                   8324:   else  hstepm=estepm;   
                   8325:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   8326:    * This is mainly to measure the difference between two models: for example
                   8327:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   8328:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   8329:    * progression in between and thus overestimating or underestimating according
                   8330:    * to the curvature of the survival function. If, for the same date, we 
                   8331:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   8332:    * to compare the new estimate of Life expectancy with the same linear 
                   8333:    * hypothesis. A more precise result, taking into account a more precise
                   8334:    * curvature will be obtained if estepm is as small as stepm. */
                   8335: 
                   8336:   /* For example we decided to compute the life expectancy with the smallest unit */
                   8337:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   8338:      nhstepm is the number of hstepm from age to agelim 
                   8339:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  8340:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  8341:      and note for a fixed period like estepm months */
                   8342:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   8343:      survival function given by stepm (the optimization length). Unfortunately it
                   8344:      means that if the survival funtion is printed only each two years of age and if
                   8345:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   8346:      results. So we changed our mind and took the option of the best precision.
                   8347:   */
                   8348:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   8349: 
                   8350:   agelim=AGESUP;
                   8351:   /* If stepm=6 months */
                   8352:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   8353:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   8354:     
                   8355: /* nhstepm age range expressed in number of stepm */
                   8356:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   8357:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   8358:   /* if (stepm >= YEARM) hstepm=1;*/
                   8359:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   8360:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8361: 
                   8362:   for (age=bage; age<=fage; age ++){ 
                   8363:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   8364:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   8365:     /* if (stepm >= YEARM) hstepm=1;*/
                   8366:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   8367: 
                   8368:     /* If stepm=6 months */
                   8369:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   8370:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  8371:     /* 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  8372:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  8373:     
                   8374:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   8375:     
                   8376:     printf("%d|",(int)age);fflush(stdout);
                   8377:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   8378:     
                   8379:     /* Computing expectancies */
                   8380:     for(i=1; i<=nlstate;i++)
                   8381:       for(j=1; j<=nlstate;j++)
                   8382:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   8383:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   8384:          
                   8385:          /* 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]);*/
                   8386: 
                   8387:        }
                   8388: 
                   8389:     fprintf(ficreseij,"%3.0f",age );
                   8390:     for(i=1; i<=nlstate;i++){
                   8391:       eip=0;
                   8392:       for(j=1; j<=nlstate;j++){
                   8393:        eip +=eij[i][j][(int)age];
                   8394:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   8395:       }
                   8396:       fprintf(ficreseij,"%9.4f", eip );
                   8397:     }
                   8398:     fprintf(ficreseij,"\n");
                   8399:     
                   8400:   }
                   8401:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8402:   printf("\n");
                   8403:   fprintf(ficlog,"\n");
                   8404:   
                   8405: }
                   8406: 
1.235     brouard  8407:  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  8408: 
                   8409: {
                   8410:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  8411:      to initial status i, ei. .
1.126     brouard  8412:   */
1.336     brouard  8413:   /* Very time consuming function, but already optimized with precov */
1.126     brouard  8414:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   8415:   int nhstepma, nstepma; /* Decreasing with age */
                   8416:   double age, agelim, hf;
                   8417:   double ***p3matp, ***p3matm, ***varhe;
                   8418:   double **dnewm,**doldm;
                   8419:   double *xp, *xm;
                   8420:   double **gp, **gm;
                   8421:   double ***gradg, ***trgradg;
                   8422:   int theta;
                   8423: 
                   8424:   double eip, vip;
                   8425: 
                   8426:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   8427:   xp=vector(1,npar);
                   8428:   xm=vector(1,npar);
                   8429:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   8430:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   8431:   
                   8432:   pstamp(ficresstdeij);
                   8433:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   8434:   fprintf(ficresstdeij,"# Age");
                   8435:   for(i=1; i<=nlstate;i++){
                   8436:     for(j=1; j<=nlstate;j++)
                   8437:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   8438:     fprintf(ficresstdeij," e%1d. ",i);
                   8439:   }
                   8440:   fprintf(ficresstdeij,"\n");
                   8441: 
                   8442:   pstamp(ficrescveij);
                   8443:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   8444:   fprintf(ficrescveij,"# Age");
                   8445:   for(i=1; i<=nlstate;i++)
                   8446:     for(j=1; j<=nlstate;j++){
                   8447:       cptj= (j-1)*nlstate+i;
                   8448:       for(i2=1; i2<=nlstate;i2++)
                   8449:        for(j2=1; j2<=nlstate;j2++){
                   8450:          cptj2= (j2-1)*nlstate+i2;
                   8451:          if(cptj2 <= cptj)
                   8452:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   8453:        }
                   8454:     }
                   8455:   fprintf(ficrescveij,"\n");
                   8456:   
                   8457:   if(estepm < stepm){
                   8458:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8459:   }
                   8460:   else  hstepm=estepm;   
                   8461:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   8462:    * This is mainly to measure the difference between two models: for example
                   8463:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   8464:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   8465:    * progression in between and thus overestimating or underestimating according
                   8466:    * to the curvature of the survival function. If, for the same date, we 
                   8467:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   8468:    * to compare the new estimate of Life expectancy with the same linear 
                   8469:    * hypothesis. A more precise result, taking into account a more precise
                   8470:    * curvature will be obtained if estepm is as small as stepm. */
                   8471: 
                   8472:   /* For example we decided to compute the life expectancy with the smallest unit */
                   8473:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   8474:      nhstepm is the number of hstepm from age to agelim 
                   8475:      nstepm is the number of stepm from age to agelin. 
                   8476:      Look at hpijx to understand the reason of that which relies in memory size
                   8477:      and note for a fixed period like estepm months */
                   8478:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   8479:      survival function given by stepm (the optimization length). Unfortunately it
                   8480:      means that if the survival funtion is printed only each two years of age and if
                   8481:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   8482:      results. So we changed our mind and took the option of the best precision.
                   8483:   */
                   8484:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   8485: 
                   8486:   /* If stepm=6 months */
                   8487:   /* nhstepm age range expressed in number of stepm */
                   8488:   agelim=AGESUP;
                   8489:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   8490:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   8491:   /* if (stepm >= YEARM) hstepm=1;*/
                   8492:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   8493:   
                   8494:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8495:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8496:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   8497:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   8498:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   8499:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   8500: 
                   8501:   for (age=bage; age<=fage; age ++){ 
                   8502:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   8503:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   8504:     /* if (stepm >= YEARM) hstepm=1;*/
                   8505:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  8506:                
1.126     brouard  8507:     /* If stepm=6 months */
                   8508:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   8509:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   8510:     
                   8511:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  8512:                
1.126     brouard  8513:     /* Computing  Variances of health expectancies */
                   8514:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   8515:        decrease memory allocation */
                   8516:     for(theta=1; theta <=npar; theta++){
                   8517:       for(i=1; i<=npar; i++){ 
1.222     brouard  8518:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   8519:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  8520:       }
1.235     brouard  8521:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   8522:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  8523:                        
1.126     brouard  8524:       for(j=1; j<= nlstate; j++){
1.222     brouard  8525:        for(i=1; i<=nlstate; i++){
                   8526:          for(h=0; h<=nhstepm-1; h++){
                   8527:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   8528:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   8529:          }
                   8530:        }
1.126     brouard  8531:       }
1.218     brouard  8532:                        
1.126     brouard  8533:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  8534:        for(h=0; h<=nhstepm-1; h++){
                   8535:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   8536:        }
1.126     brouard  8537:     }/* End theta */
                   8538:     
                   8539:     
                   8540:     for(h=0; h<=nhstepm-1; h++)
                   8541:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  8542:        for(theta=1; theta <=npar; theta++)
                   8543:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  8544:     
1.218     brouard  8545:                
1.222     brouard  8546:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  8547:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  8548:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  8549:                
1.222     brouard  8550:     printf("%d|",(int)age);fflush(stdout);
                   8551:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   8552:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  8553:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  8554:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   8555:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   8556:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   8557:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   8558:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  8559:       }
                   8560:     }
1.320     brouard  8561:     /* if((int)age ==50){ */
                   8562:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   8563:     /* } */
1.126     brouard  8564:     /* Computing expectancies */
1.235     brouard  8565:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  8566:     for(i=1; i<=nlstate;i++)
                   8567:       for(j=1; j<=nlstate;j++)
1.222     brouard  8568:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   8569:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  8570:                                        
1.222     brouard  8571:          /* 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  8572:                                        
1.222     brouard  8573:        }
1.269     brouard  8574: 
                   8575:     /* Standard deviation of expectancies ij */                
1.126     brouard  8576:     fprintf(ficresstdeij,"%3.0f",age );
                   8577:     for(i=1; i<=nlstate;i++){
                   8578:       eip=0.;
                   8579:       vip=0.;
                   8580:       for(j=1; j<=nlstate;j++){
1.222     brouard  8581:        eip += eij[i][j][(int)age];
                   8582:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   8583:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   8584:        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  8585:       }
                   8586:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   8587:     }
                   8588:     fprintf(ficresstdeij,"\n");
1.218     brouard  8589:                
1.269     brouard  8590:     /* Variance of expectancies ij */          
1.126     brouard  8591:     fprintf(ficrescveij,"%3.0f",age );
                   8592:     for(i=1; i<=nlstate;i++)
                   8593:       for(j=1; j<=nlstate;j++){
1.222     brouard  8594:        cptj= (j-1)*nlstate+i;
                   8595:        for(i2=1; i2<=nlstate;i2++)
                   8596:          for(j2=1; j2<=nlstate;j2++){
                   8597:            cptj2= (j2-1)*nlstate+i2;
                   8598:            if(cptj2 <= cptj)
                   8599:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   8600:          }
1.126     brouard  8601:       }
                   8602:     fprintf(ficrescveij,"\n");
1.218     brouard  8603:                
1.126     brouard  8604:   }
                   8605:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   8606:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   8607:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   8608:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   8609:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8610:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8611:   printf("\n");
                   8612:   fprintf(ficlog,"\n");
1.218     brouard  8613:        
1.126     brouard  8614:   free_vector(xm,1,npar);
                   8615:   free_vector(xp,1,npar);
                   8616:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   8617:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   8618:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   8619: }
1.218     brouard  8620:  
1.126     brouard  8621: /************ Variance ******************/
1.235     brouard  8622:  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  8623:  {
1.361     brouard  8624:    /** Computes the matrix of variance covariance of health expectancies e.j= sum_i w_i e_ij where w_i depends of popbased,
                   8625:     * either cross-sectional or implied.
                   8626:     * 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  8627:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   8628:     * double **newm;
                   8629:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   8630:     */
1.218     brouard  8631:   
                   8632:    /* int movingaverage(); */
                   8633:    double **dnewm,**doldm;
                   8634:    double **dnewmp,**doldmp;
                   8635:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  8636:    int first=0;
1.218     brouard  8637:    int k;
                   8638:    double *xp;
1.279     brouard  8639:    double **gp, **gm;  /**< for var eij */
                   8640:    double ***gradg, ***trgradg; /**< for var eij */
                   8641:    double **gradgp, **trgradgp; /**< for var p point j */
                   8642:    double *gpp, *gmp; /**< for var p point j */
1.362     brouard  8643:    double **varppt; /**< for var p.3 p.death nlstate+1 to nlstate+ndeath */
1.218     brouard  8644:    double ***p3mat;
                   8645:    double age,agelim, hf;
                   8646:    /* double ***mobaverage; */
                   8647:    int theta;
                   8648:    char digit[4];
                   8649:    char digitp[25];
                   8650: 
                   8651:    char fileresprobmorprev[FILENAMELENGTH];
                   8652: 
                   8653:    if(popbased==1){
                   8654:      if(mobilav!=0)
                   8655:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   8656:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   8657:    }
                   8658:    else 
                   8659:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  8660: 
1.218     brouard  8661:    /* if (mobilav!=0) { */
                   8662:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8663:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   8664:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   8665:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   8666:    /*   } */
                   8667:    /* } */
                   8668: 
                   8669:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   8670:    sprintf(digit,"%-d",ij);
                   8671:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   8672:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   8673:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   8674:    strcat(fileresprobmorprev,fileresu);
                   8675:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   8676:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   8677:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   8678:    }
                   8679:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   8680:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   8681:    pstamp(ficresprobmorprev);
                   8682:    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  8683:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.337     brouard  8684: 
                   8685:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
                   8686:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
                   8687:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   8688:    /* } */
                   8689:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
1.344     brouard  8690:      /* fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); */
1.337     brouard  8691:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  8692:    }
1.337     brouard  8693:    /* for(j=1;j<=cptcoveff;j++)  */
                   8694:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
1.238     brouard  8695:    fprintf(ficresprobmorprev,"\n");
                   8696: 
1.218     brouard  8697:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   8698:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   8699:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   8700:      for(i=1; i<=nlstate;i++)
                   8701:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   8702:    }  
                   8703:    fprintf(ficresprobmorprev,"\n");
                   8704:   
                   8705:    fprintf(ficgp,"\n# Routine varevsij");
                   8706:    fprintf(ficgp,"\nunset title \n");
                   8707:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   8708:    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");
                   8709:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  8710: 
1.361     brouard  8711:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath); /* In fact, currently a double */
1.218     brouard  8712:    pstamp(ficresvij);
                   8713:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   8714:    if(popbased==1)
                   8715:      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);
                   8716:    else
                   8717:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   8718:    fprintf(ficresvij,"# Age");
                   8719:    for(i=1; i<=nlstate;i++)
                   8720:      for(j=1; j<=nlstate;j++)
                   8721:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   8722:    fprintf(ficresvij,"\n");
                   8723: 
                   8724:    xp=vector(1,npar);
                   8725:    dnewm=matrix(1,nlstate,1,npar);
                   8726:    doldm=matrix(1,nlstate,1,nlstate);
                   8727:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   8728:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   8729: 
                   8730:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   8731:    gpp=vector(nlstate+1,nlstate+ndeath);
                   8732:    gmp=vector(nlstate+1,nlstate+ndeath);
                   8733:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  8734:   
1.218     brouard  8735:    if(estepm < stepm){
                   8736:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   8737:    }
                   8738:    else  hstepm=estepm;   
                   8739:    /* For example we decided to compute the life expectancy with the smallest unit */
                   8740:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   8741:       nhstepm is the number of hstepm from age to agelim 
                   8742:       nstepm is the number of stepm from age to agelim. 
                   8743:       Look at function hpijx to understand why because of memory size limitations, 
                   8744:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   8745:       survival function given by stepm (the optimization length). Unfortunately it
                   8746:       means that if the survival funtion is printed every two years of age and if
                   8747:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   8748:       results. So we changed our mind and took the option of the best precision.
                   8749:    */
                   8750:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   8751:    agelim = AGESUP;
                   8752:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   8753:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   8754:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   8755:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8756:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   8757:      gp=matrix(0,nhstepm,1,nlstate);
                   8758:      gm=matrix(0,nhstepm,1,nlstate);
                   8759:                
                   8760:                
                   8761:      for(theta=1; theta <=npar; theta++){
                   8762:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   8763:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   8764:        }
1.279     brouard  8765:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   8766:        * returns into prlim .
1.288     brouard  8767:        */
1.242     brouard  8768:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  8769: 
                   8770:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  8771:        if (popbased==1) {
                   8772:         if(mobilav ==0){
                   8773:           for(i=1; i<=nlstate;i++)
                   8774:             prlim[i][i]=probs[(int)age][i][ij];
                   8775:         }else{ /* mobilav */ 
                   8776:           for(i=1; i<=nlstate;i++)
                   8777:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   8778:         }
                   8779:        }
1.361     brouard  8780:        /**< Computes the shifted plus (gp) transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  8781:        */                      
                   8782:        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  8783:        /**< 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  8784:        * at horizon h in state j including mortality.
                   8785:        */
1.218     brouard  8786:        for(j=1; j<= nlstate; j++){
                   8787:         for(h=0; h<=nhstepm; h++){
                   8788:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
1.361     brouard  8789:             gp[h][j] += prlim[i][i]*p3mat[i][j][h]; /* gp[h][j]= w_i h_pij */
1.218     brouard  8790:         }
                   8791:        }
1.279     brouard  8792:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  8793:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  8794:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  8795:        */
1.361     brouard  8796:        for(j=nlstate+1;j<=nlstate+ndeath;j++){ /* Currently only once for theta plus  p.3(age) Sum_i wi pi3*/
1.218     brouard  8797:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   8798:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  8799:        }
                   8800:        
                   8801:        /* Again with minus shift */
1.218     brouard  8802:                        
                   8803:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   8804:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  8805: 
1.242     brouard  8806:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  8807:                        
                   8808:        if (popbased==1) {
                   8809:         if(mobilav ==0){
                   8810:           for(i=1; i<=nlstate;i++)
                   8811:             prlim[i][i]=probs[(int)age][i][ij];
                   8812:         }else{ /* mobilav */ 
                   8813:           for(i=1; i<=nlstate;i++)
                   8814:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   8815:         }
                   8816:        }
                   8817:                        
1.361     brouard  8818:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  /* Still minus */
1.218     brouard  8819:                        
1.361     brouard  8820:        for(j=1; j<= nlstate; j++){  /* gm[h][j]= Sum_i of wi * pij =  h_p.j */
1.218     brouard  8821:         for(h=0; h<=nhstepm; h++){
                   8822:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   8823:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   8824:         }
                   8825:        }
                   8826:        /* This for computing probability of death (h=1 means
                   8827:          computed over hstepm matrices product = hstepm*stepm months) 
1.361     brouard  8828:          as a weighted average of prlim. j is death. gmp[3]=sum_i w_i*p_i3=p.3 minus theta
1.218     brouard  8829:        */
1.361     brouard  8830:        for(j=nlstate+1;j<=nlstate+ndeath;j++){  /* Currently only once theta_minus  p.3=Sum_i wi pi3*/
1.218     brouard  8831:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   8832:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   8833:        }    
1.279     brouard  8834:        /* end shifting computations */
                   8835: 
1.361     brouard  8836:        /**< Computing gradient of p.j matrix at horizon h and still for one parameter of vector theta
                   8837:        * equation 31 and 32
1.279     brouard  8838:        */
1.361     brouard  8839:        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)
                   8840:                                  * equation 24 */
1.218     brouard  8841:         for(h=0; h<=nhstepm; h++){
                   8842:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   8843:         }
1.361     brouard  8844:        /**< Gradient of overall mortality p.3 (or p.death) 
1.279     brouard  8845:        */
1.361     brouard  8846:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* computes grad of p.3 from wi+pi3 grad p.3 (theta) */
1.218     brouard  8847:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   8848:        }
                   8849:                        
                   8850:      } /* End theta */
1.279     brouard  8851:      
1.361     brouard  8852:      /* We got the gradient matrix for each theta and each state j of gradg(h]theta][j)=grad(_hp.j(theta) */           
                   8853:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar);
1.218     brouard  8854:                
1.361     brouard  8855:      for(h=0; h<=nhstepm; h++) /* veij */ /* computes the transposed of grad  (_hp.j(theta)*/
1.218     brouard  8856:        for(j=1; j<=nlstate;j++)
                   8857:         for(theta=1; theta <=npar; theta++)
                   8858:           trgradg[h][j][theta]=gradg[h][theta][j];
                   8859:                
1.361     brouard  8860:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* computes transposed of grad p.3 (theta)*/
1.218     brouard  8861:        for(theta=1; theta <=npar; theta++)
                   8862:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  8863:      /**< as well as its transposed matrix 
                   8864:       */               
1.218     brouard  8865:                
                   8866:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   8867:      for(i=1;i<=nlstate;i++)
                   8868:        for(j=1;j<=nlstate;j++)
                   8869:         vareij[i][j][(int)age] =0.;
1.279     brouard  8870: 
                   8871:      /* Computing trgradg by matcov by gradg at age and summing over h
1.361     brouard  8872:       * and k (nhstepm) formula 32 of article
                   8873:       * Lievre-Brouard-Heathcote so that for each j, computes the cov(e.j,e.k) (formula 31).
                   8874:       * for given h and k computes trgradg[h](i,j) matcov (theta) gradg(k)(i,j) into vareij[i][j] which is
                   8875:       cov(e.i,e.j) and sums on h and k
                   8876:       * including the covariances.
1.279     brouard  8877:       */
                   8878:      
1.218     brouard  8879:      for(h=0;h<=nhstepm;h++){
                   8880:        for(k=0;k<=nhstepm;k++){
                   8881:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   8882:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   8883:         for(i=1;i<=nlstate;i++)
                   8884:           for(j=1;j<=nlstate;j++)
1.361     brouard  8885:             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)
                   8886:                                                             including the covariances of e.j */
1.218     brouard  8887:        }
                   8888:      }
                   8889:                
1.361     brouard  8890:      /* Mortality: pptj is p.3 or p.death = trgradgp by cov by gradgp, variance of
                   8891:       * p.3=1-p..=1-sum i p.i  overall mortality computed directly because
1.279     brouard  8892:       * we compute the grad (wix pijx) instead of grad (pijx),even if
1.361     brouard  8893:       * wix is independent of theta. 
1.279     brouard  8894:       */
1.218     brouard  8895:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   8896:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   8897:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   8898:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
1.361     brouard  8899:         varppt[j][i]=doldmp[j][i];  /* This is the variance of p.3 */
1.218     brouard  8900:      /* end ppptj */
                   8901:      /*  x centered again */
                   8902:                
1.242     brouard  8903:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  8904:                
                   8905:      if (popbased==1) {
                   8906:        if(mobilav ==0){
                   8907:         for(i=1; i<=nlstate;i++)
                   8908:           prlim[i][i]=probs[(int)age][i][ij];
                   8909:        }else{ /* mobilav */ 
                   8910:         for(i=1; i<=nlstate;i++)
                   8911:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   8912:        }
                   8913:      }
                   8914:                
                   8915:      /* This for computing probability of death (h=1 means
                   8916:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   8917:        as a weighted average of prlim.
                   8918:      */
1.235     brouard  8919:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  8920:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   8921:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
1.361     brouard  8922:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; /* gmp[j] is p.3 */
1.218     brouard  8923:      }    
                   8924:      /* end probability of death */
                   8925:                
                   8926:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   8927:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
1.361     brouard  8928:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));/* p.3 (STD p.3) */
1.218     brouard  8929:        for(i=1; i<=nlstate;i++){
1.361     brouard  8930:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]); /* wi, pi3 */
1.218     brouard  8931:        }
                   8932:      } 
                   8933:      fprintf(ficresprobmorprev,"\n");
                   8934:                
                   8935:      fprintf(ficresvij,"%.0f ",age );
                   8936:      for(i=1; i<=nlstate;i++)
                   8937:        for(j=1; j<=nlstate;j++){
                   8938:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   8939:        }
                   8940:      fprintf(ficresvij,"\n");
                   8941:      free_matrix(gp,0,nhstepm,1,nlstate);
                   8942:      free_matrix(gm,0,nhstepm,1,nlstate);
                   8943:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   8944:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   8945:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8946:    } /* End age */
                   8947:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   8948:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   8949:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   8950:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   8951:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   8952:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   8953:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   8954:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   8955:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   8956:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   8957:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   8958:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   8959:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   8960:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   8961:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   8962:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   8963:    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);
                   8964:    /*  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  8965:     */
1.218     brouard  8966:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   8967:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  8968: 
1.218     brouard  8969:    free_vector(xp,1,npar);
                   8970:    free_matrix(doldm,1,nlstate,1,nlstate);
                   8971:    free_matrix(dnewm,1,nlstate,1,npar);
                   8972:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   8973:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   8974:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   8975:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8976:    fclose(ficresprobmorprev);
                   8977:    fflush(ficgp);
                   8978:    fflush(fichtm); 
                   8979:  }  /* end varevsij */
1.126     brouard  8980: 
                   8981: /************ Variance of prevlim ******************/
1.269     brouard  8982:  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  8983: {
1.205     brouard  8984:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  8985:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  8986: 
1.268     brouard  8987:   double **dnewmpar,**doldm;
1.126     brouard  8988:   int i, j, nhstepm, hstepm;
                   8989:   double *xp;
                   8990:   double *gp, *gm;
                   8991:   double **gradg, **trgradg;
1.208     brouard  8992:   double **mgm, **mgp;
1.126     brouard  8993:   double age,agelim;
                   8994:   int theta;
                   8995:   
                   8996:   pstamp(ficresvpl);
1.288     brouard  8997:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  8998:   fprintf(ficresvpl,"# Age ");
                   8999:   if(nresult >=1)
                   9000:     fprintf(ficresvpl," Result# ");
1.126     brouard  9001:   for(i=1; i<=nlstate;i++)
                   9002:       fprintf(ficresvpl," %1d-%1d",i,i);
                   9003:   fprintf(ficresvpl,"\n");
                   9004: 
                   9005:   xp=vector(1,npar);
1.268     brouard  9006:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  9007:   doldm=matrix(1,nlstate,1,nlstate);
                   9008:   
                   9009:   hstepm=1*YEARM; /* Every year of age */
                   9010:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   9011:   agelim = AGESUP;
                   9012:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   9013:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   9014:     if (stepm >= YEARM) hstepm=1;
                   9015:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   9016:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  9017:     mgp=matrix(1,npar,1,nlstate);
                   9018:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  9019:     gp=vector(1,nlstate);
                   9020:     gm=vector(1,nlstate);
                   9021: 
                   9022:     for(theta=1; theta <=npar; theta++){
                   9023:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   9024:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   9025:       }
1.288     brouard  9026:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   9027:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   9028:       /* else */
                   9029:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  9030:       for(i=1;i<=nlstate;i++){
1.126     brouard  9031:        gp[i] = prlim[i][i];
1.208     brouard  9032:        mgp[theta][i] = prlim[i][i];
                   9033:       }
1.126     brouard  9034:       for(i=1; i<=npar; i++) /* Computes gradient */
                   9035:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  9036:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   9037:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   9038:       /* else */
                   9039:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  9040:       for(i=1;i<=nlstate;i++){
1.126     brouard  9041:        gm[i] = prlim[i][i];
1.208     brouard  9042:        mgm[theta][i] = prlim[i][i];
                   9043:       }
1.126     brouard  9044:       for(i=1;i<=nlstate;i++)
                   9045:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  9046:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  9047:     } /* End theta */
                   9048: 
                   9049:     trgradg =matrix(1,nlstate,1,npar);
                   9050: 
                   9051:     for(j=1; j<=nlstate;j++)
                   9052:       for(theta=1; theta <=npar; theta++)
                   9053:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  9054:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   9055:     /*   printf("\nmgm mgp %d ",(int)age); */
                   9056:     /*   for(j=1; j<=nlstate;j++){ */
                   9057:     /*         printf(" %d ",j); */
                   9058:     /*         for(theta=1; theta <=npar; theta++) */
                   9059:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   9060:     /*         printf("\n "); */
                   9061:     /*   } */
                   9062:     /* } */
                   9063:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   9064:     /*   printf("\n gradg %d ",(int)age); */
                   9065:     /*   for(j=1; j<=nlstate;j++){ */
                   9066:     /*         printf("%d ",j); */
                   9067:     /*         for(theta=1; theta <=npar; theta++) */
                   9068:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   9069:     /*         printf("\n "); */
                   9070:     /*   } */
                   9071:     /* } */
1.126     brouard  9072: 
                   9073:     for(i=1;i<=nlstate;i++)
                   9074:       varpl[i][(int)age] =0.;
1.209     brouard  9075:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  9076:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   9077:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  9078:     }else{
1.268     brouard  9079:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   9080:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  9081:     }
1.126     brouard  9082:     for(i=1;i<=nlstate;i++)
                   9083:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   9084: 
                   9085:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  9086:     if(nresult >=1)
                   9087:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  9088:     for(i=1; i<=nlstate;i++){
1.126     brouard  9089:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  9090:       /* for(j=1;j<=nlstate;j++) */
                   9091:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   9092:     }
1.126     brouard  9093:     fprintf(ficresvpl,"\n");
                   9094:     free_vector(gp,1,nlstate);
                   9095:     free_vector(gm,1,nlstate);
1.208     brouard  9096:     free_matrix(mgm,1,npar,1,nlstate);
                   9097:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  9098:     free_matrix(gradg,1,npar,1,nlstate);
                   9099:     free_matrix(trgradg,1,nlstate,1,npar);
                   9100:   } /* End age */
                   9101: 
                   9102:   free_vector(xp,1,npar);
                   9103:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  9104:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   9105: 
                   9106: }
                   9107: 
                   9108: 
                   9109: /************ Variance of backprevalence limit ******************/
1.269     brouard  9110:  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  9111: {
                   9112:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   9113:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   9114: 
                   9115:   double **dnewmpar,**doldm;
                   9116:   int i, j, nhstepm, hstepm;
                   9117:   double *xp;
                   9118:   double *gp, *gm;
                   9119:   double **gradg, **trgradg;
                   9120:   double **mgm, **mgp;
                   9121:   double age,agelim;
                   9122:   int theta;
                   9123:   
                   9124:   pstamp(ficresvbl);
                   9125:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   9126:   fprintf(ficresvbl,"# Age ");
                   9127:   if(nresult >=1)
                   9128:     fprintf(ficresvbl," Result# ");
                   9129:   for(i=1; i<=nlstate;i++)
                   9130:       fprintf(ficresvbl," %1d-%1d",i,i);
                   9131:   fprintf(ficresvbl,"\n");
                   9132: 
                   9133:   xp=vector(1,npar);
                   9134:   dnewmpar=matrix(1,nlstate,1,npar);
                   9135:   doldm=matrix(1,nlstate,1,nlstate);
                   9136:   
                   9137:   hstepm=1*YEARM; /* Every year of age */
                   9138:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   9139:   agelim = AGEINF;
                   9140:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   9141:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   9142:     if (stepm >= YEARM) hstepm=1;
                   9143:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   9144:     gradg=matrix(1,npar,1,nlstate);
                   9145:     mgp=matrix(1,npar,1,nlstate);
                   9146:     mgm=matrix(1,npar,1,nlstate);
                   9147:     gp=vector(1,nlstate);
                   9148:     gm=vector(1,nlstate);
                   9149: 
                   9150:     for(theta=1; theta <=npar; theta++){
                   9151:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   9152:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   9153:       }
                   9154:       if(mobilavproj > 0 )
                   9155:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   9156:       else
                   9157:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   9158:       for(i=1;i<=nlstate;i++){
                   9159:        gp[i] = bprlim[i][i];
                   9160:        mgp[theta][i] = bprlim[i][i];
                   9161:       }
                   9162:      for(i=1; i<=npar; i++) /* Computes gradient */
                   9163:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   9164:        if(mobilavproj > 0 )
                   9165:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   9166:        else
                   9167:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   9168:       for(i=1;i<=nlstate;i++){
                   9169:        gm[i] = bprlim[i][i];
                   9170:        mgm[theta][i] = bprlim[i][i];
                   9171:       }
                   9172:       for(i=1;i<=nlstate;i++)
                   9173:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   9174:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   9175:     } /* End theta */
                   9176: 
                   9177:     trgradg =matrix(1,nlstate,1,npar);
                   9178: 
                   9179:     for(j=1; j<=nlstate;j++)
                   9180:       for(theta=1; theta <=npar; theta++)
                   9181:        trgradg[j][theta]=gradg[theta][j];
                   9182:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   9183:     /*   printf("\nmgm mgp %d ",(int)age); */
                   9184:     /*   for(j=1; j<=nlstate;j++){ */
                   9185:     /*         printf(" %d ",j); */
                   9186:     /*         for(theta=1; theta <=npar; theta++) */
                   9187:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   9188:     /*         printf("\n "); */
                   9189:     /*   } */
                   9190:     /* } */
                   9191:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   9192:     /*   printf("\n gradg %d ",(int)age); */
                   9193:     /*   for(j=1; j<=nlstate;j++){ */
                   9194:     /*         printf("%d ",j); */
                   9195:     /*         for(theta=1; theta <=npar; theta++) */
                   9196:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   9197:     /*         printf("\n "); */
                   9198:     /*   } */
                   9199:     /* } */
                   9200: 
                   9201:     for(i=1;i<=nlstate;i++)
                   9202:       varbpl[i][(int)age] =0.;
                   9203:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   9204:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   9205:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   9206:     }else{
                   9207:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   9208:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   9209:     }
                   9210:     for(i=1;i<=nlstate;i++)
                   9211:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   9212: 
                   9213:     fprintf(ficresvbl,"%.0f ",age );
                   9214:     if(nresult >=1)
                   9215:       fprintf(ficresvbl,"%d ",nres );
                   9216:     for(i=1; i<=nlstate;i++)
                   9217:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   9218:     fprintf(ficresvbl,"\n");
                   9219:     free_vector(gp,1,nlstate);
                   9220:     free_vector(gm,1,nlstate);
                   9221:     free_matrix(mgm,1,npar,1,nlstate);
                   9222:     free_matrix(mgp,1,npar,1,nlstate);
                   9223:     free_matrix(gradg,1,npar,1,nlstate);
                   9224:     free_matrix(trgradg,1,nlstate,1,npar);
                   9225:   } /* End age */
                   9226: 
                   9227:   free_vector(xp,1,npar);
                   9228:   free_matrix(doldm,1,nlstate,1,npar);
                   9229:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  9230: 
                   9231: }
                   9232: 
                   9233: /************ Variance of one-step probabilities  ******************/
                   9234: 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  9235:  {
                   9236:    int i, j=0,  k1, l1, tj;
                   9237:    int k2, l2, j1,  z1;
                   9238:    int k=0, l;
                   9239:    int first=1, first1, first2;
1.326     brouard  9240:    int nres=0; /* New */
1.222     brouard  9241:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   9242:    double **dnewm,**doldm;
                   9243:    double *xp;
                   9244:    double *gp, *gm;
                   9245:    double **gradg, **trgradg;
                   9246:    double **mu;
                   9247:    double age, cov[NCOVMAX+1];
                   9248:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   9249:    int theta;
                   9250:    char fileresprob[FILENAMELENGTH];
                   9251:    char fileresprobcov[FILENAMELENGTH];
                   9252:    char fileresprobcor[FILENAMELENGTH];
                   9253:    double ***varpij;
                   9254: 
                   9255:    strcpy(fileresprob,"PROB_"); 
1.356     brouard  9256:    strcat(fileresprob,fileresu);
1.222     brouard  9257:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   9258:      printf("Problem with resultfile: %s\n", fileresprob);
                   9259:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   9260:    }
                   9261:    strcpy(fileresprobcov,"PROBCOV_"); 
                   9262:    strcat(fileresprobcov,fileresu);
                   9263:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   9264:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   9265:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   9266:    }
                   9267:    strcpy(fileresprobcor,"PROBCOR_"); 
                   9268:    strcat(fileresprobcor,fileresu);
                   9269:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   9270:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   9271:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   9272:    }
                   9273:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   9274:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   9275:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   9276:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   9277:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   9278:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   9279:    pstamp(ficresprob);
                   9280:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   9281:    fprintf(ficresprob,"# Age");
                   9282:    pstamp(ficresprobcov);
                   9283:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   9284:    fprintf(ficresprobcov,"# Age");
                   9285:    pstamp(ficresprobcor);
                   9286:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   9287:    fprintf(ficresprobcor,"# Age");
1.126     brouard  9288: 
                   9289: 
1.222     brouard  9290:    for(i=1; i<=nlstate;i++)
                   9291:      for(j=1; j<=(nlstate+ndeath);j++){
                   9292:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   9293:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   9294:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   9295:      }  
                   9296:    /* fprintf(ficresprob,"\n");
                   9297:       fprintf(ficresprobcov,"\n");
                   9298:       fprintf(ficresprobcor,"\n");
                   9299:    */
                   9300:    xp=vector(1,npar);
                   9301:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   9302:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   9303:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   9304:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   9305:    first=1;
                   9306:    fprintf(ficgp,"\n# Routine varprob");
                   9307:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   9308:    fprintf(fichtm,"\n");
                   9309: 
1.288     brouard  9310:    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  9311:    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);
                   9312:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  9313: and drawn. It helps understanding how is the covariance between two incidences.\
                   9314:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  9315:    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  9316: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   9317: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   9318: standard deviations wide on each axis. <br>\
                   9319:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   9320:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   9321: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   9322: 
1.222     brouard  9323:    cov[1]=1;
                   9324:    /* tj=cptcoveff; */
1.225     brouard  9325:    tj = (int) pow(2,cptcoveff);
1.222     brouard  9326:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   9327:    j1=0;
1.332     brouard  9328: 
                   9329:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   9330:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.342     brouard  9331:      /* 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  9332:      if(tj != 1 && TKresult[nres]!= j1)
                   9333:        continue;
                   9334: 
                   9335:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   9336:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   9337:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  9338:      if  (cptcovn>0) {
1.334     brouard  9339:        fprintf(ficresprob, "\n#********** Variable ");
                   9340:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   9341:        fprintf(ficgp, "\n#********** Variable ");
                   9342:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   9343:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   9344: 
                   9345:        /* Including quantitative variables of the resultline to be done */
                   9346:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
1.343     brouard  9347:         /* printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model); */
1.338     brouard  9348:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   9349:         /* 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  9350:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   9351:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   9352:             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  */
                   9353:             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  */
                   9354:             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  */
                   9355:             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  */
                   9356:             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  */
                   9357:             fprintf(ficresprob,"fixed ");
                   9358:             fprintf(ficresprobcov,"fixed ");
                   9359:             fprintf(ficgp,"fixed ");
                   9360:             fprintf(fichtmcov,"fixed ");
                   9361:             fprintf(ficresprobcor,"fixed ");
                   9362:           }else{
                   9363:             fprintf(ficresprob,"varyi ");
                   9364:             fprintf(ficresprobcov,"varyi ");
                   9365:             fprintf(ficgp,"varyi ");
                   9366:             fprintf(fichtmcov,"varyi ");
                   9367:             fprintf(ficresprobcor,"varyi ");
                   9368:           }
                   9369:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   9370:           /* For each selected (single) quantitative value */
1.337     brouard  9371:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
1.334     brouard  9372:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   9373:             fprintf(ficresprob,"fixed ");
                   9374:             fprintf(ficresprobcov,"fixed ");
                   9375:             fprintf(ficgp,"fixed ");
                   9376:             fprintf(fichtmcov,"fixed ");
                   9377:             fprintf(ficresprobcor,"fixed ");
                   9378:           }else{
                   9379:             fprintf(ficresprob,"varyi ");
                   9380:             fprintf(ficresprobcov,"varyi ");
                   9381:             fprintf(ficgp,"varyi ");
                   9382:             fprintf(fichtmcov,"varyi ");
                   9383:             fprintf(ficresprobcor,"varyi ");
                   9384:           }
                   9385:         }else{
                   9386:           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 */
                   9387:           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 */
                   9388:           exit(1);
                   9389:         }
                   9390:        } /* End loop on variable of this resultline */
                   9391:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  9392:        fprintf(ficresprob, "**********\n#\n");
                   9393:        fprintf(ficresprobcov, "**********\n#\n");
                   9394:        fprintf(ficgp, "**********\n#\n");
                   9395:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   9396:        fprintf(ficresprobcor, "**********\n#");    
                   9397:        if(invalidvarcomb[j1]){
                   9398:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   9399:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   9400:         continue;
                   9401:        }
                   9402:      }
                   9403:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   9404:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   9405:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   9406:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  9407:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  9408:        cov[2]=age;
                   9409:        if(nagesqr==1)
                   9410:         cov[3]= age*age;
1.334     brouard  9411:        /* New code end of combination but for each resultline */
                   9412:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  9413:         if(Typevar[k1]==1 || Typevar[k1] ==3){ /* A product with age */
1.334     brouard  9414:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  9415:         }else{
1.334     brouard  9416:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  9417:         }
1.334     brouard  9418:        }/* End of loop on model equation */
                   9419: /* Old code */
                   9420:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   9421:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   9422:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   9423:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   9424:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   9425:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   9426:        /*                                                                  * 1  1 1 1 1 */
                   9427:        /*                                                                  * 2  2 1 1 1 */
                   9428:        /*                                                                  * 3  1 2 1 1 */
                   9429:        /*                                                                  *\/ */
                   9430:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   9431:        /* } */
                   9432:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   9433:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   9434:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   9435:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   9436:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   9437:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   9438:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   9439:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   9440:        /*         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]); */
                   9441:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   9442:        /*         /\* exit(1); *\/ */
                   9443:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   9444:        /*       } */
                   9445:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   9446:        /* } */
                   9447:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   9448:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   9449:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   9450:        /*           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]])]; */
                   9451:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   9452:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   9453:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   9454:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   9455:        /*         } */
                   9456:        /*       }else{ */
                   9457:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   9458:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   9459:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   9460:        /*         }else{ */
                   9461:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   9462:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   9463:        /*         } */
                   9464:        /*       } */
                   9465:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   9466:        /* } */                 
1.326     brouard  9467: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  9468:        for(theta=1; theta <=npar; theta++){
                   9469:         for(i=1; i<=npar; i++)
                   9470:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  9471:                                
1.222     brouard  9472:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  9473:                                
1.222     brouard  9474:         k=0;
                   9475:         for(i=1; i<= (nlstate); i++){
                   9476:           for(j=1; j<=(nlstate+ndeath);j++){
                   9477:             k=k+1;
                   9478:             gp[k]=pmmij[i][j];
                   9479:           }
                   9480:         }
1.220     brouard  9481:                                
1.222     brouard  9482:         for(i=1; i<=npar; i++)
                   9483:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  9484:                                
1.222     brouard  9485:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   9486:         k=0;
                   9487:         for(i=1; i<=(nlstate); i++){
                   9488:           for(j=1; j<=(nlstate+ndeath);j++){
                   9489:             k=k+1;
                   9490:             gm[k]=pmmij[i][j];
                   9491:           }
                   9492:         }
1.220     brouard  9493:                                
1.222     brouard  9494:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   9495:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   9496:        }
1.126     brouard  9497: 
1.222     brouard  9498:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   9499:         for(theta=1; theta <=npar; theta++)
                   9500:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  9501:                        
1.222     brouard  9502:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   9503:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  9504:                        
1.222     brouard  9505:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  9506:                        
1.222     brouard  9507:        k=0;
                   9508:        for(i=1; i<=(nlstate); i++){
                   9509:         for(j=1; j<=(nlstate+ndeath);j++){
                   9510:           k=k+1;
                   9511:           mu[k][(int) age]=pmmij[i][j];
                   9512:         }
                   9513:        }
                   9514:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   9515:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   9516:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  9517:                        
1.222     brouard  9518:        /*printf("\n%d ",(int)age);
                   9519:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   9520:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   9521:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   9522:         }*/
1.220     brouard  9523:                        
1.222     brouard  9524:        fprintf(ficresprob,"\n%d ",(int)age);
                   9525:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   9526:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  9527:                        
1.222     brouard  9528:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   9529:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   9530:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   9531:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   9532:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   9533:        }
                   9534:        i=0;
                   9535:        for (k=1; k<=(nlstate);k++){
                   9536:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   9537:           i++;
                   9538:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   9539:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   9540:           for (j=1; j<=i;j++){
                   9541:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   9542:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   9543:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   9544:           }
                   9545:         }
                   9546:        }/* end of loop for state */
                   9547:      } /* end of loop for age */
                   9548:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   9549:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   9550:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   9551:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   9552:     
                   9553:      /* Confidence intervalle of pij  */
                   9554:      /*
                   9555:        fprintf(ficgp,"\nunset parametric;unset label");
                   9556:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   9557:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   9558:        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);
                   9559:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   9560:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   9561:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   9562:      */
                   9563:                
                   9564:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   9565:      first1=1;first2=2;
                   9566:      for (k2=1; k2<=(nlstate);k2++){
                   9567:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   9568:         if(l2==k2) continue;
                   9569:         j=(k2-1)*(nlstate+ndeath)+l2;
                   9570:         for (k1=1; k1<=(nlstate);k1++){
                   9571:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   9572:             if(l1==k1) continue;
                   9573:             i=(k1-1)*(nlstate+ndeath)+l1;
                   9574:             if(i<=j) continue;
                   9575:             for (age=bage; age<=fage; age ++){ 
                   9576:               if ((int)age %5==0){
                   9577:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   9578:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   9579:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   9580:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   9581:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   9582:                 c12=cv12/sqrt(v1*v2);
                   9583:                 /* Computing eigen value of matrix of covariance */
                   9584:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   9585:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   9586:                 if ((lc2 <0) || (lc1 <0) ){
                   9587:                   if(first2==1){
                   9588:                     first1=0;
                   9589:                     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);
                   9590:                   }
                   9591:                   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);
                   9592:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   9593:                   /* lc2=fabs(lc2); */
                   9594:                 }
1.220     brouard  9595:                                                                
1.222     brouard  9596:                 /* Eigen vectors */
1.280     brouard  9597:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   9598:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   9599:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   9600:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   9601:                 }else
                   9602:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  9603:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   9604:                 v21=(lc1-v1)/cv12*v11;
                   9605:                 v12=-v21;
                   9606:                 v22=v11;
                   9607:                 tnalp=v21/v11;
                   9608:                 if(first1==1){
                   9609:                   first1=0;
                   9610:                   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);
                   9611:                 }
                   9612:                 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);
                   9613:                 /*printf(fignu*/
                   9614:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   9615:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   9616:                 if(first==1){
                   9617:                   first=0;
                   9618:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   9619:                   fprintf(ficgp,"\nset parametric;unset label");
                   9620:                   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);
                   9621:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  9622:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  9623:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  9624: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  9625:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   9626:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   9627:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   9628:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   9629:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   9630:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   9631:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   9632:                   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  9633:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   9634:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  9635:                 }else{
                   9636:                   first=0;
                   9637:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   9638:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   9639:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   9640:                   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  9641:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   9642:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  9643:                 }/* if first */
                   9644:               } /* age mod 5 */
                   9645:             } /* end loop age */
                   9646:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   9647:             first=1;
                   9648:           } /*l12 */
                   9649:         } /* k12 */
                   9650:        } /*l1 */
                   9651:      }/* k1 */
1.332     brouard  9652:    }  /* loop on combination of covariates j1 */
1.326     brouard  9653:    } /* loop on nres */
1.222     brouard  9654:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   9655:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   9656:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   9657:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   9658:    free_vector(xp,1,npar);
                   9659:    fclose(ficresprob);
                   9660:    fclose(ficresprobcov);
                   9661:    fclose(ficresprobcor);
                   9662:    fflush(ficgp);
                   9663:    fflush(fichtmcov);
                   9664:  }
1.126     brouard  9665: 
                   9666: 
                   9667: /******************* Printing html file ***********/
1.201     brouard  9668: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  9669:                  int lastpass, int stepm, int weightopt, char model[],\
                   9670:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  9671:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   9672:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   9673:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.359     brouard  9674:   int jj1, k1, cpt, nres;
1.319     brouard  9675:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  9676:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   9677:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   9678: </ul>");
1.319     brouard  9679: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   9680: /* </ul>", model); */
1.214     brouard  9681:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   9682:    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",
                   9683:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  9684:    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  9685:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   9686:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  9687:    fprintf(fichtm,"\
                   9688:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  9689:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  9690:    fprintf(fichtm,"\
1.217     brouard  9691:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   9692:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   9693:    fprintf(fichtm,"\
1.288     brouard  9694:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  9695:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  9696:    fprintf(fichtm,"\
1.288     brouard  9697:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  9698:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   9699:    fprintf(fichtm,"\
1.211     brouard  9700:  - (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  9701:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  9702:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  9703:    if(prevfcast==1){
                   9704:      fprintf(fichtm,"\
                   9705:  - Prevalence projections by age and states:                           \
1.201     brouard  9706:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  9707:    }
1.126     brouard  9708: 
                   9709: 
1.225     brouard  9710:    m=pow(2,cptcoveff);
1.222     brouard  9711:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  9712: 
1.317     brouard  9713:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  9714: 
                   9715:    jj1=0;
                   9716: 
                   9717:    fprintf(fichtm," \n<ul>");
1.337     brouard  9718:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9719:      /* k1=nres; */
1.338     brouard  9720:      k1=TKresult[nres];
                   9721:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
1.337     brouard  9722:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   9723:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   9724:    /*     continue; */
1.264     brouard  9725:      jj1++;
                   9726:      if (cptcovn > 0) {
                   9727:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
1.337     brouard  9728:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   9729:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  9730:        }
1.337     brouard  9731:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   9732:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   9733:        /* } */
                   9734:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9735:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   9736:        /* } */
1.264     brouard  9737:        fprintf(fichtm,"\">");
                   9738:        
                   9739:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   9740:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  9741:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9742:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  9743:        }
1.337     brouard  9744:        /* fprintf(fichtm,"************ Results for covariates"); */
                   9745:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   9746:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   9747:        /* } */
                   9748:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9749:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   9750:        /* } */
1.264     brouard  9751:        if(invalidvarcomb[k1]){
                   9752:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   9753:         continue;
                   9754:        }
                   9755:        fprintf(fichtm,"</a></li>");
                   9756:      } /* cptcovn >0 */
                   9757:    }
1.317     brouard  9758:    fprintf(fichtm," \n</ul>");
1.264     brouard  9759: 
1.222     brouard  9760:    jj1=0;
1.237     brouard  9761: 
1.337     brouard  9762:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9763:      /* k1=nres; */
1.338     brouard  9764:      k1=TKresult[nres];
                   9765:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9766:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   9767:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   9768:    /*     continue; */
1.220     brouard  9769: 
1.222     brouard  9770:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   9771:      jj1++;
                   9772:      if (cptcovn > 0) {
1.264     brouard  9773:        fprintf(fichtm,"\n<p><a name=\"rescov");
1.337     brouard  9774:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9775:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  9776:        }
1.337     brouard  9777:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9778:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   9779:        /* } */
1.264     brouard  9780:        fprintf(fichtm,"\"</a>");
                   9781:  
1.222     brouard  9782:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  9783:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9784:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   9785:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  9786:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   9787:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  9788:        }
1.230     brouard  9789:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.338     brouard  9790:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  9791:        if(invalidvarcomb[k1]){
                   9792:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   9793:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   9794:         continue;
                   9795:        }
                   9796:      }
                   9797:      /* aij, bij */
1.259     brouard  9798:      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  9799: <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  9800:      /* Pij */
1.241     brouard  9801:      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> \
                   9802: <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  9803:      /* Quasi-incidences */
                   9804:      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  9805:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  9806:  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  9807: 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> \
                   9808: <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  9809:      /* Survival functions (period) in state j */
                   9810:      for(cpt=1; cpt<=nlstate;cpt++){
1.359     brouard  9811:        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  9812:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   9813:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  9814:      }
                   9815:      /* State specific survival functions (period) */
                   9816:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  9817:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
1.359     brouard  9818:  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  9819:  <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);
                   9820:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   9821:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  9822:      }
1.288     brouard  9823:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  9824:      for(cpt=1; cpt<=nlstate;cpt++){
1.359     brouard  9825:        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  9826:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
1.329     brouard  9827:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  9828:      }
1.296     brouard  9829:      if(prevbcast==1){
1.288     brouard  9830:        /* Backward prevalence in each health state */
1.222     brouard  9831:        for(cpt=1; cpt<=nlstate;cpt++){
1.338     brouard  9832:         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);
                   9833:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
                   9834:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  9835:        }
1.217     brouard  9836:      }
1.222     brouard  9837:      if(prevfcast==1){
1.288     brouard  9838:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  9839:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  9840:         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);
                   9841:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   9842:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   9843:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  9844:        }
                   9845:      }
1.296     brouard  9846:      if(prevbcast==1){
1.268     brouard  9847:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   9848:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  9849:         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  9850:  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 \
                   9851:  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  9852: 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);
                   9853:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   9854:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  9855:        }
                   9856:      }
1.220     brouard  9857:         
1.222     brouard  9858:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  9859:        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);
                   9860:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   9861:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  9862:      }
                   9863:      /* } /\* end i1 *\/ */
1.337     brouard  9864:    }/* End k1=nres */
1.222     brouard  9865:    fprintf(fichtm,"</ul>");
1.126     brouard  9866: 
1.222     brouard  9867:    fprintf(fichtm,"\
1.126     brouard  9868: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  9869:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  9870:  - 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  9871: But because parameters are usually highly correlated (a higher incidence of disability \
                   9872: and a higher incidence of recovery can give very close observed transition) it might \
                   9873: be very useful to look not only at linear confidence intervals estimated from the \
                   9874: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   9875: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   9876: covariance matrix of the one-step probabilities. \
                   9877: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  9878: 
1.222     brouard  9879:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   9880:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   9881:    fprintf(fichtm,"\
1.126     brouard  9882:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  9883:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  9884: 
1.222     brouard  9885:    fprintf(fichtm,"\
1.126     brouard  9886:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  9887:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   9888:    fprintf(fichtm,"\
1.126     brouard  9889:  - 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): \
                   9890:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  9891:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  9892:    fprintf(fichtm,"\
1.126     brouard  9893:  - (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): \
                   9894:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  9895:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  9896:    fprintf(fichtm,"\
1.288     brouard  9897:  - 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  9898:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   9899:    fprintf(fichtm,"\
1.128     brouard  9900:  - 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  9901:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   9902:    fprintf(fichtm,"\
1.288     brouard  9903:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  9904:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  9905: 
                   9906: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   9907: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   9908: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   9909: /*     <br>",fileres,fileres,fileres,fileres); */
                   9910: /*  else  */
1.338     brouard  9911: /*    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  9912:    fflush(fichtm);
1.126     brouard  9913: 
1.225     brouard  9914:    m=pow(2,cptcoveff);
1.222     brouard  9915:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  9916: 
1.317     brouard  9917:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   9918: 
                   9919:   jj1=0;
                   9920: 
                   9921:    fprintf(fichtm," \n<ul>");
1.337     brouard  9922:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9923:      /* k1=nres; */
1.338     brouard  9924:      k1=TKresult[nres];
1.337     brouard  9925:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   9926:      /* if(m != 1 && TKresult[nres]!= k1) */
                   9927:      /*   continue; */
1.317     brouard  9928:      jj1++;
                   9929:      if (cptcovn > 0) {
                   9930:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
1.337     brouard  9931:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9932:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  9933:        }
                   9934:        fprintf(fichtm,"\">");
                   9935:        
                   9936:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   9937:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  9938:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9939:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  9940:        }
                   9941:        if(invalidvarcomb[k1]){
                   9942:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   9943:         continue;
                   9944:        }
                   9945:        fprintf(fichtm,"</a></li>");
                   9946:      } /* cptcovn >0 */
1.337     brouard  9947:    } /* End nres */
1.317     brouard  9948:    fprintf(fichtm," \n</ul>");
                   9949: 
1.222     brouard  9950:    jj1=0;
1.237     brouard  9951: 
1.241     brouard  9952:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9953:      /* k1=nres; */
1.338     brouard  9954:      k1=TKresult[nres];
                   9955:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9956:      /* for(k1=1; k1<=m;k1++){ */
                   9957:      /* if(m != 1 && TKresult[nres]!= k1) */
                   9958:      /*   continue; */
1.222     brouard  9959:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   9960:      jj1++;
1.126     brouard  9961:      if (cptcovn > 0) {
1.317     brouard  9962:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
1.337     brouard  9963:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9964:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  9965:        }
                   9966:        fprintf(fichtm,"\"</a>");
                   9967:        
1.126     brouard  9968:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  9969:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
                   9970:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   9971:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  9972:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  9973:        }
1.237     brouard  9974: 
1.338     brouard  9975:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  9976: 
1.222     brouard  9977:        if(invalidvarcomb[k1]){
                   9978:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   9979:         continue;
                   9980:        }
1.337     brouard  9981:      } /* If cptcovn >0 */
1.126     brouard  9982:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  9983:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  9984: 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);
                   9985:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   9986:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  9987:      }
                   9988:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.360     brouard  9989: health expectancies in each live state (1 to %d) with confidence intervals \
                   9990: on left y-scale as well as proportions of time spent in each live state \
                   9991: (with confidence intervals) on right y-scale 0 to 100%%.\
                   9992:  If popbased=1 the smooth (due to the model)                           \
1.128     brouard  9993: true period expectancies (those weighted with period prevalences are also\
                   9994:  drawn in addition to the population based expectancies computed using\
1.314     brouard  9995:  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);
                   9996:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   9997:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  9998:      /* } /\* end i1 *\/ */
1.241     brouard  9999:   }/* End nres */
1.222     brouard  10000:    fprintf(fichtm,"</ul>");
                   10001:    fflush(fichtm);
1.126     brouard  10002: }
                   10003: 
                   10004: /******************* Gnuplot file **************/
1.296     brouard  10005: 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  10006: 
1.354     brouard  10007:   char dirfileres[256],optfileres[256];
                   10008:   char gplotcondition[256], gplotlabel[256];
1.343     brouard  10009:   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.365     brouard  10010:   /* int lv=0, vlv=0, kl=0; */
                   10011:   int lv=0, kl=0;
                   10012:   double vlv=0;
1.130     brouard  10013:   int ng=0;
1.201     brouard  10014:   int vpopbased;
1.223     brouard  10015:   int ioffset; /* variable offset for columns */
1.270     brouard  10016:   int iyearc=1; /* variable column for year of projection  */
                   10017:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  10018:   int nres=0; /* Index of resultline */
1.266     brouard  10019:   int istart=1; /* For starting graphs in projections */
1.219     brouard  10020: 
1.126     brouard  10021: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   10022: /*     printf("Problem with file %s",optionfilegnuplot); */
                   10023: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   10024: /*   } */
                   10025: 
                   10026:   /*#ifdef windows */
                   10027:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  10028:   /*#endif */
1.225     brouard  10029:   m=pow(2,cptcoveff);
1.126     brouard  10030: 
1.274     brouard  10031:   /* diagram of the model */
                   10032:   fprintf(ficgp,"\n#Diagram of the model \n");
                   10033:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   10034:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   10035:   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);
                   10036: 
1.343     brouard  10037:   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  10038:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   10039:   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);
                   10040:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   10041:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   10042:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   10043:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   10044: 
1.202     brouard  10045:   /* Contribution to likelihood */
                   10046:   /* Plot the probability implied in the likelihood */
1.223     brouard  10047:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   10048:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   10049:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   10050:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  10051: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  10052:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   10053: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  10054:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   10055:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   10056:   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));
                   10057:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   10058:   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));
                   10059:   for (i=1; i<= nlstate ; i ++) {
                   10060:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   10061:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   10062:     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);
                   10063:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   10064:       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);
                   10065:     }
                   10066:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   10067:   }
                   10068:   /* 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 */               
                   10069:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   10070:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   10071:   fprintf(ficgp,"\nset out;unset log\n");
                   10072:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  10073: 
1.343     brouard  10074:   /* Plot the probability implied in the likelihood by covariate value */
                   10075:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
                   10076:   /* if(debugILK==1){ */
                   10077:   for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.347     brouard  10078:     kvar=Tvar[TvarFind[kf]]; /* variable name */
                   10079:     /* k=18+Tvar[TvarFind[kf]];/\*offset because there are 18 columns in the ILK_ file but could be placed else where *\/ */
1.350     brouard  10080:     /* k=18+kf;/\*offset because there are 18 columns in the ILK_ file *\/ */
1.356     brouard  10081:     /* k=19+kf;/\*offset because there are 19 columns in the ILK_ file *\/ */
1.355     brouard  10082:     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  10083:     for (i=1; i<= nlstate ; i ++) {
                   10084:       fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   10085:       fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
1.348     brouard  10086:       if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   10087:        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);
                   10088:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   10089:          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);
                   10090:        }
                   10091:       }else{
                   10092:        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);
                   10093:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   10094:          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);
                   10095:        }
1.343     brouard  10096:       }
                   10097:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   10098:     }
                   10099:   } /* End of each covariate dummy */
                   10100:   for(ncovv=1, iposold=0, kk=0; ncovv <= ncovvt ; ncovv++){
                   10101:     /* Other example        V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   10102:      *     kmodel       =     1   2     3     4         5        6        7       8        9
                   10103:      *  varying                   1     2                                 3       4        5
                   10104:      *  ncovv                     1     2                                3 4     5 6      7 8
                   10105:      * TvarVV[ncovv]             V3     5                                1 3     3 5      1 5
                   10106:      * TvarVVind[ncovv]=kmodel    2     3                                7 7     8 8      9 9
                   10107:      * TvarFind[kmodel]       1   0     0     0         0        0        0       0        0
                   10108:      * kdata     ncovcol=[V1 V2] nqv=0 ntv=[V3 V4] nqtv=V5
                   10109:      * Dummy[kmodel]          0   0     1     2         2        3        1       1        1
                   10110:      */
                   10111:     ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   10112:     kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   10113:     /* 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]); */
                   10114:     if(ipos!=iposold){ /* Not a product or first of a product */
                   10115:       /* printf(" %d",ipos); */
                   10116:       /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   10117:       /* printf(" DebugILK ficgp suite ipos=%d != iposold=%d\n", ipos, iposold); */
                   10118:       kk++; /* Position of the ncovv column in ILK_ */
                   10119:       k=18+ncovf+kk; /*offset because there are 18 columns in the ILK_ file plus ncovf fixed covariate */
                   10120:       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)  */
                   10121:        for (i=1; i<= nlstate ; i ++) {
                   10122:          fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   10123:          fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   10124: 
1.348     brouard  10125:            /* printf("Before DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
1.343     brouard  10126:          if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   10127:            /* printf("DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
                   10128:            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);
                   10129:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   10130:              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);
                   10131:            }
                   10132:          }else{
                   10133:            /* printf("DebugILK gnuplotversion=%g <5.2\n",gnuplotversion); */
                   10134:            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);
                   10135:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   10136:              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);
                   10137:            }
                   10138:          }
                   10139:          fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   10140:        }
                   10141:       }/* End if dummy varying */
                   10142:     }else{ /*Product */
                   10143:       /* printf("*"); */
                   10144:       /* fprintf(ficresilk,"*"); */
                   10145:     }
                   10146:     iposold=ipos;
                   10147:   } /* For each time varying covariate */
                   10148:   /* } /\* debugILK==1 *\/ */
                   10149:   /* 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 */               
                   10150:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   10151:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   10152:   fprintf(ficgp,"\nset out;unset log\n");
                   10153:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   10154: 
                   10155: 
                   10156:   
1.126     brouard  10157:   strcpy(dirfileres,optionfilefiname);
                   10158:   strcpy(optfileres,"vpl");
1.223     brouard  10159:   /* 1eme*/
1.238     brouard  10160:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
1.337     brouard  10161:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
1.236     brouard  10162:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10163:        k1=TKresult[nres];
1.338     brouard  10164:        if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.238     brouard  10165:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.337     brouard  10166:        /* if(m != 1 && TKresult[nres]!= k1) */
                   10167:        /*   continue; */
1.238     brouard  10168:        /* We are interested in selected combination by the resultline */
1.246     brouard  10169:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  10170:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  10171:        strcpy(gplotlabel,"(");
1.337     brouard  10172:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10173:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10174:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10175: 
                   10176:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
                   10177:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
                   10178:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10179:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10180:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10181:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10182:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
                   10183:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
                   10184:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
                   10185:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10186:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10187:        /* } */
                   10188:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10189:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
                   10190:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10191:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.264     brouard  10192:        }
                   10193:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  10194:        /* printf("\n#\n"); */
1.238     brouard  10195:        fprintf(ficgp,"\n#\n");
                   10196:        if(invalidvarcomb[k1]){
1.260     brouard  10197:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  10198:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10199:          continue;
                   10200:        }
1.235     brouard  10201:       
1.241     brouard  10202:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   10203:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  10204:        /* 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  10205:        fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.367   ! brouard  10206:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \nset ter svg size 640, 480\nplot [%.f:%.f] [0:1] \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),nres-1,nres-1,nres);
1.260     brouard  10207:        /* 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); */
                   10208:       /* k1-1 error should be nres-1*/
1.238     brouard  10209:        for (i=1; i<= nlstate ; i ++) {
                   10210:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10211:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   10212:        }
1.288     brouard  10213:        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  10214:        for (i=1; i<= nlstate ; i ++) {
                   10215:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10216:          else fprintf(ficgp," %%*lf (%%*lf)");
                   10217:        } 
1.260     brouard  10218:        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  10219:        for (i=1; i<= nlstate ; i ++) {
                   10220:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10221:          else fprintf(ficgp," %%*lf (%%*lf)");
                   10222:        }  
1.265     brouard  10223:        /* 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)); */
                   10224:        
                   10225:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   10226:         if(cptcoveff ==0){
1.271     brouard  10227:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  10228:        }else{
                   10229:          kl=0;
                   10230:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  10231:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   10232:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  10233:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   10234:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   10235:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   10236:            vlv= nbcode[Tvaraff[k]][lv];
                   10237:            kl++;
                   10238:            /* 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 *\/ */
                   10239:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   10240:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   10241:            /* ''  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*/
                   10242:            if(k==cptcoveff){
                   10243:              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], \
                   10244:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   10245:            }else{
                   10246:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   10247:              kl++;
                   10248:            }
                   10249:          } /* end covariate */
                   10250:        } /* end if no covariate */
                   10251: 
1.296     brouard  10252:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  10253:          /* 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  10254:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  10255:          if(cptcoveff ==0){
1.245     brouard  10256:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  10257:          }else{
                   10258:            kl=0;
                   10259:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  10260:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   10261:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  10262:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   10263:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   10264:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  10265:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   10266:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  10267:              kl++;
1.238     brouard  10268:              /* 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 *\/ */
                   10269:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   10270:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   10271:              /* ''  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*/
                   10272:              if(k==cptcoveff){
1.245     brouard  10273:                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  10274:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  10275:              }else{
1.332     brouard  10276:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  10277:                kl++;
                   10278:              }
                   10279:            } /* end covariate */
                   10280:          } /* end if no covariate */
1.296     brouard  10281:          if(prevbcast == 1){
1.268     brouard  10282:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   10283:            /* k1-1 error should be nres-1*/
                   10284:            for (i=1; i<= nlstate ; i ++) {
                   10285:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10286:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   10287:            }
1.271     brouard  10288:            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  10289:            for (i=1; i<= nlstate ; i ++) {
                   10290:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10291:              else fprintf(ficgp," %%*lf (%%*lf)");
                   10292:            } 
1.276     brouard  10293:            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  10294:            for (i=1; i<= nlstate ; i ++) {
                   10295:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10296:              else fprintf(ficgp," %%*lf (%%*lf)");
                   10297:            } 
1.274     brouard  10298:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  10299:          } /* end if backprojcast */
1.296     brouard  10300:        } /* end if prevbcast */
1.276     brouard  10301:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   10302:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  10303:       } /* nres */
1.337     brouard  10304:     /* } /\* k1 *\/ */
1.201     brouard  10305:   } /* cpt */
1.235     brouard  10306: 
                   10307:   
1.126     brouard  10308:   /*2 eme*/
1.337     brouard  10309:   /* for (k1=1; k1<= m ; k1 ++){   */
1.238     brouard  10310:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10311:       k1=TKresult[nres];
1.338     brouard  10312:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10313:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10314:       /*       continue; */
1.238     brouard  10315:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  10316:       strcpy(gplotlabel,"(");
1.337     brouard  10317:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10318:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10319:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10320:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10321:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10322:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10323:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10324:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10325:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10326:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10327:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10328:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10329:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10330:       /* } */
                   10331:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
                   10332:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10333:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10334:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10335:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  10336:       }
1.264     brouard  10337:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  10338:       fprintf(ficgp,"\n#\n");
1.223     brouard  10339:       if(invalidvarcomb[k1]){
                   10340:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10341:        continue;
                   10342:       }
1.219     brouard  10343:                        
1.241     brouard  10344:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  10345:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  10346:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   10347:        if(vpopbased==0){
1.360     brouard  10348:          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  10349:        }else
1.238     brouard  10350:          fprintf(ficgp,"\nreplot ");
1.360     brouard  10351:        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  10352:          k=2*i;
1.360     brouard  10353:          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 */
                   10354:          for (j=1; j<= nlstate+1 ; j ++) { /* e.. e.1 e.2 again j-1 is the state of end, wlim_i eij*/
                   10355:            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 */
                   10356:            else fprintf(ficgp," %%*lf (%%*lf)");  /* skipping that field with a star */
1.238     brouard  10357:          }   
                   10358:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
1.360     brouard  10359:          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  10360:          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  10361:          for (j=1; j<= nlstate+1 ; j ++) {
                   10362:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   10363:            else fprintf(ficgp," %%*lf (%%*lf)");
                   10364:          }   
                   10365:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  10366:          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  10367:          for (j=1; j<= nlstate+1 ; j ++) {
                   10368:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   10369:            else fprintf(ficgp," %%*lf (%%*lf)");
                   10370:          }   
1.360     brouard  10371:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0,\\\n"); /* ,\\\n added for th percentage graphs */
1.238     brouard  10372:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   10373:        } /* state */
1.360     brouard  10374:        /* again for the percentag spent in state i-1=1 to i-1=nlstate */
                   10375:        for (i=2; i<= nlstate+1 ; i ++) { /* For state i-1=0 is LE, while i-1=1 to nlstate are origin state */
                   10376:          k=2*i;
                   10377:          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 */
                   10378:          for (j=1; j<= nlstate ; j ++)
                   10379:            fprintf(ficgp," %%*lf (%%*lf)"); /* Skipping TLE and LE to read %LE only */
                   10380:          for (j=1; j<= nlstate+1 ; j ++) { /* e.. e.1 e.2 again j-1 is the state of end, wlim_i eij*/
                   10381:            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 */
                   10382:            else fprintf(ficgp," %%*lf (%%*lf)");  /* skipping that field with a star */
                   10383:          }   
                   10384:          if (i== 1) fprintf(ficgp,"\" t\"%%TLE\" w l lt %d axis x1y2, \\\n",i); /* Not used */
                   10385:          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  */
                   10386:          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);
                   10387:          for (j=1; j<= nlstate ; j ++)
                   10388:            fprintf(ficgp," %%*lf (%%*lf)"); /* Skipping TLE and LE to read %LE only */
                   10389:          for (j=1; j<= nlstate+1 ; j ++) {
                   10390:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   10391:            else fprintf(ficgp," %%*lf (%%*lf)");
                   10392:          }   
                   10393:          fprintf(ficgp,"\" t\"\" w l lt 0 axis x1y2,");
                   10394:          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);
                   10395:          for (j=1; j<= nlstate ; j ++)
                   10396:            fprintf(ficgp," %%*lf (%%*lf)"); /* Skipping TLE and LE to read %LE only */
                   10397:          for (j=1; j<= nlstate+1 ; j ++) {
                   10398:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   10399:            else fprintf(ficgp," %%*lf (%%*lf)");
                   10400:          }   
                   10401:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0 axis x1y2");
                   10402:          else fprintf(ficgp,"\" t\"\" w l lt 0 axis x1y2,\\\n");
                   10403:        } /* state for percent */
1.238     brouard  10404:       } /* vpopbased */
1.264     brouard  10405:       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  10406:     } /* end nres */
1.337     brouard  10407:   /* } /\* k1 end 2 eme*\/ */
1.238     brouard  10408:        
                   10409:        
                   10410:   /*3eme*/
1.337     brouard  10411:   /* for (k1=1; k1<= m ; k1 ++){ */
1.238     brouard  10412:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10413:       k1=TKresult[nres];
1.338     brouard  10414:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10415:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10416:       /*       continue; */
1.238     brouard  10417: 
1.332     brouard  10418:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  10419:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  10420:        strcpy(gplotlabel,"(");
1.337     brouard  10421:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10422:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10423:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10424:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10425:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10426:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   10427:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10428:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10429:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10430:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10431:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10432:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10433:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10434:        /* } */
                   10435:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10436:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   10437:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   10438:        }
1.264     brouard  10439:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  10440:        fprintf(ficgp,"\n#\n");
                   10441:        if(invalidvarcomb[k1]){
                   10442:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10443:          continue;
                   10444:        }
                   10445:                        
                   10446:        /*       k=2+nlstate*(2*cpt-2); */
                   10447:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  10448:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  10449:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  10450:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  10451: 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  10452:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   10453:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   10454:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   10455:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   10456:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   10457:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  10458:                                
1.238     brouard  10459:        */
                   10460:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  10461:          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  10462:          /*    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  10463:                                
1.238     brouard  10464:        } 
1.261     brouard  10465:        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  10466:       }
1.264     brouard  10467:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  10468:     } /* end nres */
1.337     brouard  10469:   /* } /\* end kl 3eme *\/ */
1.126     brouard  10470:   
1.223     brouard  10471:   /* 4eme */
1.201     brouard  10472:   /* Survival functions (period) from state i in state j by initial state i */
1.337     brouard  10473:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
1.238     brouard  10474:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10475:       k1=TKresult[nres];
1.338     brouard  10476:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10477:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10478:       /*       continue; */
1.238     brouard  10479:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  10480:        strcpy(gplotlabel,"(");
1.337     brouard  10481:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
                   10482:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10483:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10484:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10485:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10486:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10487:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10488:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10489:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10490:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10491:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10492:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10493:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10494:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10495:        /* } */
                   10496:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10497:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10498:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  10499:        }       
1.264     brouard  10500:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  10501:        fprintf(ficgp,"\n#\n");
                   10502:        if(invalidvarcomb[k1]){
                   10503:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10504:          continue;
1.223     brouard  10505:        }
1.238     brouard  10506:       
1.241     brouard  10507:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  10508:        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  10509:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   10510: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   10511:        k=3;
                   10512:        for (i=1; i<= nlstate ; i ++){
                   10513:          if(i==1){
                   10514:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   10515:          }else{
                   10516:            fprintf(ficgp,", '' ");
                   10517:          }
                   10518:          l=(nlstate+ndeath)*(i-1)+1;
                   10519:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   10520:          for (j=2; j<= nlstate+ndeath ; j ++)
                   10521:            fprintf(ficgp,"+$%d",k+l+j-1);
                   10522:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   10523:        } /* nlstate */
1.264     brouard  10524:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  10525:       } /* end cpt state*/ 
                   10526:     } /* end nres */
1.337     brouard  10527:   /* } /\* end covariate k1 *\/   */
1.238     brouard  10528: 
1.220     brouard  10529: /* 5eme */
1.201     brouard  10530:   /* Survival functions (period) from state i in state j by final state j */
1.337     brouard  10531:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
1.238     brouard  10532:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10533:       k1=TKresult[nres];
1.338     brouard  10534:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10535:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10536:       /*       continue; */
1.238     brouard  10537:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  10538:        strcpy(gplotlabel,"(");
1.238     brouard  10539:        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  10540:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10541:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10542:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10543:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10544:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10545:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10546:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10547:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10548:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10549:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10550:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10551:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10552:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10553:        /* } */
                   10554:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10555:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10556:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  10557:        }       
1.264     brouard  10558:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  10559:        fprintf(ficgp,"\n#\n");
                   10560:        if(invalidvarcomb[k1]){
                   10561:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10562:          continue;
                   10563:        }
1.227     brouard  10564:       
1.241     brouard  10565:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  10566:        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  10567:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   10568: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   10569:        k=3;
                   10570:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   10571:          if(j==1)
                   10572:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   10573:          else
                   10574:            fprintf(ficgp,", '' ");
                   10575:          l=(nlstate+ndeath)*(cpt-1) +j;
                   10576:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   10577:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   10578:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   10579:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   10580:        } /* nlstate */
                   10581:        fprintf(ficgp,", '' ");
                   10582:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   10583:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   10584:          l=(nlstate+ndeath)*(cpt-1) +j;
                   10585:          if(j < nlstate)
                   10586:            fprintf(ficgp,"$%d +",k+l);
                   10587:          else
                   10588:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   10589:        }
1.264     brouard  10590:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  10591:       } /* end cpt state*/ 
1.337     brouard  10592:     /* } /\* end covariate *\/   */
1.238     brouard  10593:   } /* end nres */
1.227     brouard  10594:   
1.220     brouard  10595: /* 6eme */
1.202     brouard  10596:   /* CV preval stable (period) for each covariate */
1.337     brouard  10597:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  10598:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10599:      k1=TKresult[nres];
1.338     brouard  10600:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10601:      /* if(m != 1 && TKresult[nres]!= k1) */
                   10602:      /*  continue; */
1.255     brouard  10603:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  10604:       strcpy(gplotlabel,"(");      
1.288     brouard  10605:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  10606:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10607:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10608:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10609:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10610:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10611:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10612:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10613:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10614:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10615:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10616:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10617:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10618:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10619:       /* } */
                   10620:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10621:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10622:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  10623:       }        
1.264     brouard  10624:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  10625:       fprintf(ficgp,"\n#\n");
1.223     brouard  10626:       if(invalidvarcomb[k1]){
1.227     brouard  10627:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10628:        continue;
1.223     brouard  10629:       }
1.227     brouard  10630:       
1.241     brouard  10631:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  10632:       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  10633:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  10634: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  10635:       k=3; /* Offset */
1.255     brouard  10636:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  10637:        if(i==1)
                   10638:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   10639:        else
                   10640:          fprintf(ficgp,", '' ");
1.255     brouard  10641:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  10642:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   10643:        for (j=2; j<= nlstate ; j ++)
                   10644:          fprintf(ficgp,"+$%d",k+l+j-1);
                   10645:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  10646:       } /* nlstate */
1.264     brouard  10647:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  10648:     } /* end cpt state*/ 
                   10649:   } /* end covariate */  
1.227     brouard  10650:   
                   10651:   
1.220     brouard  10652: /* 7eme */
1.296     brouard  10653:   if(prevbcast == 1){
1.288     brouard  10654:     /* CV backward prevalence  for each covariate */
1.337     brouard  10655:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  10656:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10657:       k1=TKresult[nres];
1.338     brouard  10658:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10659:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10660:       /*       continue; */
1.268     brouard  10661:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  10662:        strcpy(gplotlabel,"(");      
1.288     brouard  10663:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  10664:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10665:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10666:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10667:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10668:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10669:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10670:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10671:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10672:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10673:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10674:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10675:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10676:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10677:        /* } */
                   10678:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10679:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10680:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  10681:        }       
1.264     brouard  10682:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  10683:        fprintf(ficgp,"\n#\n");
                   10684:        if(invalidvarcomb[k1]){
                   10685:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10686:          continue;
                   10687:        }
                   10688:        
1.241     brouard  10689:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  10690:        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  10691:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  10692: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  10693:        k=3; /* Offset */
1.268     brouard  10694:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  10695:          if(i==1)
                   10696:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   10697:          else
                   10698:            fprintf(ficgp,", '' ");
                   10699:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  10700:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  10701:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   10702:          /* 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  10703:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  10704:          /* for (j=2; j<= nlstate ; j ++) */
                   10705:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   10706:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  10707:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  10708:        } /* nlstate */
1.264     brouard  10709:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  10710:       } /* end cpt state*/ 
                   10711:     } /* end covariate */  
1.296     brouard  10712:   } /* End if prevbcast */
1.218     brouard  10713:   
1.223     brouard  10714:   /* 8eme */
1.218     brouard  10715:   if(prevfcast==1){
1.288     brouard  10716:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  10717:     
1.337     brouard  10718:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  10719:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10720:       k1=TKresult[nres];
1.338     brouard  10721:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10722:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10723:       /*       continue; */
1.211     brouard  10724:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  10725:        strcpy(gplotlabel,"(");      
1.288     brouard  10726:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  10727:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10728:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10729:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10730:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   10731:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   10732:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10733:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10734:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10735:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10736:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10737:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10738:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10739:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10740:        /* } */
                   10741:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10742:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10743:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  10744:        }       
1.264     brouard  10745:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  10746:        fprintf(ficgp,"\n#\n");
                   10747:        if(invalidvarcomb[k1]){
                   10748:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10749:          continue;
                   10750:        }
                   10751:        
                   10752:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  10753:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  10754:        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  10755:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  10756: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  10757: 
                   10758:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   10759:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   10760:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   10761:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  10762:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10763:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   10764:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10765:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  10766:          if(i==istart){
1.227     brouard  10767:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   10768:          }else{
                   10769:            fprintf(ficgp,",\\\n '' ");
                   10770:          }
1.367   ! brouard  10771:          /* if(cptcoveff ==0){ /\* No covariate *\/ */
        !          10772:          if(cptcovs ==0){ /* No covariate */
1.227     brouard  10773:            ioffset=2; /* Age is in 2 */
                   10774:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   10775:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   10776:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   10777:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
1.367   ! brouard  10778:            /*# V1  = 1 yearproj age age*p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
        !          10779:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
1.227     brouard  10780:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  10781:            if(i==nlstate+1){
1.270     brouard  10782:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  10783:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   10784:              fprintf(ficgp,",\\\n '' ");
                   10785:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  10786:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  10787:                     offyear,                           \
1.268     brouard  10788:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  10789:            }else
1.227     brouard  10790:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   10791:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   10792:          }else{ /* more than 2 covariates */
1.367   ! brouard  10793:            /* ioffset=2*cptcoveff+2; */ /* Age is in 4 or 6 or etc.*/
        !          10794:            ioffset=2*cptcovs+2; /* Age is in 4 or 6 or etc.*/
1.270     brouard  10795:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10796:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
1.367   ! brouard  10797:            /* # Forecasting at date 3/1/2003  */
        !          10798:             /* V1=0 V2=1 V3=0 V6=2.47 yearproj age */      
        !          10799:             /* # 2 3 4 5 6 7  8    9   10   11    12     13    14   15     16    17    18    19   20    21    22     23    24   25    26 */
        !          10800:             /* #                             p11  p21    p31   wp.1 p12    p22   p32   wp.2  p13   p23  p33  wp.3    p14   p24   p34  wp.4 */
        !          10801:             /* 1 0 2 1 3 0 6 2.47 2003 100  1.000 0.000 0.000 0.297 0.000 1.000 0.000 0.207 0.000 0.000 1.000 0.497 0.000 0.000 0.000 0.000 */
1.270     brouard  10802:            iyearc=ioffset-1;
                   10803:            iagec=ioffset;
1.227     brouard  10804:            fprintf(ficgp," u %d:(",ioffset); 
                   10805:            kl=0;
                   10806:            strcpy(gplotcondition,"(");
1.351     brouard  10807:            /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
1.332     brouard  10808:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
1.351     brouard  10809:            for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10810:              /* lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10811:              lv=Tvresult[nres][k];
                   10812:              vlv=TinvDoQresult[nres][Tvresult[nres][k]];
1.227     brouard  10813:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   10814:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   10815:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  10816:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
1.351     brouard  10817:              /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
1.227     brouard  10818:              kl++;
1.364     brouard  10819:              /* Problem with quantitative variables TinvDoQresult[nres] */
1.351     brouard  10820:              /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
1.364     brouard  10821:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,lv, kl+1, vlv );/* Solved but quantitative must be shifted */
1.227     brouard  10822:              kl++;
1.351     brouard  10823:              if(k <cptcovs && cptcovs>1)
1.227     brouard  10824:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   10825:            }
                   10826:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   10827:            /* 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 *\/ */
                   10828:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   10829:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   10830:            /* ''  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*/
                   10831:            if(i==nlstate+1){
1.270     brouard  10832:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   10833:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  10834:              fprintf(ficgp,",\\\n '' ");
1.364     brouard  10835:              fprintf(ficgp," u %d:(",iagec); /* Below iyearc should be increades if quantitative variable in the reult line */
                   10836:              /* $7==6 && $8==2.47 ) && (($9-$10) == 1953 ) ? $12/(1.-$24) : 1/0):7 with labels center not */
                   10837:              /* but was  && $7==6 && $8==2 ) && (($7-$8) == 1953 ) ? $12/(1.-$24) : 1/0):7 with labels center not */
1.270     brouard  10838:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   10839:                      iyearc, iagec, offyear,                           \
                   10840:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  10841: /*  '' 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  10842:            }else{
                   10843:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   10844:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   10845:            }
                   10846:          } /* end if covariate */
                   10847:        } /* nlstate */
1.264     brouard  10848:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  10849:       } /* end cpt state*/
                   10850:     } /* end covariate */
                   10851:   } /* End if prevfcast */
1.227     brouard  10852:   
1.296     brouard  10853:   if(prevbcast==1){
1.268     brouard  10854:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   10855:     
1.337     brouard  10856:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.268     brouard  10857:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10858:      k1=TKresult[nres];
1.338     brouard  10859:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10860:        /* if(m != 1 && TKresult[nres]!= k1) */
                   10861:        /*      continue; */
1.268     brouard  10862:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   10863:        strcpy(gplotlabel,"(");      
                   10864:        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  10865:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10866:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10867:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10868:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   10869:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   10870:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   10871:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10872:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10873:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10874:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10875:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10876:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10877:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10878:        /* } */
                   10879:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10880:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10881:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.268     brouard  10882:        }       
                   10883:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   10884:        fprintf(ficgp,"\n#\n");
                   10885:        if(invalidvarcomb[k1]){
                   10886:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10887:          continue;
                   10888:        }
                   10889:        
                   10890:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   10891:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   10892:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   10893:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   10894: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   10895: 
                   10896:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   10897:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   10898:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   10899:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   10900:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10901:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   10902:          /*# 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:          if(i==istart){
                   10905:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   10906:          }else{
                   10907:            fprintf(ficgp,",\\\n '' ");
                   10908:          }
1.351     brouard  10909:          /* if(cptcoveff ==0){ /\* No covariate *\/ */
                   10910:          if(cptcovs ==0){ /* No covariate */
1.268     brouard  10911:            ioffset=2; /* Age is in 2 */
                   10912:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   10913:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   10914:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   10915:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   10916:            fprintf(ficgp," u %d:(", ioffset); 
                   10917:            if(i==nlstate+1){
1.367   ! brouard  10918:              fprintf(ficgp," $%d):1 t 'bw%d' with line lc variable ",  \
        !          10919:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),cpt );
        !          10920:              /* fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ",      \ */
        !          10921:              /*              ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt ); */
1.268     brouard  10922:              fprintf(ficgp,",\\\n '' ");
                   10923:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  10924:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  10925:                     offbyear,                          \
                   10926:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
1.367   ! brouard  10927:            }else  /* not sure divided by 1- to be checked */
        !          10928:              fprintf(ficgp," $%d) t 'b%d%d' with line ",       \
        !          10929:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),cpt,i );
        !          10930:              /* fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",   \ */
        !          10931:              /*              ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i ); */
1.268     brouard  10932:          }else{ /* more than 2 covariates */
1.367   ! brouard  10933:            /* ioffset=2*cptcoveff+2; /\* Age is in 4 or 6 or etc.*\/ */
        !          10934:            ioffset=2*cptcovs+2; /* Age is in 4 or 6 or etc.*/
1.270     brouard  10935:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10936:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
1.367   ! brouard  10937: /* #****** hbijx=probability over h years, hb.jx is weighted by observed prev  */
        !          10938: /* # V1=0  V2=1  V3=0  V6=2.47 */
        !          10939: /*              yearbproj age b11     b21    b31   b.1   b12  b22  b32    b.2   b13   b23   b33   b.3   b14   b24   b34    b.4 */
        !          10940: /* # Back Forecasting at date 3/1/2003  */
        !          10941: /* 1 2 3 4 5 6 7   8    9  10  11     12     13    14    15   16    17    18    19    20    21     22    23   24    25    26   */          
        !          10942: /* 1 0 2 1 3 0 6 2.47 2003 50  1.000 0.000 0.000 0.714 0.000 1.000 0.000 0.286 0.000 0.000 1.000 0.000 0.000 0.000 0.000 0.000 */
1.270     brouard  10943:            iyearc=ioffset-1;
                   10944:            iagec=ioffset;
1.268     brouard  10945:            fprintf(ficgp," u %d:(",ioffset); 
                   10946:            kl=0;
                   10947:            strcpy(gplotcondition,"(");
1.337     brouard  10948:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
1.367   ! brouard  10949:              /* if(Dummy[modelresult[nres][k]]==0){  /\* To be verified *\/ */
1.337     brouard  10950:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
                   10951:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   10952:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   10953:                lv=Tvresult[nres][k];
                   10954:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
                   10955:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   10956:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   10957:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   10958:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   10959:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10960:                kl++;
                   10961:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   10962:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
                   10963:                kl++;
1.338     brouard  10964:                if(k <cptcovs && cptcovs>1)
1.337     brouard  10965:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
1.367   ! brouard  10966:                /* } */ /* end dummy */
1.268     brouard  10967:            }
                   10968:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   10969:            /* 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 *\/ */
                   10970:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   10971:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   10972:            /* ''  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*/
                   10973:            if(i==nlstate+1){
1.270     brouard  10974:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   10975:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  10976:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  10977:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  10978:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  10979:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   10980:                      iyearc,iagec,offbyear,                            \
                   10981:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  10982: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   10983:            }else{
                   10984:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   10985:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   10986:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   10987:            }
                   10988:          } /* end if covariate */
                   10989:        } /* nlstate */
                   10990:        fprintf(ficgp,"\nset out; unset label;\n");
                   10991:       } /* end cpt state*/
                   10992:     } /* end covariate */
1.296     brouard  10993:   } /* End if prevbcast */
1.268     brouard  10994:   
1.227     brouard  10995:   
1.238     brouard  10996:   /* 9eme writing MLE parameters */
                   10997:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  10998:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  10999:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  11000:     for(k=1; k <=(nlstate+ndeath); k++){
                   11001:       if (k != i) {
1.227     brouard  11002:        fprintf(ficgp,"#   current state %d\n",k);
                   11003:        for(j=1; j <=ncovmodel; j++){
                   11004:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   11005:          jk++; 
                   11006:        }
                   11007:        fprintf(ficgp,"\n");
1.126     brouard  11008:       }
                   11009:     }
1.223     brouard  11010:   }
1.187     brouard  11011:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  11012:   
1.145     brouard  11013:   /*goto avoid;*/
1.238     brouard  11014:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   11015:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  11016:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   11017:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   11018:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   11019:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   11020:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   11021:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   11022:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   11023:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   11024:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   11025:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   11026:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   11027:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   11028:   fprintf(ficgp,"#\n");
1.223     brouard  11029:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  11030:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.338     brouard  11031:     fprintf(ficgp,"#model=1+age+%s \n",model);
1.238     brouard  11032:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.351     brouard  11033:     /* fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/\* to be checked *\/ */
                   11034:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcovs,m);/* to be checked */
1.337     brouard  11035:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
1.237     brouard  11036:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  11037:      /* k1=nres; */
1.338     brouard  11038:       k1=TKresult[nres];
                   11039:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  11040:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
1.264     brouard  11041:       strcpy(gplotlabel,"(");
1.276     brouard  11042:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.337     brouard  11043:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   11044:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
                   11045:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
                   11046:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   11047:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   11048:       }
                   11049:       /* if(m != 1 && TKresult[nres]!= k1) */
                   11050:       /*       continue; */
                   11051:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
                   11052:       /* strcpy(gplotlabel,"("); */
                   11053:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
                   11054:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   11055:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   11056:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   11057:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   11058:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   11059:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   11060:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   11061:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   11062:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   11063:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   11064:       /* } */
                   11065:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11066:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   11067:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   11068:       /* }      */
1.264     brouard  11069:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  11070:       fprintf(ficgp,"\n#\n");
1.264     brouard  11071:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  11072:       fprintf(ficgp,"\nset key outside ");
                   11073:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   11074:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  11075:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   11076:       if (ng==1){
                   11077:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   11078:        fprintf(ficgp,"\nunset log y");
                   11079:       }else if (ng==2){
                   11080:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   11081:        fprintf(ficgp,"\nset log y");
                   11082:       }else if (ng==3){
                   11083:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   11084:        fprintf(ficgp,"\nset log y");
                   11085:       }else
                   11086:        fprintf(ficgp,"\nunset title ");
                   11087:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   11088:       i=1;
                   11089:       for(k2=1; k2<=nlstate; k2++) {
                   11090:        k3=i;
                   11091:        for(k=1; k<=(nlstate+ndeath); k++) {
                   11092:          if (k != k2){
                   11093:            switch( ng) {
                   11094:            case 1:
                   11095:              if(nagesqr==0)
                   11096:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   11097:              else /* nagesqr =1 */
                   11098:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   11099:              break;
                   11100:            case 2: /* ng=2 */
                   11101:              if(nagesqr==0)
                   11102:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   11103:              else /* nagesqr =1 */
                   11104:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   11105:              break;
                   11106:            case 3:
                   11107:              if(nagesqr==0)
                   11108:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   11109:              else /* nagesqr =1 */
                   11110:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   11111:              break;
                   11112:            }
                   11113:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  11114:            ijp=1; /* product no age */
                   11115:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   11116:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  11117:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  11118:              switch(Typevar[j]){
                   11119:              case 1:
                   11120:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   11121:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   11122:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   11123:                      if(DummyV[j]==0){/* Bug valgrind */
                   11124:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   11125:                      }else{ /* quantitative */
                   11126:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   11127:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   11128:                      }
                   11129:                      ij++;
1.268     brouard  11130:                    }
1.237     brouard  11131:                  }
1.329     brouard  11132:                }
                   11133:                break;
                   11134:              case 2:
                   11135:                if(cptcovprod >0){
                   11136:                  if(j==Tprod[ijp]) { /* */ 
                   11137:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   11138:                    if(ijp <=cptcovprod) { /* Product */
                   11139:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   11140:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   11141:                          /* 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)]); */
                   11142:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   11143:                        }else{ /* Vn is dummy and Vm is quanti */
                   11144:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11145:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   11146:                        }
                   11147:                      }else{ /* Vn*Vm Vn is quanti */
                   11148:                        if(DummyV[Tvard[ijp][2]]==0){
                   11149:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   11150:                        }else{ /* Both quanti */
                   11151:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   11152:                        }
1.268     brouard  11153:                      }
1.329     brouard  11154:                      ijp++;
1.237     brouard  11155:                    }
1.329     brouard  11156:                  } /* end Tprod */
                   11157:                }
                   11158:                break;
1.349     brouard  11159:              case 3:
                   11160:                if(cptcovdageprod >0){
                   11161:                  /* if(j==Tprod[ijp]) { */ /* not necessary */ 
                   11162:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
1.350     brouard  11163:                    if(ijp <=cptcovprod) { /* Product Vn*Vm and age*VN*Vm*/
                   11164:                      if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   11165:                        if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  11166:                          /* 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)]); */
                   11167:                          fprintf(ficgp,"+p%d*%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   11168:                        }else{ /* Vn is dummy and Vm is quanti */
                   11169:                          /* 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  11170:                          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  11171:                        }
1.350     brouard  11172:                      }else{ /* age* Vn*Vm Vn is quanti HERE */
1.349     brouard  11173:                        if(DummyV[Tvard[ijp][2]]==0){
1.350     brouard  11174:                          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  11175:                        }else{ /* Both quanti */
1.350     brouard  11176:                          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  11177:                        }
                   11178:                      }
                   11179:                      ijp++;
                   11180:                    }
                   11181:                    /* } */ /* end Tprod */
                   11182:                }
                   11183:                break;
1.329     brouard  11184:              case 0:
                   11185:                /* simple covariate */
1.264     brouard  11186:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  11187:                if(Dummy[j]==0){
                   11188:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   11189:                }else{ /* quantitative */
                   11190:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  11191:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  11192:                }
1.329     brouard  11193:               /* end simple */
                   11194:                break;
                   11195:              default:
                   11196:                break;
                   11197:              } /* end switch */
1.237     brouard  11198:            } /* end j */
1.329     brouard  11199:          }else{ /* k=k2 */
                   11200:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   11201:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   11202:            }else
                   11203:              i=i-ncovmodel;
1.223     brouard  11204:          }
1.227     brouard  11205:          
1.223     brouard  11206:          if(ng != 1){
                   11207:            fprintf(ficgp,")/(1");
1.227     brouard  11208:            
1.264     brouard  11209:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  11210:              if(nagesqr==0)
1.264     brouard  11211:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  11212:              else /* nagesqr =1 */
1.264     brouard  11213:                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  11214:               
1.223     brouard  11215:              ij=1;
1.329     brouard  11216:              ijp=1;
                   11217:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   11218:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   11219:                switch(Typevar[j]){
                   11220:                case 1:
                   11221:                  if(cptcovage >0){ 
                   11222:                    if(j==Tage[ij]) { /* Bug valgrind */
                   11223:                      if(ij <=cptcovage) { /* Bug valgrind */
                   11224:                        if(DummyV[j]==0){/* Bug valgrind */
                   11225:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   11226:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   11227:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   11228:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   11229:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   11230:                        }else{ /* quantitative */
                   11231:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   11232:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   11233:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   11234:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   11235:                        }
                   11236:                        ij++;
                   11237:                      }
                   11238:                    }
                   11239:                  }
                   11240:                  break;
                   11241:                case 2:
                   11242:                  if(cptcovprod >0){
                   11243:                    if(j==Tprod[ijp]) { /* */ 
                   11244:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   11245:                      if(ijp <=cptcovprod) { /* Product */
                   11246:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   11247:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   11248:                            /* 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)]); */
                   11249:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   11250:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   11251:                          }else{ /* Vn is dummy and Vm is quanti */
                   11252:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11253:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   11254:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11255:                          }
                   11256:                        }else{ /* Vn*Vm Vn is quanti */
                   11257:                          if(DummyV[Tvard[ijp][2]]==0){
                   11258:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   11259:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   11260:                          }else{ /* Both quanti */
                   11261:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   11262:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11263:                          } 
                   11264:                        }
                   11265:                        ijp++;
                   11266:                      }
                   11267:                    } /* end Tprod */
                   11268:                  } /* end if */
                   11269:                  break;
1.349     brouard  11270:                case 3:
                   11271:                  if(cptcovdageprod >0){
                   11272:                    /* if(j==Tprod[ijp]) { /\* *\/  */
                   11273:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   11274:                      if(ijp <=cptcovprod) { /* Product */
1.350     brouard  11275:                        if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   11276:                          if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  11277:                            /* 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  11278:                            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  11279:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   11280:                          }else{ /* Vn is dummy and Vm is quanti */
                   11281:                            /* 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  11282:                            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  11283:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11284:                          }
                   11285:                        }else{ /* Vn*Vm Vn is quanti */
1.350     brouard  11286:                          if(DummyV[Tvardk[ijp][2]]==0){
                   11287:                            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  11288:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   11289:                          }else{ /* Both quanti */
1.350     brouard  11290:                            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  11291:                            /* fprintf(ficgp,"+p%d*%f*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11292:                          } 
                   11293:                        }
                   11294:                        ijp++;
                   11295:                      }
                   11296:                    /* } /\* end Tprod *\/ */
                   11297:                  } /* end if */
                   11298:                  break;
1.329     brouard  11299:                case 0: 
                   11300:                  /* simple covariate */
                   11301:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   11302:                  if(Dummy[j]==0){
                   11303:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   11304:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   11305:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   11306:                  }else{ /* quantitative */
                   11307:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   11308:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   11309:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   11310:                  }
                   11311:                  /* end simple */
                   11312:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   11313:                  break;
                   11314:                default:
                   11315:                  break;
                   11316:                } /* end switch */
1.223     brouard  11317:              }
                   11318:              fprintf(ficgp,")");
                   11319:            }
                   11320:            fprintf(ficgp,")");
                   11321:            if(ng ==2)
1.276     brouard  11322:              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  11323:            else /* ng= 3 */
1.276     brouard  11324:              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  11325:           }else{ /* end ng <> 1 */
1.223     brouard  11326:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  11327:              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  11328:          }
                   11329:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   11330:            fprintf(ficgp,",");
                   11331:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   11332:            fprintf(ficgp,",");
                   11333:          i=i+ncovmodel;
                   11334:        } /* end k */
                   11335:       } /* end k2 */
1.276     brouard  11336:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   11337:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.337     brouard  11338:     } /* end resultline */
1.223     brouard  11339:   } /* end ng */
                   11340:   /* avoid: */
                   11341:   fflush(ficgp); 
1.126     brouard  11342: }  /* end gnuplot */
                   11343: 
                   11344: 
                   11345: /*************** Moving average **************/
1.219     brouard  11346: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  11347:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  11348:    
1.222     brouard  11349:    int i, cpt, cptcod;
                   11350:    int modcovmax =1;
                   11351:    int mobilavrange, mob;
                   11352:    int iage=0;
1.288     brouard  11353:    int firstA1=0, firstA2=0;
1.222     brouard  11354: 
1.266     brouard  11355:    double sum=0., sumr=0.;
1.222     brouard  11356:    double age;
1.266     brouard  11357:    double *sumnewp, *sumnewm, *sumnewmr;
                   11358:    double *agemingood, *agemaxgood; 
                   11359:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  11360:   
                   11361:   
1.278     brouard  11362:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   11363:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  11364: 
                   11365:    sumnewp = vector(1,ncovcombmax);
                   11366:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  11367:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  11368:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  11369:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  11370:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  11371:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  11372: 
                   11373:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  11374:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  11375:      sumnewp[cptcod]=0.;
1.266     brouard  11376:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   11377:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  11378:    }
                   11379:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   11380:   
1.266     brouard  11381:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   11382:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  11383:      else mobilavrange=mobilav;
                   11384:      for (age=bage; age<=fage; age++)
                   11385:        for (i=1; i<=nlstate;i++)
                   11386:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   11387:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   11388:      /* We keep the original values on the extreme ages bage, fage and for 
                   11389:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   11390:        we use a 5 terms etc. until the borders are no more concerned. 
                   11391:      */ 
                   11392:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   11393:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  11394:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   11395:           sumnewm[cptcod]=0.;
                   11396:           for (i=1; i<=nlstate;i++){
1.222     brouard  11397:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   11398:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   11399:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   11400:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   11401:             }
                   11402:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  11403:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   11404:           } /* end i */
                   11405:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   11406:         } /* end cptcod */
1.222     brouard  11407:        }/* end age */
                   11408:      }/* end mob */
1.266     brouard  11409:    }else{
                   11410:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  11411:      return -1;
1.266     brouard  11412:    }
                   11413: 
                   11414:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  11415:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   11416:      if(invalidvarcomb[cptcod]){
                   11417:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   11418:        continue;
                   11419:      }
1.219     brouard  11420: 
1.266     brouard  11421:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   11422:        sumnewm[cptcod]=0.;
                   11423:        sumnewmr[cptcod]=0.;
                   11424:        for (i=1; i<=nlstate;i++){
                   11425:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   11426:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   11427:        }
                   11428:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   11429:         agemingoodr[cptcod]=age;
                   11430:        }
                   11431:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   11432:           agemingood[cptcod]=age;
                   11433:        }
                   11434:      } /* age */
                   11435:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  11436:        sumnewm[cptcod]=0.;
1.266     brouard  11437:        sumnewmr[cptcod]=0.;
1.222     brouard  11438:        for (i=1; i<=nlstate;i++){
                   11439:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  11440:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   11441:        }
                   11442:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   11443:         agemaxgoodr[cptcod]=age;
1.222     brouard  11444:        }
                   11445:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  11446:         agemaxgood[cptcod]=age;
                   11447:        }
                   11448:      } /* age */
                   11449:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   11450:      /* but they will change */
1.288     brouard  11451:      firstA1=0;firstA2=0;
1.266     brouard  11452:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   11453:        sumnewm[cptcod]=0.;
                   11454:        sumnewmr[cptcod]=0.;
                   11455:        for (i=1; i<=nlstate;i++){
                   11456:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   11457:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   11458:        }
                   11459:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   11460:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   11461:           agemaxgoodr[cptcod]=age;  /* age min */
                   11462:           for (i=1; i<=nlstate;i++)
                   11463:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   11464:         }else{ /* bad we change the value with the values of good ages */
                   11465:           for (i=1; i<=nlstate;i++){
                   11466:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   11467:           } /* i */
                   11468:         } /* end bad */
                   11469:        }else{
                   11470:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   11471:           agemaxgood[cptcod]=age;
                   11472:         }else{ /* bad we change the value with the values of good ages */
                   11473:           for (i=1; i<=nlstate;i++){
                   11474:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   11475:           } /* i */
                   11476:         } /* end bad */
                   11477:        }/* end else */
                   11478:        sum=0.;sumr=0.;
                   11479:        for (i=1; i<=nlstate;i++){
                   11480:         sum+=mobaverage[(int)age][i][cptcod];
                   11481:         sumr+=probs[(int)age][i][cptcod];
                   11482:        }
                   11483:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  11484:         if(!firstA1){
                   11485:           firstA1=1;
                   11486:           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);
                   11487:         }
                   11488:         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  11489:        } /* end bad */
                   11490:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   11491:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  11492:         if(!firstA2){
                   11493:           firstA2=1;
                   11494:           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);
                   11495:         }
                   11496:         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  11497:        } /* end bad */
                   11498:      }/* age */
1.266     brouard  11499: 
                   11500:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  11501:        sumnewm[cptcod]=0.;
1.266     brouard  11502:        sumnewmr[cptcod]=0.;
1.222     brouard  11503:        for (i=1; i<=nlstate;i++){
                   11504:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  11505:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   11506:        } 
                   11507:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   11508:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   11509:           agemingoodr[cptcod]=age;
                   11510:           for (i=1; i<=nlstate;i++)
                   11511:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   11512:         }else{ /* bad we change the value with the values of good ages */
                   11513:           for (i=1; i<=nlstate;i++){
                   11514:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   11515:           } /* i */
                   11516:         } /* end bad */
                   11517:        }else{
                   11518:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   11519:           agemingood[cptcod]=age;
                   11520:         }else{ /* bad */
                   11521:           for (i=1; i<=nlstate;i++){
                   11522:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   11523:           } /* i */
                   11524:         } /* end bad */
                   11525:        }/* end else */
                   11526:        sum=0.;sumr=0.;
                   11527:        for (i=1; i<=nlstate;i++){
                   11528:         sum+=mobaverage[(int)age][i][cptcod];
                   11529:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  11530:        }
1.266     brouard  11531:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  11532:         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  11533:        } /* end bad */
                   11534:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   11535:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  11536:         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  11537:        } /* end bad */
                   11538:      }/* age */
1.266     brouard  11539: 
1.222     brouard  11540:                
                   11541:      for (age=bage; age<=fage; age++){
1.235     brouard  11542:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  11543:        sumnewp[cptcod]=0.;
                   11544:        sumnewm[cptcod]=0.;
                   11545:        for (i=1; i<=nlstate;i++){
                   11546:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   11547:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   11548:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   11549:        }
                   11550:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   11551:      }
                   11552:      /* printf("\n"); */
                   11553:      /* } */
1.266     brouard  11554: 
1.222     brouard  11555:      /* brutal averaging */
1.266     brouard  11556:      /* for (i=1; i<=nlstate;i++){ */
                   11557:      /*   for (age=1; age<=bage; age++){ */
                   11558:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   11559:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   11560:      /*   }     */
                   11561:      /*   for (age=fage; age<=AGESUP; age++){ */
                   11562:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   11563:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   11564:      /*   } */
                   11565:      /* } /\* end i status *\/ */
                   11566:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   11567:      /*   for (age=1; age<=AGESUP; age++){ */
                   11568:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   11569:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   11570:      /*   } */
                   11571:      /* } */
1.222     brouard  11572:    }/* end cptcod */
1.266     brouard  11573:    free_vector(agemaxgoodr,1, ncovcombmax);
                   11574:    free_vector(agemaxgood,1, ncovcombmax);
                   11575:    free_vector(agemingood,1, ncovcombmax);
                   11576:    free_vector(agemingoodr,1, ncovcombmax);
                   11577:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  11578:    free_vector(sumnewm,1, ncovcombmax);
                   11579:    free_vector(sumnewp,1, ncovcombmax);
                   11580:    return 0;
                   11581:  }/* End movingaverage */
1.218     brouard  11582:  
1.126     brouard  11583: 
1.296     brouard  11584:  
1.126     brouard  11585: /************** Forecasting ******************/
1.296     brouard  11586: /* 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)*/
                   11587: 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){
                   11588:   /* dateintemean, mean date of interviews
                   11589:      dateprojd, year, month, day of starting projection 
                   11590:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  11591:      agemin, agemax range of age
                   11592:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   11593:   */
1.296     brouard  11594:   /* double anprojd, mprojd, jprojd; */
                   11595:   /* double anprojf, mprojf, jprojf; */
1.359     brouard  11596:   int yearp, stepsize, hstepm, nhstepm, j, k, i, h,  nres=0;
1.126     brouard  11597:   double agec; /* generic age */
1.359     brouard  11598:   double agelim, ppij;
                   11599:   /*double *popcount;*/
1.126     brouard  11600:   double ***p3mat;
1.218     brouard  11601:   /* double ***mobaverage; */
1.126     brouard  11602:   char fileresf[FILENAMELENGTH];
                   11603: 
                   11604:   agelim=AGESUP;
1.211     brouard  11605:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   11606:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   11607:      We still use firstpass and lastpass as another selection.
                   11608:   */
1.214     brouard  11609:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   11610:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  11611:  
1.201     brouard  11612:   strcpy(fileresf,"F_"); 
                   11613:   strcat(fileresf,fileresu);
1.126     brouard  11614:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   11615:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   11616:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   11617:   }
1.235     brouard  11618:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   11619:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  11620: 
1.225     brouard  11621:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  11622: 
                   11623: 
                   11624:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11625:   if (stepm<=12) stepsize=1;
                   11626:   if(estepm < stepm){
                   11627:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   11628:   }
1.270     brouard  11629:   else{
                   11630:     hstepm=estepm;   
                   11631:   }
                   11632:   if(estepm > stepm){ /* Yes every two year */
                   11633:     stepsize=2;
                   11634:   }
1.296     brouard  11635:   hstepm=hstepm/stepm;
1.126     brouard  11636: 
1.296     brouard  11637:   
                   11638:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   11639:   /*                              fractional in yp1 *\/ */
                   11640:   /* aintmean=yp; */
                   11641:   /* yp2=modf((yp1*12),&yp); */
                   11642:   /* mintmean=yp; */
                   11643:   /* yp1=modf((yp2*30.5),&yp); */
                   11644:   /* jintmean=yp; */
                   11645:   /* if(jintmean==0) jintmean=1; */
                   11646:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  11647: 
1.296     brouard  11648: 
                   11649:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   11650:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   11651:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.351     brouard  11652:   /* i1=pow(2,cptcoveff); */
                   11653:   /* if (cptcovn < 1){i1=1;} */
1.126     brouard  11654:   
1.296     brouard  11655:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  11656:   
                   11657:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  11658:   
1.126     brouard  11659: /*           if (h==(int)(YEARM*yearp)){ */
1.351     brouard  11660:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11661:     k=TKresult[nres];
                   11662:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   11663:     /*  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) *\/ */
                   11664:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   11665:     /*   continue; */
                   11666:     /* if(invalidvarcomb[k]){ */
                   11667:     /*   printf("\nCombination (%d) projection ignored because no cases \n",k);  */
                   11668:     /*   continue; */
                   11669:     /* } */
1.227     brouard  11670:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
1.351     brouard  11671:     for(j=1;j<=cptcovs;j++){
                   11672:       /* for(j=1;j<=cptcoveff;j++) { */
                   11673:     /*   /\* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); *\/ */
                   11674:     /*   fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11675:     /* } */
                   11676:     /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11677:     /*   fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11678:     /* } */
                   11679:       fprintf(ficresf," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.235     brouard  11680:     }
1.351     brouard  11681:  
1.227     brouard  11682:     fprintf(ficresf," yearproj age");
                   11683:     for(j=1; j<=nlstate+ndeath;j++){ 
                   11684:       for(i=1; i<=nlstate;i++)               
                   11685:        fprintf(ficresf," p%d%d",i,j);
                   11686:       fprintf(ficresf," wp.%d",j);
                   11687:     }
1.296     brouard  11688:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  11689:       fprintf(ficresf,"\n");
1.296     brouard  11690:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  11691:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   11692:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  11693:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   11694:        nhstepm = nhstepm/hstepm; 
                   11695:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11696:        oldm=oldms;savm=savms;
1.268     brouard  11697:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  11698:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  11699:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  11700:        for (h=0; h<=nhstepm; h++){
                   11701:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  11702:            break;
                   11703:          }
                   11704:        }
                   11705:        fprintf(ficresf,"\n");
1.351     brouard  11706:        /* for(j=1;j<=cptcoveff;j++)  */
                   11707:        for(j=1;j<=cptcovs;j++) 
                   11708:          fprintf(ficresf,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.332     brouard  11709:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
1.351     brouard  11710:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* TnsdVar[Tvaraff]  correct *\/ */
1.296     brouard  11711:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  11712:        
                   11713:        for(j=1; j<=nlstate+ndeath;j++) {
                   11714:          ppij=0.;
                   11715:          for(i=1; i<=nlstate;i++) {
1.278     brouard  11716:            if (mobilav>=1)
                   11717:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   11718:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   11719:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   11720:            }
1.268     brouard  11721:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   11722:          } /* end i */
                   11723:          fprintf(ficresf," %.3f", ppij);
                   11724:        }/* end j */
1.227     brouard  11725:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11726:       } /* end agec */
1.266     brouard  11727:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   11728:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  11729:     } /* end yearp */
                   11730:   } /* end  k */
1.219     brouard  11731:        
1.126     brouard  11732:   fclose(ficresf);
1.215     brouard  11733:   printf("End of Computing forecasting \n");
                   11734:   fprintf(ficlog,"End of Computing forecasting\n");
                   11735: 
1.126     brouard  11736: }
                   11737: 
1.269     brouard  11738: /************** Back Forecasting ******************/
1.296     brouard  11739:  /* 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){ */
                   11740:  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){
                   11741:   /* back1, year, month, day of starting backprojection
1.267     brouard  11742:      agemin, agemax range of age
                   11743:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  11744:      anback2 year of end of backprojection (same day and month as back1).
                   11745:      prevacurrent and prev are prevalences.
1.267     brouard  11746:   */
1.359     brouard  11747:   int yearp, stepsize, hstepm, nhstepm, j, k,  i, h, nres=0;
1.267     brouard  11748:   double agec; /* generic age */
1.359     brouard  11749:   double agelim, ppij, ppi; /* ,jintmean,mintmean,aintmean;*/
                   11750:   /*double *popcount;*/
1.267     brouard  11751:   double ***p3mat;
                   11752:   /* double ***mobaverage; */
                   11753:   char fileresfb[FILENAMELENGTH];
                   11754:  
1.268     brouard  11755:   agelim=AGEINF;
1.267     brouard  11756:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   11757:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   11758:      We still use firstpass and lastpass as another selection.
                   11759:   */
                   11760:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   11761:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   11762: 
                   11763:   /*Do we need to compute prevalence again?*/
                   11764: 
                   11765:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   11766:   
                   11767:   strcpy(fileresfb,"FB_");
                   11768:   strcat(fileresfb,fileresu);
                   11769:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   11770:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   11771:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   11772:   }
                   11773:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   11774:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   11775:   
                   11776:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   11777:   
                   11778:    
                   11779:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11780:   if (stepm<=12) stepsize=1;
                   11781:   if(estepm < stepm){
                   11782:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   11783:   }
1.270     brouard  11784:   else{
                   11785:     hstepm=estepm;   
                   11786:   }
                   11787:   if(estepm >= stepm){ /* Yes every two year */
                   11788:     stepsize=2;
                   11789:   }
1.267     brouard  11790:   
                   11791:   hstepm=hstepm/stepm;
1.296     brouard  11792:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   11793:   /*                              fractional in yp1 *\/ */
                   11794:   /* aintmean=yp; */
                   11795:   /* yp2=modf((yp1*12),&yp); */
                   11796:   /* mintmean=yp; */
                   11797:   /* yp1=modf((yp2*30.5),&yp); */
                   11798:   /* jintmean=yp; */
                   11799:   /* if(jintmean==0) jintmean=1; */
                   11800:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  11801:   
1.351     brouard  11802:   /* i1=pow(2,cptcoveff); */
                   11803:   /* if (cptcovn < 1){i1=1;} */
1.267     brouard  11804:   
1.296     brouard  11805:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   11806:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  11807:   
                   11808:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   11809:   
1.351     brouard  11810:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11811:     k=TKresult[nres];
                   11812:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   11813:   /* for(k=1; k<=i1;k++){ */
                   11814:   /*   if(i1 != 1 && TKresult[nres]!= k) */
                   11815:   /*     continue; */
                   11816:   /*   if(invalidvarcomb[k]){ */
                   11817:   /*     printf("\nCombination (%d) projection ignored because no cases \n",k);  */
                   11818:   /*     continue; */
                   11819:   /*   } */
1.268     brouard  11820:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.351     brouard  11821:     for(j=1;j<=cptcovs;j++){
                   11822:     /* for(j=1;j<=cptcoveff;j++) { */
                   11823:     /*   fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11824:     /* } */
                   11825:       fprintf(ficresfb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.267     brouard  11826:     }
1.351     brouard  11827:    /*  fprintf(ficrespij,"******\n"); */
                   11828:    /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11829:    /*    fprintf(ficresfb," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11830:    /*  } */
1.267     brouard  11831:     fprintf(ficresfb," yearbproj age");
                   11832:     for(j=1; j<=nlstate+ndeath;j++){
                   11833:       for(i=1; i<=nlstate;i++)
1.268     brouard  11834:        fprintf(ficresfb," b%d%d",i,j);
                   11835:       fprintf(ficresfb," b.%d",j);
1.267     brouard  11836:     }
1.296     brouard  11837:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  11838:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   11839:       fprintf(ficresfb,"\n");
1.296     brouard  11840:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  11841:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  11842:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   11843:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  11844:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  11845:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  11846:        nhstepm = nhstepm/hstepm;
                   11847:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11848:        oldm=oldms;savm=savms;
1.268     brouard  11849:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  11850:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  11851:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  11852:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   11853:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   11854:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  11855:        for (h=0; h<=nhstepm; h++){
1.268     brouard  11856:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   11857:            break;
                   11858:          }
                   11859:        }
                   11860:        fprintf(ficresfb,"\n");
1.351     brouard  11861:        /* for(j=1;j<=cptcoveff;j++) */
                   11862:        for(j=1;j<=cptcovs;j++)
                   11863:          fprintf(ficresfb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11864:          /* fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.296     brouard  11865:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  11866:        for(i=1; i<=nlstate+ndeath;i++) {
                   11867:          ppij=0.;ppi=0.;
                   11868:          for(j=1; j<=nlstate;j++) {
                   11869:            /* if (mobilav==1) */
1.269     brouard  11870:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   11871:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   11872:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   11873:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  11874:              /* else { */
                   11875:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   11876:              /* } */
1.268     brouard  11877:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   11878:          } /* end j */
                   11879:          if(ppi <0.99){
                   11880:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   11881:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   11882:          }
                   11883:          fprintf(ficresfb," %.3f", ppij);
                   11884:        }/* end j */
1.267     brouard  11885:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11886:       } /* end agec */
                   11887:     } /* end yearp */
                   11888:   } /* end k */
1.217     brouard  11889:   
1.267     brouard  11890:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  11891:   
1.267     brouard  11892:   fclose(ficresfb);
                   11893:   printf("End of Computing Back forecasting \n");
                   11894:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  11895:        
1.267     brouard  11896: }
1.217     brouard  11897: 
1.269     brouard  11898: /* Variance of prevalence limit: varprlim */
                   11899:  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  11900:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  11901:  
                   11902:    char fileresvpl[FILENAMELENGTH];  
                   11903:    FILE *ficresvpl;
                   11904:    double **oldm, **savm;
                   11905:    double **varpl; /* Variances of prevalence limits by age */   
                   11906:    int i1, k, nres, j ;
                   11907:    
                   11908:     strcpy(fileresvpl,"VPL_");
                   11909:     strcat(fileresvpl,fileresu);
                   11910:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  11911:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  11912:       exit(0);
                   11913:     }
1.288     brouard  11914:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   11915:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  11916:     
                   11917:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   11918:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   11919:     
                   11920:     i1=pow(2,cptcoveff);
                   11921:     if (cptcovn < 1){i1=1;}
                   11922: 
1.337     brouard  11923:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11924:        k=TKresult[nres];
1.338     brouard  11925:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  11926:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
1.269     brouard  11927:       if(i1 != 1 && TKresult[nres]!= k)
                   11928:        continue;
                   11929:       fprintf(ficresvpl,"\n#****** ");
                   11930:       printf("\n#****** ");
                   11931:       fprintf(ficlog,"\n#****** ");
1.337     brouard  11932:       for(j=1;j<=cptcovs;j++) {
                   11933:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11934:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11935:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11936:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11937:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.269     brouard  11938:       }
1.337     brouard  11939:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   11940:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11941:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11942:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11943:       /* }      */
1.269     brouard  11944:       fprintf(ficresvpl,"******\n");
                   11945:       printf("******\n");
                   11946:       fprintf(ficlog,"******\n");
                   11947:       
                   11948:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   11949:       oldm=oldms;savm=savms;
                   11950:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   11951:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   11952:       /*}*/
                   11953:     }
                   11954:     
                   11955:     fclose(ficresvpl);
1.288     brouard  11956:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   11957:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  11958: 
                   11959:  }
                   11960: /* Variance of back prevalence: varbprlim */
                   11961:  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){
                   11962:       /*------- Variance of back (stable) prevalence------*/
                   11963: 
                   11964:    char fileresvbl[FILENAMELENGTH];  
                   11965:    FILE  *ficresvbl;
                   11966: 
                   11967:    double **oldm, **savm;
                   11968:    double **varbpl; /* Variances of back prevalence limits by age */   
                   11969:    int i1, k, nres, j ;
                   11970: 
                   11971:    strcpy(fileresvbl,"VBL_");
                   11972:    strcat(fileresvbl,fileresu);
                   11973:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   11974:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   11975:      exit(0);
                   11976:    }
                   11977:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   11978:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   11979:    
                   11980:    
                   11981:    i1=pow(2,cptcoveff);
                   11982:    if (cptcovn < 1){i1=1;}
                   11983:    
1.337     brouard  11984:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11985:      k=TKresult[nres];
1.338     brouard  11986:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  11987:     /* for(k=1; k<=i1;k++){ */
                   11988:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   11989:     /*          continue; */
1.269     brouard  11990:        fprintf(ficresvbl,"\n#****** ");
                   11991:        printf("\n#****** ");
                   11992:        fprintf(ficlog,"\n#****** ");
1.337     brouard  11993:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
1.338     brouard  11994:         printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   11995:         fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   11996:         fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
1.337     brouard  11997:        /* for(j=1;j<=cptcoveff;j++) { */
                   11998:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11999:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12000:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12001:        /* } */
                   12002:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12003:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12004:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12005:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
1.269     brouard  12006:        }
                   12007:        fprintf(ficresvbl,"******\n");
                   12008:        printf("******\n");
                   12009:        fprintf(ficlog,"******\n");
                   12010:        
                   12011:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   12012:        oldm=oldms;savm=savms;
                   12013:        
                   12014:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   12015:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   12016:        /*}*/
                   12017:      }
                   12018:    
                   12019:    fclose(ficresvbl);
                   12020:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   12021:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   12022: 
                   12023:  } /* End of varbprlim */
                   12024: 
1.126     brouard  12025: /************** Forecasting *****not tested NB*************/
1.227     brouard  12026: /* 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  12027:   
1.227     brouard  12028: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   12029: /*   int *popage; */
                   12030: /*   double calagedatem, agelim, kk1, kk2; */
                   12031: /*   double *popeffectif,*popcount; */
                   12032: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   12033: /*   /\* double ***mobaverage; *\/ */
                   12034: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  12035: 
1.227     brouard  12036: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   12037: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   12038: /*   agelim=AGESUP; */
                   12039: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  12040:   
1.227     brouard  12041: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  12042:   
                   12043:   
1.227     brouard  12044: /*   strcpy(filerespop,"POP_");  */
                   12045: /*   strcat(filerespop,fileresu); */
                   12046: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   12047: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   12048: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   12049: /*   } */
                   12050: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   12051: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  12052: 
1.227     brouard  12053: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  12054: 
1.227     brouard  12055: /*   /\* if (mobilav!=0) { *\/ */
                   12056: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   12057: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   12058: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   12059: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   12060: /*   /\*   } *\/ */
                   12061: /*   /\* } *\/ */
1.126     brouard  12062: 
1.227     brouard  12063: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   12064: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  12065:   
1.227     brouard  12066: /*   agelim=AGESUP; */
1.126     brouard  12067:   
1.227     brouard  12068: /*   hstepm=1; */
                   12069: /*   hstepm=hstepm/stepm;  */
1.218     brouard  12070:        
1.227     brouard  12071: /*   if (popforecast==1) { */
                   12072: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   12073: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   12074: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   12075: /*     }  */
                   12076: /*     popage=ivector(0,AGESUP); */
                   12077: /*     popeffectif=vector(0,AGESUP); */
                   12078: /*     popcount=vector(0,AGESUP); */
1.126     brouard  12079:     
1.227     brouard  12080: /*     i=1;    */
                   12081: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  12082:     
1.227     brouard  12083: /*     imx=i; */
                   12084: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   12085: /*   } */
1.218     brouard  12086:   
1.227     brouard  12087: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   12088: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   12089: /*       k=k+1; */
                   12090: /*       fprintf(ficrespop,"\n#******"); */
                   12091: /*       for(j=1;j<=cptcoveff;j++) { */
                   12092: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   12093: /*       } */
                   12094: /*       fprintf(ficrespop,"******\n"); */
                   12095: /*       fprintf(ficrespop,"# Age"); */
                   12096: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   12097: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  12098:       
1.227     brouard  12099: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   12100: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  12101:        
1.227     brouard  12102: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   12103: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   12104: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  12105:          
1.227     brouard  12106: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   12107: /*       oldm=oldms;savm=savms; */
                   12108: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  12109:          
1.227     brouard  12110: /*       for (h=0; h<=nhstepm; h++){ */
                   12111: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   12112: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   12113: /*         }  */
                   12114: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   12115: /*           kk1=0.;kk2=0; */
                   12116: /*           for(i=1; i<=nlstate;i++) {               */
                   12117: /*             if (mobilav==1)  */
                   12118: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   12119: /*             else { */
                   12120: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   12121: /*             } */
                   12122: /*           } */
                   12123: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   12124: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   12125: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   12126: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   12127: /*           } */
                   12128: /*         } */
                   12129: /*         for(i=1; i<=nlstate;i++){ */
                   12130: /*           kk1=0.; */
                   12131: /*           for(j=1; j<=nlstate;j++){ */
                   12132: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   12133: /*           } */
                   12134: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   12135: /*         } */
1.218     brouard  12136:            
1.227     brouard  12137: /*         if (h==(int)(calagedatem+12*cpt)) */
                   12138: /*           for(j=1; j<=nlstate;j++)  */
                   12139: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   12140: /*       } */
                   12141: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   12142: /*     } */
                   12143: /*       } */
1.218     brouard  12144:       
1.227     brouard  12145: /*       /\******\/ */
1.218     brouard  12146:       
1.227     brouard  12147: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   12148: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   12149: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   12150: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   12151: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  12152:          
1.227     brouard  12153: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   12154: /*       oldm=oldms;savm=savms; */
                   12155: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   12156: /*       for (h=0; h<=nhstepm; h++){ */
                   12157: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   12158: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   12159: /*         }  */
                   12160: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   12161: /*           kk1=0.;kk2=0; */
                   12162: /*           for(i=1; i<=nlstate;i++) {               */
                   12163: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   12164: /*           } */
                   12165: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   12166: /*         } */
                   12167: /*       } */
                   12168: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   12169: /*     } */
                   12170: /*       } */
                   12171: /*     }  */
                   12172: /*   } */
1.218     brouard  12173:   
1.227     brouard  12174: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  12175:   
1.227     brouard  12176: /*   if (popforecast==1) { */
                   12177: /*     free_ivector(popage,0,AGESUP); */
                   12178: /*     free_vector(popeffectif,0,AGESUP); */
                   12179: /*     free_vector(popcount,0,AGESUP); */
                   12180: /*   } */
                   12181: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   12182: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   12183: /*   fclose(ficrespop); */
                   12184: /* } /\* End of popforecast *\/ */
1.218     brouard  12185:  
1.126     brouard  12186: int fileappend(FILE *fichier, char *optionfich)
                   12187: {
                   12188:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   12189:     printf("Problem with file: %s\n", optionfich);
                   12190:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   12191:     return (0);
                   12192:   }
                   12193:   fflush(fichier);
                   12194:   return (1);
                   12195: }
                   12196: 
                   12197: 
                   12198: /**************** function prwizard **********************/
                   12199: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   12200: {
                   12201: 
                   12202:   /* Wizard to print covariance matrix template */
                   12203: 
1.164     brouard  12204:   char ca[32], cb[32];
                   12205:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  12206:   int numlinepar;
                   12207: 
                   12208:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12209:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12210:   for(i=1; i <=nlstate; i++){
                   12211:     jj=0;
                   12212:     for(j=1; j <=nlstate+ndeath; j++){
                   12213:       if(j==i) continue;
                   12214:       jj++;
                   12215:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   12216:       printf("%1d%1d",i,j);
                   12217:       fprintf(ficparo,"%1d%1d",i,j);
                   12218:       for(k=1; k<=ncovmodel;k++){
                   12219:        /*        printf(" %lf",param[i][j][k]); */
                   12220:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   12221:        printf(" 0.");
                   12222:        fprintf(ficparo," 0.");
                   12223:       }
                   12224:       printf("\n");
                   12225:       fprintf(ficparo,"\n");
                   12226:     }
                   12227:   }
                   12228:   printf("# Scales (for hessian or gradient estimation)\n");
                   12229:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   12230:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   12231:   for(i=1; i <=nlstate; i++){
                   12232:     jj=0;
                   12233:     for(j=1; j <=nlstate+ndeath; j++){
                   12234:       if(j==i) continue;
                   12235:       jj++;
                   12236:       fprintf(ficparo,"%1d%1d",i,j);
                   12237:       printf("%1d%1d",i,j);
                   12238:       fflush(stdout);
                   12239:       for(k=1; k<=ncovmodel;k++){
                   12240:        /*      printf(" %le",delti3[i][j][k]); */
                   12241:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   12242:        printf(" 0.");
                   12243:        fprintf(ficparo," 0.");
                   12244:       }
                   12245:       numlinepar++;
                   12246:       printf("\n");
                   12247:       fprintf(ficparo,"\n");
                   12248:     }
                   12249:   }
                   12250:   printf("# Covariance matrix\n");
                   12251: /* # 121 Var(a12)\n\ */
                   12252: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   12253: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   12254: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   12255: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   12256: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   12257: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   12258: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   12259:   fflush(stdout);
                   12260:   fprintf(ficparo,"# Covariance matrix\n");
                   12261:   /* # 121 Var(a12)\n\ */
                   12262:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   12263:   /* #   ...\n\ */
                   12264:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   12265:   
                   12266:   for(itimes=1;itimes<=2;itimes++){
                   12267:     jj=0;
                   12268:     for(i=1; i <=nlstate; i++){
                   12269:       for(j=1; j <=nlstate+ndeath; j++){
                   12270:        if(j==i) continue;
                   12271:        for(k=1; k<=ncovmodel;k++){
                   12272:          jj++;
                   12273:          ca[0]= k+'a'-1;ca[1]='\0';
                   12274:          if(itimes==1){
                   12275:            printf("#%1d%1d%d",i,j,k);
                   12276:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   12277:          }else{
                   12278:            printf("%1d%1d%d",i,j,k);
                   12279:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   12280:            /*  printf(" %.5le",matcov[i][j]); */
                   12281:          }
                   12282:          ll=0;
                   12283:          for(li=1;li <=nlstate; li++){
                   12284:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   12285:              if(lj==li) continue;
                   12286:              for(lk=1;lk<=ncovmodel;lk++){
                   12287:                ll++;
                   12288:                if(ll<=jj){
                   12289:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   12290:                  if(ll<jj){
                   12291:                    if(itimes==1){
                   12292:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12293:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12294:                    }else{
                   12295:                      printf(" 0.");
                   12296:                      fprintf(ficparo," 0.");
                   12297:                    }
                   12298:                  }else{
                   12299:                    if(itimes==1){
                   12300:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   12301:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   12302:                    }else{
                   12303:                      printf(" 0.");
                   12304:                      fprintf(ficparo," 0.");
                   12305:                    }
                   12306:                  }
                   12307:                }
                   12308:              } /* end lk */
                   12309:            } /* end lj */
                   12310:          } /* end li */
                   12311:          printf("\n");
                   12312:          fprintf(ficparo,"\n");
                   12313:          numlinepar++;
                   12314:        } /* end k*/
                   12315:       } /*end j */
                   12316:     } /* end i */
                   12317:   } /* end itimes */
                   12318: 
                   12319: } /* end of prwizard */
                   12320: /******************* Gompertz Likelihood ******************************/
                   12321: double gompertz(double x[])
                   12322: { 
1.302     brouard  12323:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  12324:   int i,n=0; /* n is the size of the sample */
                   12325: 
1.220     brouard  12326:   for (i=1;i<=imx ; i++) {
1.126     brouard  12327:     sump=sump+weight[i];
                   12328:     /*    sump=sump+1;*/
                   12329:     num=num+1;
                   12330:   }
1.302     brouard  12331:   L=0.0;
                   12332:   /* agegomp=AGEGOMP; */
1.126     brouard  12333:   /* for (i=0; i<=imx; i++) 
                   12334:      if (wav[i]>0) printf("i=%d ageex=%lf agecens=%lf agedc=%lf cens=%d %d\n" ,i,ageexmed[i],agecens[i],agedc[i],cens[i],wav[i]);*/
                   12335: 
1.302     brouard  12336:   for (i=1;i<=imx ; i++) {
                   12337:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   12338:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   12339:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   12340:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   12341:      * +
                   12342:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   12343:      */
                   12344:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   12345:        if (cens[i] == 1){
                   12346:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   12347:        } else if (cens[i] == 0){
1.126     brouard  12348:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.362     brouard  12349:          +log(fabs(x[1])/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   12350:        /* +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM); */  /* To be seen */
1.302     brouard  12351:       } else
                   12352:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  12353:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  12354:        L=L+A*weight[i];
1.126     brouard  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]);*/
1.302     brouard  12356:      }
                   12357:   }
1.126     brouard  12358: 
1.302     brouard  12359:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  12360:  
                   12361:   return -2*L*num/sump;
                   12362: }
                   12363: 
1.136     brouard  12364: #ifdef GSL
                   12365: /******************* Gompertz_f Likelihood ******************************/
                   12366: double gompertz_f(const gsl_vector *v, void *params)
                   12367: { 
1.302     brouard  12368:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  12369:   double *x= (double *) v->data;
                   12370:   int i,n=0; /* n is the size of the sample */
                   12371: 
                   12372:   for (i=0;i<=imx-1 ; i++) {
                   12373:     sump=sump+weight[i];
                   12374:     /*    sump=sump+1;*/
                   12375:     num=num+1;
                   12376:   }
                   12377:  
                   12378:  
                   12379:   /* for (i=0; i<=imx; i++) 
                   12380:      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]);*/
                   12381:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   12382:   for (i=1;i<=imx ; i++)
                   12383:     {
                   12384:       if (cens[i] == 1 && wav[i]>1)
                   12385:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   12386:       
                   12387:       if (cens[i] == 0 && wav[i]>1)
                   12388:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   12389:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   12390:       
                   12391:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   12392:       if (wav[i] > 1 ) { /* ??? */
                   12393:        LL=LL+A*weight[i];
                   12394:        /*      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]);*/
                   12395:       }
                   12396:     }
                   12397: 
                   12398:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   12399:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   12400:  
                   12401:   return -2*LL*num/sump;
                   12402: }
                   12403: #endif
                   12404: 
1.126     brouard  12405: /******************* Printing html file ***********/
1.201     brouard  12406: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  12407:                  int lastpass, int stepm, int weightopt, char model[],\
                   12408:                  int imx,  double p[],double **matcov,double agemortsup){
                   12409:   int i,k;
                   12410: 
                   12411:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   12412:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   12413:   for (i=1;i<=2;i++) 
                   12414:     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  12415:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  12416:   fprintf(fichtm,"</ul>");
                   12417: 
                   12418: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   12419: 
                   12420:  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>");
                   12421: 
                   12422:  for (k=agegomp;k<(agemortsup-2);k++) 
                   12423:    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]);
                   12424: 
                   12425:  
                   12426:   fflush(fichtm);
                   12427: }
                   12428: 
                   12429: /******************* Gnuplot file **************/
1.201     brouard  12430: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  12431: 
                   12432:   char dirfileres[132],optfileres[132];
1.164     brouard  12433: 
1.359     brouard  12434:   /*int ng;*/
1.126     brouard  12435: 
                   12436: 
                   12437:   /*#ifdef windows */
                   12438:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   12439:     /*#endif */
                   12440: 
                   12441: 
                   12442:   strcpy(dirfileres,optionfilefiname);
                   12443:   strcpy(optfileres,"vpl");
1.199     brouard  12444:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  12445:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  12446:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  12447:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  12448:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   12449: 
                   12450: } 
                   12451: 
1.136     brouard  12452: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   12453: {
1.126     brouard  12454: 
1.136     brouard  12455:   /*-------- data file ----------*/
                   12456:   FILE *fic;
                   12457:   char dummy[]="                         ";
1.359     brouard  12458:   int i = 0, j = 0, n = 0, iv = 0;/* , v;*/
1.223     brouard  12459:   int lstra;
1.136     brouard  12460:   int linei, month, year,iout;
1.302     brouard  12461:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  12462:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  12463:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  12464:   char *stratrunc;
1.223     brouard  12465: 
1.349     brouard  12466:   /* DummyV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
                   12467:   /* FixedV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
1.339     brouard  12468:   
                   12469:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
                   12470:   
1.136     brouard  12471:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  12472:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   12473:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  12474:   }
1.126     brouard  12475: 
1.302     brouard  12476:     /* Is it a BOM UTF-8 Windows file? */
                   12477:   /* First data line */
                   12478:   linei=0;
                   12479:   while(fgets(line, MAXLINE, fic)) {
                   12480:     noffset=0;
                   12481:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   12482:     {
                   12483:       noffset=noffset+3;
                   12484:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   12485:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   12486:       fflush(ficlog); return 1;
                   12487:     }
                   12488:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   12489:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   12490:     {
                   12491:       noffset=noffset+2;
1.304     brouard  12492:       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);
                   12493:       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  12494:       fflush(ficlog); return 1;
                   12495:     }
                   12496:     else if( line[0] == 0 && line[1] == 0)
                   12497:     {
                   12498:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   12499:        noffset=noffset+4;
1.304     brouard  12500:        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);
                   12501:        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  12502:        fflush(ficlog); return 1;
                   12503:       }
                   12504:     } else{
                   12505:       ;/*printf(" Not a BOM file\n");*/
                   12506:     }
                   12507:         /* If line starts with a # it is a comment */
                   12508:     if (line[noffset] == '#') {
                   12509:       linei=linei+1;
                   12510:       break;
                   12511:     }else{
                   12512:       break;
                   12513:     }
                   12514:   }
                   12515:   fclose(fic);
                   12516:   if((fic=fopen(datafile,"r"))==NULL)    {
                   12517:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   12518:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   12519:   }
                   12520:   /* Not a Bom file */
                   12521:   
1.136     brouard  12522:   i=1;
                   12523:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   12524:     linei=linei+1;
                   12525:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   12526:       if(line[j] == '\t')
                   12527:        line[j] = ' ';
                   12528:     }
                   12529:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   12530:       ;
                   12531:     };
                   12532:     line[j+1]=0;  /* Trims blanks at end of line */
                   12533:     if(line[0]=='#'){
                   12534:       fprintf(ficlog,"Comment line\n%s\n",line);
                   12535:       printf("Comment line\n%s\n",line);
                   12536:       continue;
                   12537:     }
                   12538:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  12539:     strcpy(line, linetmp);
1.223     brouard  12540:     
                   12541:     /* Loops on waves */
                   12542:     for (j=maxwav;j>=1;j--){
                   12543:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  12544:        cutv(stra, strb, line, ' '); 
                   12545:        if(strb[0]=='.') { /* Missing value */
                   12546:          lval=-1;
                   12547:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
1.341     brouard  12548:          cotvar[j][ncovcol+nqv+ntv+iv][i]=-1; /* For performance reasons */
1.238     brouard  12549:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   12550:            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);
                   12551:            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);
                   12552:            return 1;
                   12553:          }
                   12554:        }else{
                   12555:          errno=0;
                   12556:          /* what_kind_of_number(strb); */
                   12557:          dval=strtod(strb,&endptr); 
                   12558:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   12559:          /* if(strb != endptr && *endptr == '\0') */
                   12560:          /*    dval=dlval; */
                   12561:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   12562:          if( strb[0]=='\0' || (*endptr != '\0')){
                   12563:            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);
                   12564:            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);
                   12565:            return 1;
                   12566:          }
                   12567:          cotqvar[j][iv][i]=dval; 
1.341     brouard  12568:          cotvar[j][ncovcol+nqv+ntv+iv][i]=dval; /* because cotvar starts now at first ntv */ 
1.238     brouard  12569:        }
                   12570:        strcpy(line,stra);
1.223     brouard  12571:       }/* end loop ntqv */
1.225     brouard  12572:       
1.223     brouard  12573:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  12574:        cutv(stra, strb, line, ' '); 
                   12575:        if(strb[0]=='.') { /* Missing value */
                   12576:          lval=-1;
                   12577:        }else{
                   12578:          errno=0;
                   12579:          lval=strtol(strb,&endptr,10); 
                   12580:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   12581:          if( strb[0]=='\0' || (*endptr != '\0')){
                   12582:            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);
                   12583:            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);
                   12584:            return 1;
                   12585:          }
                   12586:        }
                   12587:        if(lval <-1 || lval >1){
                   12588:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  12589:  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  12590:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  12591:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   12592:  build V1=0 V2=0 for the reference value (1),\n                                \
                   12593:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  12594:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  12595:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  12596:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  12597:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  12598:  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  12599:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  12600:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   12601:  build V1=0 V2=0 for the reference value (1),\n                                \
                   12602:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  12603:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  12604:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  12605:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  12606:          return 1;
                   12607:        }
1.341     brouard  12608:        cotvar[j][ncovcol+nqv+iv][i]=(double)(lval);
1.238     brouard  12609:        strcpy(line,stra);
1.223     brouard  12610:       }/* end loop ntv */
1.225     brouard  12611:       
1.223     brouard  12612:       /* Statuses  at wave */
1.137     brouard  12613:       cutv(stra, strb, line, ' '); 
1.223     brouard  12614:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  12615:        lval=-1;
1.136     brouard  12616:       }else{
1.238     brouard  12617:        errno=0;
                   12618:        lval=strtol(strb,&endptr,10); 
                   12619:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
1.347     brouard  12620:        if( strb[0]=='\0' || (*endptr != '\0' )){
                   12621:          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);
                   12622:          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);
                   12623:          return 1;
                   12624:        }else if( lval==0 || lval > nlstate+ndeath){
1.348     brouard  12625:          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);
                   12626:          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  12627:          return 1;
                   12628:        }
1.136     brouard  12629:       }
1.225     brouard  12630:       
1.136     brouard  12631:       s[j][i]=lval;
1.225     brouard  12632:       
1.223     brouard  12633:       /* Date of Interview */
1.136     brouard  12634:       strcpy(line,stra);
                   12635:       cutv(stra, strb,line,' ');
1.169     brouard  12636:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  12637:       }
1.169     brouard  12638:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  12639:        month=99;
                   12640:        year=9999;
1.136     brouard  12641:       }else{
1.225     brouard  12642:        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);
                   12643:        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);
                   12644:        return 1;
1.136     brouard  12645:       }
                   12646:       anint[j][i]= (double) year; 
1.302     brouard  12647:       mint[j][i]= (double)month;
                   12648:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   12649:       /*       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]); */
                   12650:       /*       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]); */
                   12651:       /* } */
1.136     brouard  12652:       strcpy(line,stra);
1.223     brouard  12653:     } /* End loop on waves */
1.225     brouard  12654:     
1.223     brouard  12655:     /* Date of death */
1.136     brouard  12656:     cutv(stra, strb,line,' '); 
1.169     brouard  12657:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  12658:     }
1.169     brouard  12659:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  12660:       month=99;
                   12661:       year=9999;
                   12662:     }else{
1.141     brouard  12663:       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  12664:       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);
                   12665:       return 1;
1.136     brouard  12666:     }
                   12667:     andc[i]=(double) year; 
                   12668:     moisdc[i]=(double) month; 
                   12669:     strcpy(line,stra);
                   12670:     
1.223     brouard  12671:     /* Date of birth */
1.136     brouard  12672:     cutv(stra, strb,line,' '); 
1.169     brouard  12673:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  12674:     }
1.169     brouard  12675:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  12676:       month=99;
                   12677:       year=9999;
                   12678:     }else{
1.141     brouard  12679:       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);
                   12680:       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  12681:       return 1;
1.136     brouard  12682:     }
                   12683:     if (year==9999) {
1.141     brouard  12684:       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);
                   12685:       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  12686:       return 1;
                   12687:       
1.136     brouard  12688:     }
                   12689:     annais[i]=(double)(year);
1.302     brouard  12690:     moisnais[i]=(double)(month);
                   12691:     for (j=1;j<=maxwav;j++){
                   12692:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   12693:        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]);
                   12694:        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]);
                   12695:       }
                   12696:     }
                   12697: 
1.136     brouard  12698:     strcpy(line,stra);
1.225     brouard  12699:     
1.223     brouard  12700:     /* Sample weight */
1.136     brouard  12701:     cutv(stra, strb,line,' '); 
                   12702:     errno=0;
                   12703:     dval=strtod(strb,&endptr); 
                   12704:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  12705:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   12706:       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  12707:       fflush(ficlog);
                   12708:       return 1;
                   12709:     }
                   12710:     weight[i]=dval; 
                   12711:     strcpy(line,stra);
1.225     brouard  12712:     
1.223     brouard  12713:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   12714:       cutv(stra, strb, line, ' '); 
                   12715:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  12716:        lval=-1;
1.311     brouard  12717:        coqvar[iv][i]=NAN; 
                   12718:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  12719:       }else{
1.225     brouard  12720:        errno=0;
                   12721:        /* what_kind_of_number(strb); */
                   12722:        dval=strtod(strb,&endptr);
                   12723:        /* if(strb != endptr && *endptr == '\0') */
                   12724:        /*   dval=dlval; */
                   12725:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   12726:        if( strb[0]=='\0' || (*endptr != '\0')){
                   12727:          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);
                   12728:          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);
                   12729:          return 1;
                   12730:        }
                   12731:        coqvar[iv][i]=dval; 
1.226     brouard  12732:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  12733:       }
                   12734:       strcpy(line,stra);
                   12735:     }/* end loop nqv */
1.136     brouard  12736:     
1.223     brouard  12737:     /* Covariate values */
1.136     brouard  12738:     for (j=ncovcol;j>=1;j--){
                   12739:       cutv(stra, strb,line,' '); 
1.223     brouard  12740:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  12741:        lval=-1;
1.136     brouard  12742:       }else{
1.225     brouard  12743:        errno=0;
                   12744:        lval=strtol(strb,&endptr,10); 
                   12745:        if( strb[0]=='\0' || (*endptr != '\0')){
                   12746:          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);
                   12747:          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);
                   12748:          return 1;
                   12749:        }
1.136     brouard  12750:       }
                   12751:       if(lval <-1 || lval >1){
1.225     brouard  12752:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  12753:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   12754:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  12755:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   12756:  build V1=0 V2=0 for the reference value (1),\n                                \
                   12757:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  12758:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  12759:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  12760:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  12761:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  12762:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   12763:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  12764:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   12765:  build V1=0 V2=0 for the reference value (1),\n                                \
                   12766:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  12767:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  12768:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  12769:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  12770:        return 1;
1.136     brouard  12771:       }
                   12772:       covar[j][i]=(double)(lval);
                   12773:       strcpy(line,stra);
                   12774:     }  
                   12775:     lstra=strlen(stra);
1.225     brouard  12776:     
1.136     brouard  12777:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   12778:       stratrunc = &(stra[lstra-9]);
                   12779:       num[i]=atol(stratrunc);
                   12780:     }
                   12781:     else
                   12782:       num[i]=atol(stra);
                   12783:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   12784:       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;}*/
                   12785:     
                   12786:     i=i+1;
                   12787:   } /* End loop reading  data */
1.225     brouard  12788:   
1.136     brouard  12789:   *imax=i-1; /* Number of individuals */
                   12790:   fclose(fic);
1.225     brouard  12791:   
1.136     brouard  12792:   return (0);
1.164     brouard  12793:   /* endread: */
1.225     brouard  12794:   printf("Exiting readdata: ");
                   12795:   fclose(fic);
                   12796:   return (1);
1.223     brouard  12797: }
1.126     brouard  12798: 
1.234     brouard  12799: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  12800:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  12801:   while (*p2 == ' ')
1.234     brouard  12802:     p2++; 
                   12803:   /* while ((*p1++ = *p2++) !=0) */
                   12804:   /*   ; */
                   12805:   /* do */
                   12806:   /*   while (*p2 == ' ') */
                   12807:   /*     p2++; */
                   12808:   /* while (*p1++ == *p2++); */
                   12809:   *stri=p2; 
1.145     brouard  12810: }
                   12811: 
1.330     brouard  12812: int decoderesult( char resultline[], int nres)
1.230     brouard  12813: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   12814: {
1.235     brouard  12815:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  12816:   char resultsav[MAXLINE];
1.330     brouard  12817:   /* int resultmodel[MAXLINE]; */
1.334     brouard  12818:   /* int modelresult[MAXLINE]; */
1.230     brouard  12819:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   12820: 
1.234     brouard  12821:   removefirstspace(&resultline);
1.332     brouard  12822:   printf("decoderesult:%s\n",resultline);
1.230     brouard  12823: 
1.332     brouard  12824:   strcpy(resultsav,resultline);
1.342     brouard  12825:   /* printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline); */
1.230     brouard  12826:   if (strlen(resultsav) >1){
1.334     brouard  12827:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  12828:   }
1.353     brouard  12829:   if(j == 0 && cptcovs== 0){ /* Resultline but no =  and no covariate in the model */
1.253     brouard  12830:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   12831:     return (0);
                   12832:   }
1.234     brouard  12833:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.353     brouard  12834:     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);
                   12835:     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);
                   12836:     if(j==0)
                   12837:       return 1;
1.234     brouard  12838:   }
1.334     brouard  12839:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  12840:     if(nbocc(resultsav,'=') >1){
1.318     brouard  12841:       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  12842:       /* 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  12843:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  12844:       /* If a blank, then strc="V4=" and strd='\0' */
                   12845:       if(strc[0]=='\0'){
                   12846:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   12847:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   12848:        return 1;
                   12849:       }
1.234     brouard  12850:     }else
                   12851:       cutl(strc,strd,resultsav,'=');
1.318     brouard  12852:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  12853:     
1.230     brouard  12854:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  12855:     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  12856:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   12857:     /* cptcovsel++;     */
                   12858:     if (nbocc(stra,'=') >0)
                   12859:       strcpy(resultsav,stra); /* and analyzes it */
                   12860:   }
1.235     brouard  12861:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  12862:   /* 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  12863:   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  12864:     if(Typevar[k1]==0){ /* Single covariate in model */
                   12865:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  12866:       match=0;
1.318     brouard  12867:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   12868:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  12869:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  12870:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  12871:          break;
                   12872:        }
                   12873:       }
                   12874:       if(match == 0){
1.338     brouard  12875:        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]);
                   12876:        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  12877:        return 1;
1.234     brouard  12878:       }
1.332     brouard  12879:     }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*/
                   12880:       /* We feed resultmodel[k1]=k2; */
                   12881:       match=0;
                   12882:       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 */
                   12883:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  12884:          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  12885:          resultmodel[nres][k1]=k2; /* Added here */
1.342     brouard  12886:          /* printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]); */
1.332     brouard  12887:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   12888:          break;
                   12889:        }
                   12890:       }
                   12891:       if(match == 0){
1.338     brouard  12892:        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]);
                   12893:        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  12894:       return 1;
                   12895:       }
1.349     brouard  12896:     }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  12897:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   12898:       match=0;
1.342     brouard  12899:       /* 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  12900:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   12901:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   12902:          /* modelresult[k2]=k1; */
1.342     brouard  12903:          /* printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]); */
1.332     brouard  12904:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   12905:        }
                   12906:       }
                   12907:       if(match == 0){
1.349     brouard  12908:        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);
                   12909:        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  12910:        return 1;
                   12911:       }
                   12912:       match=0;
                   12913:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   12914:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   12915:          /* modelresult[k2]=k1;*/
1.342     brouard  12916:          /* printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]); */
1.332     brouard  12917:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   12918:          break;
                   12919:        }
                   12920:       }
                   12921:       if(match == 0){
1.349     brouard  12922:        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);
                   12923:        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  12924:        return 1;
                   12925:       }
                   12926:     }/* End of testing */
1.333     brouard  12927:   }/* End loop cptcovt */
1.235     brouard  12928:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  12929:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  12930:   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)
                   12931:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  12932:     match=0;
1.318     brouard  12933:     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  12934:       if(Typevar[k1]==0){ /* Single only */
1.349     brouard  12935:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4  What if a product?  */
1.330     brouard  12936:          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  12937:          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  12938:          ++match;
                   12939:        }
                   12940:       }
                   12941:     }
                   12942:     if(match == 0){
1.338     brouard  12943:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   12944:       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  12945:       return 1;
1.234     brouard  12946:     }else if(match > 1){
1.338     brouard  12947:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   12948:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
1.310     brouard  12949:       return 1;
1.234     brouard  12950:     }
                   12951:   }
1.334     brouard  12952:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  12953:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  12954:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  12955:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   12956:   /* 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*/
                   12957:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  12958:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   12959:   /*    1 0 0 0 */
                   12960:   /*    2 1 0 0 */
                   12961:   /*    3 0 1 0 */ 
1.330     brouard  12962:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  12963:   /*    5 0 0 1 */
1.330     brouard  12964:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  12965:   /*    7 0 1 1 */
                   12966:   /*    8 1 1 1 */
1.237     brouard  12967:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   12968:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   12969:   /* V5*age V5 known which value for nres?  */
                   12970:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  12971:   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.
                   12972:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  12973:     /* k counting number of combination of single dummies in the equation model */
                   12974:     /* k4 counting single dummies in the equation model */
                   12975:     /* k4q counting single quantitatives in the equation model */
1.344     brouard  12976:     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  12977:        /* 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  12978:       /* 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  12979:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  12980:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   12981:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   12982:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   12983:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   12984:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  12985:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  12986:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  12987:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  12988:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   12989:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   12990:       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  12991:       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  12992:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  12993:       /* Tinvresult[nres][4]=1 */
1.334     brouard  12994:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   12995:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   12996:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   12997:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  12998:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  12999:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.342     brouard  13000:       /* 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  13001:       k4++;;
1.331     brouard  13002:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  13003:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  13004:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  13005:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  13006:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   13007:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   13008:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  13009:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   13010:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   13011:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   13012:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   13013:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   13014:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  13015:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  13016:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  13017:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  13018:       /* 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  13019:       k4q++;;
1.350     brouard  13020:     }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"*/
                   13021:       /* Tvar[k1]; */ /* Age variable */ /* 17 age*V6*V2 ?*/
1.332     brouard  13022:       /* Wrong we want the value of variable name Tvar[k1] */
1.350     brouard  13023:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   13024:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   13025:       /* 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]]); */
                   13026:       }else{
                   13027:        k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   13028:        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)*/
                   13029:        TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
                   13030:        precov[nres][k1]=Tvalsel[k3];
                   13031:       }
1.342     brouard  13032:       /* 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  13033:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.350     brouard  13034:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   13035:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   13036:       /* 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]]); */
                   13037:       }else{
                   13038:        k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
                   13039:        k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
                   13040:        TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
                   13041:        precov[nres][k1]=Tvalsel[k3q];
                   13042:       }
1.342     brouard  13043:       /* 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  13044:     }else if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
1.332     brouard  13045:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
1.342     brouard  13046:       /* 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  13047:     }else{
1.332     brouard  13048:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   13049:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  13050:     }
                   13051:   }
1.234     brouard  13052:   
1.334     brouard  13053:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  13054:   return (0);
                   13055: }
1.235     brouard  13056: 
1.230     brouard  13057: int decodemodel( char model[], int lastobs)
                   13058:  /**< This routine decodes the model and returns:
1.224     brouard  13059:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   13060:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   13061:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   13062:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   13063:        * - cptcovage number of covariates with age*products =2
                   13064:        * - cptcovs number of simple covariates
1.339     brouard  13065:        * ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
1.224     brouard  13066:        * - 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  13067:        *     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
1.319     brouard  13068:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  13069:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   13070:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   13071:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   13072:        */
1.319     brouard  13073: /* 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  13074: {
1.359     brouard  13075:   int i, j, k, ks;/* , v;*/
1.349     brouard  13076:   int n,m;
                   13077:   int  j1, k1, k11, k12, k2, k3, k4;
                   13078:   char modelsav[300];
                   13079:   char stra[300], strb[300], strc[300], strd[300],stre[300],strf[300];
1.187     brouard  13080:   char *strpt;
1.349     brouard  13081:   int  **existcomb;
                   13082:   
                   13083:   existcomb=imatrix(1,NCOVMAX,1,NCOVMAX);
                   13084:   for(i=1;i<=NCOVMAX;i++)
                   13085:     for(j=1;j<=NCOVMAX;j++)
                   13086:       existcomb[i][j]=0;
                   13087:     
1.145     brouard  13088:   /*removespace(model);*/
1.136     brouard  13089:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.349     brouard  13090:     j=0, j1=0, k1=0, k12=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  13091:     if (strstr(model,"AGE") !=0){
1.192     brouard  13092:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   13093:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  13094:       return 1;
                   13095:     }
1.141     brouard  13096:     if (strstr(model,"v") !=0){
1.338     brouard  13097:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
                   13098:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
1.141     brouard  13099:       return 1;
                   13100:     }
1.187     brouard  13101:     strcpy(modelsav,model); 
                   13102:     if ((strpt=strstr(model,"age*age")) !=0){
1.338     brouard  13103:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
1.187     brouard  13104:       if(strpt != model){
1.338     brouard  13105:        printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  13106:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  13107:  corresponding column of parameters.\n",model);
1.338     brouard  13108:        fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  13109:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  13110:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  13111:        return 1;
1.225     brouard  13112:       }
1.187     brouard  13113:       nagesqr=1;
                   13114:       if (strstr(model,"+age*age") !=0)
1.234     brouard  13115:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  13116:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  13117:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  13118:       else 
1.234     brouard  13119:        substrchaine(modelsav, model, "age*age");
1.187     brouard  13120:     }else
                   13121:       nagesqr=0;
1.349     brouard  13122:     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  13123:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   13124:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.351     brouard  13125:       cptcovs=0; /**<  Number of simple covariates V1 +V1*age +V3 +V3*V4 +age*age => V1 + V3 =4+1-3=2  Wrong */
1.187     brouard  13126:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  13127:                     * cst, age and age*age 
                   13128:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   13129:       /* including age products which are counted in cptcovage.
                   13130:        * but the covariates which are products must be treated 
                   13131:        * separately: ncovn=4- 2=2 (V1+V3). */
1.349     brouard  13132:       cptcovprod=0; /**< Number of products  V1*V2 +v3*age = 2 */
                   13133:       cptcovdageprod=0; /* Number of doouble products with age age*Vn*VM or Vn*age*Vm or Vn*Vm*age */
1.187     brouard  13134:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.349     brouard  13135:       cptcovprodage=0;
                   13136:       /* cptcovprodage=nboccstr(modelsav,"age");*/
1.225     brouard  13137:       
1.187     brouard  13138:       /*   Design
                   13139:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   13140:        *  <          ncovcol=8                >
                   13141:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   13142:        *   k=  1    2      3       4     5       6      7        8
                   13143:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
1.345     brouard  13144:        *  covar[k,i], are for fixed covariates, value of kth covariate if not including age for individual i:
1.224     brouard  13145:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   13146:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  13147:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   13148:        *  Tage[++cptcovage]=k
1.345     brouard  13149:        *       if products, new covar are created after ncovcol + nqv (quanti fixed) with k1
1.187     brouard  13150:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   13151:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   13152:        *  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
                   13153:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   13154:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   13155:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
1.345     brouard  13156:        *  <          ncovcol=8  8 fixed covariate. Additional starts at 9 (V5*V6) and 10(V7*V8)              >
1.187     brouard  13157:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   13158:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
1.345     brouard  13159:        *     Tvard[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   13160:        * p Tvar[1]@12={2,   1,     3,      3,   9,     10,     8,       8}
1.187     brouard  13161:        * p Tprod[1]@2={                         6, 5}
                   13162:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   13163:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   13164:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  13165:        *How to reorganize? Tvars(orted)
1.187     brouard  13166:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   13167:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   13168:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   13169:        * Struct []
                   13170:        */
1.225     brouard  13171:       
1.187     brouard  13172:       /* This loop fills the array Tvar from the string 'model'.*/
                   13173:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   13174:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   13175:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   13176:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   13177:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   13178:       /*       k=1 Tvar[1]=2 (from V2) */
                   13179:       /*       k=5 Tvar[5] */
                   13180:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  13181:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  13182:       /*       } */
1.198     brouard  13183:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  13184:       /*
                   13185:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  13186:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   13187:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   13188:       }
1.187     brouard  13189:       cptcovage=0;
1.351     brouard  13190: 
                   13191:       /* First loop in order to calculate */
                   13192:       /* for age*VN*Vm
                   13193:        * Provides, Typevar[k], Tage[cptcovage], existcomb[n][m], FixedV[ncovcolt+k12]
                   13194:        * Tprod[k1]=k  Tposprod[k]=k1;    Tvard[k1][1] =m;
                   13195:       */
                   13196:       /* Needs  FixedV[Tvardk[k][1]] */
                   13197:       /* For others:
                   13198:        * Sets  Typevar[k];
                   13199:        * Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   13200:        *       Tposprod[k]=k11;
                   13201:        *       Tprod[k11]=k;
                   13202:        *       Tvardk[k][1] =m;
                   13203:        * Needs FixedV[Tvardk[k][1]] == 0
                   13204:       */
                   13205:       
1.319     brouard  13206:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   13207:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   13208:                                         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" */
                   13209:        if (nbocc(modelsav,'+')==0)
                   13210:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  13211:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   13212:        /*scanf("%d",i);*/
1.349     brouard  13213:        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 */
                   13214:          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  */
                   13215:          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   */
                   13216:            Typevar[k]=3;  /* 3 for age and double product age*Vn*Vm varying of fixed */
                   13217:             if(strstr(strc,"age")!=0) { /* It means that strc=V2*age or age*V2 and thus that strd=Vn */
                   13218:               cutl(stre,strf,strc,'*') ; /* strf=age or Vm, stre=Vm or age. If strc=V6*V2 then strf=V6 and stre=V2 */
                   13219:              strcpy(strc,strb); /* save strb(=age*Vn*Vm) into strc */
                   13220:              /* We want strb=Vn*Vm */
                   13221:               if(strcmp(strf,"age")==0){ /* strf is "age" so that stre=Vm =V2 . */
                   13222:                 strcpy(strb,strd);
                   13223:                 strcat(strb,"*");
                   13224:                 strcat(strb,stre);
                   13225:               }else{  /* strf=Vm  If strf=V6 then stre=V2 */
                   13226:                 strcpy(strb,strf);
                   13227:                 strcat(strb,"*");
                   13228:                 strcat(strb,stre);
                   13229:                 strcpy(strd,strb); /* in order for strd to not be "age"  for next test (will be Vn*Vm */
                   13230:               }
1.351     brouard  13231:              /* 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]]]); */
                   13232:              /* FixedV[Tvar[Tage[k]]]=0; /\* HERY not sure if V7*V4*age Fixed might not exist  yet*\/ */
1.349     brouard  13233:             }else{  /* strc=Vn*Vm (and strd=age) and should be strb=Vn*Vm but want to keep original strb double product  */
                   13234:              strcpy(stre,strb); /* save full b in stre */
                   13235:              strcpy(strb,strc); /* save short c in new short b for next block strb=Vn*Vm*/
                   13236:              strcpy(strf,strc); /* save short c in new short f */
                   13237:               cutl(strc,strd,strf,'*'); /* We get strd=Vn and strc=Vm for next block (strb=Vn*Vm)*/
                   13238:              /* strcpy(strc,stre);*/ /* save full e in c for future */
                   13239:             }
                   13240:             cptcovdageprod++; /* double product with age  Which product is it? */
                   13241:             /* 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 *\/ */
                   13242:             /* cutl(strc,strd,strb,'*'); /\* strd=  V6    or   V2     or    age and  strc=  V2 or    age or    V2 *\/ */
1.234     brouard  13243:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
1.349     brouard  13244:            n=atoi(stre);
1.234     brouard  13245:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.349     brouard  13246:            m=atoi(strc);
                   13247:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   13248:            Tage[cptcovage]=k; /* For age*V3*V2 gives the position in model of covariates associated with age Tage[1]=6 HERY too*/
                   13249:            if(existcomb[n][m] == 0){
                   13250:              /*  r /home/brouard/Documents/Recherches/REVES/Zachary/Zach-2022/Feinuo_Sun/Feinuo-threeway/femV12V15_3wayintNBe.imach */
                   13251:              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);
                   13252:              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);
                   13253:              fflush(ficlog);
                   13254:              k1++;  /* The combination Vn*Vm will be in the model so we create it at k1 */
                   13255:              k12++;
                   13256:              existcomb[n][m]=k1;
                   13257:              existcomb[m][n]=k1;
                   13258:              Tvar[k]=ncovcol+nqv+ntv+nqtv+k1;
                   13259:              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*/
                   13260:              Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 Gives the k1 double product  Vn*Vm or age*Vn*Vm at the k position */
                   13261:              Tvard[k1][1] =m; /* m 1 for V1*/
                   13262:              Tvardk[k][1] =m; /* m 1 for V1*/
                   13263:              Tvard[k1][2] =n; /* n 4 for V4*/
                   13264:              Tvardk[k][2] =n; /* n 4 for V4*/
1.351     brouard  13265: /*           Tvar[Tage[cptcovage]]=k1;*/ /* Tvar[6=age*V3*V2]=9 (new fixed covariate) */ /* We don't know about Fixed yet HERE */
1.349     brouard  13266:              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 */
                   13267:                for (i=1; i<=lastobs;i++){/* For fixed product */
                   13268:                  /* Computes the new covariate which is a product of
                   13269:                     covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   13270:                  covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   13271:                }
                   13272:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   13273:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   13274:                k12++;
                   13275:                FixedV[ncovcolt+k12]=0;
                   13276:              }else{ /*End of FixedV */
                   13277:                cptcovprodvage++; /* Counting the number of varying covariate with age */
                   13278:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   13279:                k12++;
                   13280:                FixedV[ncovcolt+k12]=1;
                   13281:              }
                   13282:            }else{  /* k1 Vn*Vm already exists */
                   13283:              k11=existcomb[n][m];
                   13284:              Tposprod[k]=k11; /* OK */
                   13285:              Tvar[k]=Tvar[Tprod[k11]]; /* HERY */
                   13286:              Tvardk[k][1]=m;
                   13287:              Tvardk[k][2]=n;
                   13288:              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 */
                   13289:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   13290:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   13291:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   13292:                Tvar[Tage[cptcovage]]=k1;
                   13293:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   13294:                k12++;
                   13295:                FixedV[ncovcolt+k12]=0;
                   13296:              }else{ /* Already exists but time varying (and age) */
                   13297:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   13298:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   13299:                /* Tvar[Tage[cptcovage]]=k1; */
                   13300:                cptcovprodvage++;
                   13301:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   13302:                k12++;
                   13303:                FixedV[ncovcolt+k12]=1;
                   13304:              }
                   13305:            }
                   13306:            /* Tage[cptcovage]=k;  /\*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   13307:            /* Tvar[k]=k11; /\* HERY *\/ */
                   13308:          } 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 */
                   13309:             cptcovprod++;
                   13310:             if (strcmp(strc,"age")==0) { /**< Model includes age: strb= Vn*age c=age d=Vn*/
                   13311:               /* covar is not filled and then is empty */
                   13312:               cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   13313:               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 */
                   13314:               Typevar[k]=1;  /* 1 for age product */
                   13315:               cptcovage++; /* Counts the number of covariates which include age as a product */
                   13316:               Tage[cptcovage]=k;  /*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   13317:              if( FixedV[Tvar[k]] == 0){
                   13318:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   13319:              }else{
                   13320:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
                   13321:              }
                   13322:               /*printf("stre=%s ", stre);*/
                   13323:             } else if (strcmp(strd,"age")==0) { /* strb= age*Vn c=Vn */
                   13324:               cutl(stre,strb,strc,'V');
                   13325:               Tvar[k]=atoi(stre);
                   13326:               Typevar[k]=1;  /* 1 for age product */
                   13327:               cptcovage++;
                   13328:               Tage[cptcovage]=k;
                   13329:              if( FixedV[Tvar[k]] == 0){
                   13330:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   13331:              }else{
                   13332:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
1.339     brouard  13333:              }
1.349     brouard  13334:             }else{ /*  for product Vn*Vm */
                   13335:              Typevar[k]=2;  /* 2 for product Vn*Vm */
                   13336:              cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   13337:              n=atoi(stre);
                   13338:              cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   13339:              m=atoi(strc);
                   13340:              k1++;
                   13341:              cptcovprodnoage++;
                   13342:              if(existcomb[n][m] != 0 || existcomb[m][n] != 0){
                   13343:                printf("Warning in model combination V%d*V%d already exists in the model in position k1=%d!\n",n,m,existcomb[n][m]);
                   13344:                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]);
                   13345:                fflush(ficlog);
                   13346:                k11=existcomb[n][m];
                   13347:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   13348:                Tposprod[k]=k11;
                   13349:                Tprod[k11]=k;
                   13350:                Tvardk[k][1] =m; /* m 1 for V1*/
                   13351:                /* Tvard[k11][1] =m; /\* n 4 for V4*\/ */
                   13352:                Tvardk[k][2] =n; /* n 4 for V4*/                
                   13353:                /* Tvard[k11][2] =n; /\* n 4 for V4*\/ */
                   13354:              }else{ /* combination Vn*Vm doesn't exist we create it (no age)*/
                   13355:                existcomb[n][m]=k1;
                   13356:                existcomb[m][n]=k1;
                   13357:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
                   13358:                                                    because this model-covariate is a construction we invent a new column
                   13359:                                                    which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   13360:                                                    If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
                   13361:                                                    thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
                   13362:                                                    Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
                   13363:                /* Please remark that the new variables are model dependent */
                   13364:                /* If we have 4 variable but the model uses only 3, like in
                   13365:                 * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   13366:                 *  k=     1     2      3   4     5        6        7       8
                   13367:                 * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   13368:                 * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   13369:                 * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   13370:                 */
                   13371:                /* We need to feed some variables like TvarVV, but later on next loop because of ncovv (k2) is not correct */
                   13372:                Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 +V6*V2*age  */
                   13373:                Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
                   13374:                Tvard[k1][1] =m; /* m 1 for V1*/
                   13375:                Tvardk[k][1] =m; /* m 1 for V1*/
                   13376:                Tvard[k1][2] =n; /* n 4 for V4*/
                   13377:                Tvardk[k][2] =n; /* n 4 for V4*/
                   13378:                k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   13379:                /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   13380:                /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
                   13381:                /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
                   13382:                /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   13383:                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 */
                   13384:                  for (i=1; i<=lastobs;i++){/* For fixed product */
                   13385:                    /* Computes the new covariate which is a product of
                   13386:                       covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   13387:                    covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   13388:                  }
                   13389:                  /* TvarVV[k2]=n; */
                   13390:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13391:                  /* TvarVV[k2+1]=m; */
                   13392:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13393:                }else{ /* not FixedV */
                   13394:                  /* TvarVV[k2]=n; */
                   13395:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13396:                  /* TvarVV[k2+1]=m; */
                   13397:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13398:                }                 
                   13399:              }  /* End of creation of Vn*Vm if not created by age*Vn*Vm earlier  */
                   13400:            } /*  End of product Vn*Vm */
                   13401:           } /* End of age*double product or simple product */
                   13402:        }else { /* not a product */
1.234     brouard  13403:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   13404:          /*  scanf("%d",i);*/
                   13405:          cutl(strd,strc,strb,'V');
                   13406:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   13407:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   13408:          Tvar[k]=atoi(strd);
                   13409:          Typevar[k]=0;  /* 0 for simple covariates */
                   13410:        }
                   13411:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  13412:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  13413:                                  scanf("%d",i);*/
1.187     brouard  13414:       } /* end of loop + on total covariates */
1.351     brouard  13415: 
                   13416:       
1.187     brouard  13417:     } /* end if strlen(modelsave == 0) age*age might exist */
                   13418:   } /* end if strlen(model == 0) */
1.349     brouard  13419:   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  */
                   13420: 
1.136     brouard  13421:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   13422:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  13423:   
1.136     brouard  13424:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  13425:      printf("cptcovprod=%d ", cptcovprod);
                   13426:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   13427:      scanf("%d ",i);*/
                   13428: 
                   13429: 
1.230     brouard  13430: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   13431:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  13432: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   13433:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   13434:    k =           1    2   3     4       5       6      7      8        9
                   13435:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  13436:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  13437:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   13438:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   13439:          Tmodelind[combination of covar]=k;
1.225     brouard  13440: */  
                   13441: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  13442:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  13443:   /* 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  13444:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  13445:   printf("Model=1+age+%s\n\
1.349     brouard  13446: 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  13447: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   13448: 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  13449:   fprintf(ficlog,"Model=1+age+%s\n\
1.349     brouard  13450: 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  13451: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   13452: 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  13453:   for(k=-1;k<=NCOVMAX; k++){ Fixed[k]=0; Dummy[k]=0;}
                   13454:   for(k=1;k<=NCOVMAX; k++){TvarFind[k]=0; TvarVind[k]=0;}
1.351     brouard  13455: 
                   13456: 
                   13457:   /* Second loop for calculating  Fixed[k], Dummy[k]*/
                   13458: 
                   13459:   
1.349     brouard  13460:   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  13461:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  13462:       Fixed[k]= 0;
                   13463:       Dummy[k]= 0;
1.225     brouard  13464:       ncoveff++;
1.232     brouard  13465:       ncovf++;
1.234     brouard  13466:       nsd++;
                   13467:       modell[k].maintype= FTYPE;
                   13468:       TvarsD[nsd]=Tvar[k];
                   13469:       TvarsDind[nsd]=k;
1.330     brouard  13470:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  13471:       TvarF[ncovf]=Tvar[k];
                   13472:       TvarFind[ncovf]=k;
                   13473:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   13474:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.339     brouard  13475:     /* }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  13476:     }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  13477:       Fixed[k]= 0;
                   13478:       Dummy[k]= 1;
1.230     brouard  13479:       nqfveff++;
1.234     brouard  13480:       modell[k].maintype= FTYPE;
                   13481:       modell[k].subtype= FQ;
                   13482:       nsq++;
1.334     brouard  13483:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   13484:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  13485:       ncovf++;
1.234     brouard  13486:       TvarF[ncovf]=Tvar[k];
                   13487:       TvarFind[ncovf]=k;
1.231     brouard  13488:       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  13489:       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  13490:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.339     brouard  13491:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   13492:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   13493:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   13494:       ncovvt++;
                   13495:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   13496:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
                   13497: 
1.227     brouard  13498:       Fixed[k]= 1;
                   13499:       Dummy[k]= 0;
1.225     brouard  13500:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  13501:       modell[k].maintype= VTYPE;
                   13502:       modell[k].subtype= VD;
                   13503:       nsd++;
                   13504:       TvarsD[nsd]=Tvar[k];
                   13505:       TvarsDind[nsd]=k;
1.330     brouard  13506:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  13507:       ncovv++; /* Only simple time varying variables */
                   13508:       TvarV[ncovv]=Tvar[k];
1.242     brouard  13509:       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  13510:       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 */
                   13511:       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  13512:       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);
                   13513:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  13514:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.339     brouard  13515:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   13516:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   13517:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   13518:       ncovvt++;
                   13519:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   13520:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   13521:       
1.234     brouard  13522:       Fixed[k]= 1;
                   13523:       Dummy[k]= 1;
                   13524:       nqtveff++;
                   13525:       modell[k].maintype= VTYPE;
                   13526:       modell[k].subtype= VQ;
                   13527:       ncovv++; /* Only simple time varying variables */
                   13528:       nsq++;
1.334     brouard  13529:       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) */
                   13530:       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  13531:       TvarV[ncovv]=Tvar[k];
1.242     brouard  13532:       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  13533:       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 */
                   13534:       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  13535:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   13536:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
1.349     brouard  13537:       /* 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  13538:       /* printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv); */
1.227     brouard  13539:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  13540:       ncova++;
                   13541:       TvarA[ncova]=Tvar[k];
                   13542:       TvarAind[ncova]=k;
1.349     brouard  13543:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   13544:       /** 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  13545:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  13546:        Fixed[k]= 2;
                   13547:        Dummy[k]= 2;
                   13548:        modell[k].maintype= ATYPE;
                   13549:        modell[k].subtype= APFD;
1.349     brouard  13550:        ncovta++;
                   13551:        TvarAVVA[ncovta]=Tvar[k]; /*  (2)age*V3 */
                   13552:        TvarAVVAind[ncovta]=k;
1.240     brouard  13553:        /* ncoveff++; */
1.227     brouard  13554:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  13555:        Fixed[k]= 2;
                   13556:        Dummy[k]= 3;
                   13557:        modell[k].maintype= ATYPE;
                   13558:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
1.349     brouard  13559:        ncovta++;
                   13560:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   13561:        TvarAVVAind[ncovta]=k;
1.240     brouard  13562:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  13563:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  13564:        Fixed[k]= 3;
                   13565:        Dummy[k]= 2;
                   13566:        modell[k].maintype= ATYPE;
                   13567:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
1.349     brouard  13568:        ncovva++;
                   13569:        TvarVVA[ncovva]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   13570:        TvarVVAind[ncovva]=k;
                   13571:        ncovta++;
                   13572:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   13573:        TvarAVVAind[ncovta]=k;
1.240     brouard  13574:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  13575:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  13576:        Fixed[k]= 3;
                   13577:        Dummy[k]= 3;
                   13578:        modell[k].maintype= ATYPE;
                   13579:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
1.349     brouard  13580:        ncovva++;
                   13581:        TvarVVA[ncovva]=Tvar[k]; /*   */
                   13582:        TvarVVAind[ncovva]=k;
                   13583:        ncovta++;
                   13584:        TvarAVVA[ncovta]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   13585:        TvarAVVAind[ncovta]=k;
1.240     brouard  13586:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  13587:       }
1.349     brouard  13588:     }else if( Tposprod[k]>0  &&  Typevar[k]==2){  /* Detects if fixed product no age Vm*Vn */
                   13589:       printf("MEMORY ERRORR k=%d  Tposprod[k]=%d, Typevar[k]=%d\n ",k, Tposprod[k], Typevar[k]);
                   13590:       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 */
                   13591:       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]]);
                   13592:        Fixed[k]= 0;
                   13593:        Dummy[k]= 0;
                   13594:        ncoveff++;
                   13595:        ncovf++;
                   13596:        /* ncovv++; */
                   13597:        /* TvarVV[ncovv]=Tvardk[k][1]; */
                   13598:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13599:        /* ncovv++; */
                   13600:        /* TvarVV[ncovv]=Tvardk[k][2]; */
                   13601:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13602:        modell[k].maintype= FTYPE;
                   13603:        TvarF[ncovf]=Tvar[k];
                   13604:        /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
                   13605:        TvarFind[ncovf]=k;
                   13606:        TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   13607:        TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   13608:       }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  */
                   13609:        /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   13610:        /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   13611:        /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   13612:        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 */
                   13613:        ncovvt++;
                   13614:        TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   13615:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   13616:        ncovvt++;
                   13617:        TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   13618:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   13619:        
                   13620:        /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   13621:        /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   13622:        
                   13623:        if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   13624:          if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
                   13625:            Fixed[k]= 1;
                   13626:            Dummy[k]= 0;
                   13627:            modell[k].maintype= FTYPE;
                   13628:            modell[k].subtype= FPDD;            /*      Product fixed dummy * fixed dummy */
                   13629:            ncovf++; /* Fixed variables without age */
                   13630:            TvarF[ncovf]=Tvar[k];
                   13631:            TvarFind[ncovf]=k;
                   13632:          }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
                   13633:            Fixed[k]= 0;  /* Fixed product */
                   13634:            Dummy[k]= 1;
                   13635:            modell[k].maintype= FTYPE;
                   13636:            modell[k].subtype= FPDQ;            /*      Product fixed dummy * fixed quantitative */
                   13637:            ncovf++; /* Varying variables without age */
                   13638:            TvarF[ncovf]=Tvar[k];
                   13639:            TvarFind[ncovf]=k;
                   13640:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
                   13641:            Fixed[k]= 1;
                   13642:            Dummy[k]= 0;
                   13643:            modell[k].maintype= VTYPE;
                   13644:            modell[k].subtype= VPDD;            /*      Product fixed dummy * varying dummy */
                   13645:            ncovv++; /* Varying variables without age */
                   13646:            TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   13647:            TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
                   13648:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
                   13649:            Fixed[k]= 1;
                   13650:            Dummy[k]= 1;
                   13651:            modell[k].maintype= VTYPE;
                   13652:            modell[k].subtype= VPDQ;            /*      Product fixed dummy * varying quantitative */
                   13653:            ncovv++; /* Varying variables without age */
                   13654:            TvarV[ncovv]=Tvar[k];
                   13655:            TvarVind[ncovv]=k;
                   13656:          }
                   13657:        }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   13658:          if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
                   13659:            Fixed[k]= 0;  /*  Fixed product */
                   13660:            Dummy[k]= 1;
                   13661:            modell[k].maintype= FTYPE;
                   13662:            modell[k].subtype= FPDQ;            /*      Product fixed quantitative * fixed dummy */
                   13663:            ncovf++; /* Fixed variables without age */
                   13664:            TvarF[ncovf]=Tvar[k];
                   13665:            TvarFind[ncovf]=k;
                   13666:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
                   13667:            Fixed[k]= 1;
                   13668:            Dummy[k]= 1;
                   13669:            modell[k].maintype= VTYPE;
                   13670:            modell[k].subtype= VPDQ;            /*      Product fixed quantitative * varying dummy */
                   13671:            ncovv++; /* Varying variables without age */
                   13672:            TvarV[ncovv]=Tvar[k];
                   13673:            TvarVind[ncovv]=k;
                   13674:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
                   13675:            Fixed[k]= 1;
                   13676:            Dummy[k]= 1;
                   13677:            modell[k].maintype= VTYPE;
                   13678:            modell[k].subtype= VPQQ;            /*      Product fixed quantitative * varying quantitative */
                   13679:            ncovv++; /* Varying variables without age */
                   13680:            TvarV[ncovv]=Tvar[k];
                   13681:            TvarVind[ncovv]=k;
                   13682:            ncovv++; /* Varying variables without age */
                   13683:            TvarV[ncovv]=Tvar[k];
                   13684:            TvarVind[ncovv]=k;
                   13685:          }
                   13686:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
                   13687:          if(Tvard[k1][2] <=ncovcol){
                   13688:            Fixed[k]= 1;
                   13689:            Dummy[k]= 1;
                   13690:            modell[k].maintype= VTYPE;
                   13691:            modell[k].subtype= VPDD;            /*      Product time varying dummy * fixed dummy */
                   13692:            ncovv++; /* Varying variables without age */
                   13693:            TvarV[ncovv]=Tvar[k];
                   13694:            TvarVind[ncovv]=k;
                   13695:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   13696:            Fixed[k]= 1;
                   13697:            Dummy[k]= 1;
                   13698:            modell[k].maintype= VTYPE;
                   13699:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * fixed quantitative */
                   13700:            ncovv++; /* Varying variables without age */
                   13701:            TvarV[ncovv]=Tvar[k];
                   13702:            TvarVind[ncovv]=k;
                   13703:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   13704:            Fixed[k]= 1;
                   13705:            Dummy[k]= 0;
                   13706:            modell[k].maintype= VTYPE;
                   13707:            modell[k].subtype= VPDD;            /*      Product time varying dummy * time varying dummy */
                   13708:            ncovv++; /* Varying variables without age */
                   13709:            TvarV[ncovv]=Tvar[k];
                   13710:            TvarVind[ncovv]=k;
                   13711:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   13712:            Fixed[k]= 1;
                   13713:            Dummy[k]= 1;
                   13714:            modell[k].maintype= VTYPE;
                   13715:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * time varying quantitative */
                   13716:            ncovv++; /* Varying variables without age */
                   13717:            TvarV[ncovv]=Tvar[k];
                   13718:            TvarVind[ncovv]=k;
                   13719:          }
                   13720:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
                   13721:          if(Tvard[k1][2] <=ncovcol){
                   13722:            Fixed[k]= 1;
                   13723:            Dummy[k]= 1;
                   13724:            modell[k].maintype= VTYPE;
                   13725:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * fixed dummy */
                   13726:            ncovv++; /* Varying variables without age */
                   13727:            TvarV[ncovv]=Tvar[k];
                   13728:            TvarVind[ncovv]=k;
                   13729:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   13730:            Fixed[k]= 1;
                   13731:            Dummy[k]= 1;
                   13732:            modell[k].maintype= VTYPE;
                   13733:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * fixed quantitative */
                   13734:            ncovv++; /* Varying variables without age */
                   13735:            TvarV[ncovv]=Tvar[k];
                   13736:            TvarVind[ncovv]=k;
                   13737:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   13738:            Fixed[k]= 1;
                   13739:            Dummy[k]= 1;
                   13740:            modell[k].maintype= VTYPE;
                   13741:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * time varying dummy */
                   13742:            ncovv++; /* Varying variables without age */
                   13743:            TvarV[ncovv]=Tvar[k];
                   13744:            TvarVind[ncovv]=k;
                   13745:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   13746:            Fixed[k]= 1;
                   13747:            Dummy[k]= 1;
                   13748:            modell[k].maintype= VTYPE;
                   13749:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * time varying quantitative */
                   13750:            ncovv++; /* Varying variables without age */
                   13751:            TvarV[ncovv]=Tvar[k];
                   13752:            TvarVind[ncovv]=k;
                   13753:          }
                   13754:        }else{
                   13755:          printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   13756:          fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   13757:        } /*end k1*/
                   13758:       }
                   13759:     }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  13760:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  13761:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   13762:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   13763:       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 */
                   13764:       ncova++;
                   13765:       TvarA[ncova]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   13766:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   13767:       ncova++;
                   13768:       TvarA[ncova]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   13769:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
1.339     brouard  13770: 
1.349     brouard  13771:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   13772:       /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   13773:       if( FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){
                   13774:        ncovta++;
                   13775:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   13776:        TvarAVVAind[ncovta]=k;
                   13777:        ncovta++;
                   13778:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   13779:        TvarAVVAind[ncovta]=k;
                   13780:       }else{
                   13781:        ncovva++;  /* HERY  reached */
                   13782:        TvarVVA[ncovva]=Tvard[k1][1]; /*  age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4  */
                   13783:        TvarVVAind[ncovva]=k;
                   13784:        ncovva++;
                   13785:        TvarVVA[ncovva]=Tvard[k1][2]; /*   */
                   13786:        TvarVVAind[ncovva]=k;
                   13787:        ncovta++;
                   13788:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   13789:        TvarAVVAind[ncovta]=k;
                   13790:        ncovta++;
                   13791:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   13792:        TvarAVVAind[ncovta]=k;
                   13793:       }
1.339     brouard  13794:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   13795:        if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
1.349     brouard  13796:          Fixed[k]= 2;
                   13797:          Dummy[k]= 2;
1.240     brouard  13798:          modell[k].maintype= FTYPE;
                   13799:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
1.349     brouard  13800:          /* TvarF[ncova]=Tvar[k];   /\* Problem to solve *\/ */
                   13801:          /* TvarFind[ncova]=k; */
1.339     brouard  13802:        }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
1.349     brouard  13803:          Fixed[k]= 2;  /* Fixed product */
                   13804:          Dummy[k]= 3;
1.240     brouard  13805:          modell[k].maintype= FTYPE;
                   13806:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
1.349     brouard  13807:          /* TvarF[ncova]=Tvar[k]; */
                   13808:          /* TvarFind[ncova]=k; */
1.339     brouard  13809:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
1.349     brouard  13810:          Fixed[k]= 3;
                   13811:          Dummy[k]= 2;
1.240     brouard  13812:          modell[k].maintype= VTYPE;
                   13813:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
1.349     brouard  13814:          TvarV[ncova]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   13815:          TvarVind[ncova]=k;/* TvarVind[1]=5 */ 
1.339     brouard  13816:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
1.349     brouard  13817:          Fixed[k]= 3;
                   13818:          Dummy[k]= 3;
1.240     brouard  13819:          modell[k].maintype= VTYPE;
                   13820:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
1.349     brouard  13821:          /* ncovv++; /\* Varying variables without age *\/ */
                   13822:          /* TvarV[ncovv]=Tvar[k]; */
                   13823:          /* TvarVind[ncovv]=k; */
1.240     brouard  13824:        }
1.339     brouard  13825:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   13826:        if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
1.349     brouard  13827:          Fixed[k]= 2;  /*  Fixed product */
                   13828:          Dummy[k]= 2;
1.240     brouard  13829:          modell[k].maintype= FTYPE;
                   13830:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
1.349     brouard  13831:          /* ncova++; /\* Fixed variables with age *\/ */
                   13832:          /* TvarF[ncovf]=Tvar[k]; */
                   13833:          /* TvarFind[ncovf]=k; */
1.339     brouard  13834:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
1.349     brouard  13835:          Fixed[k]= 2;
                   13836:          Dummy[k]= 3;
1.240     brouard  13837:          modell[k].maintype= VTYPE;
                   13838:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
1.349     brouard  13839:          /* ncova++; /\* Varying variables with age *\/ */
                   13840:          /* TvarV[ncova]=Tvar[k]; */
                   13841:          /* TvarVind[ncova]=k; */
1.339     brouard  13842:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
1.349     brouard  13843:          Fixed[k]= 3;
                   13844:          Dummy[k]= 2;
1.240     brouard  13845:          modell[k].maintype= VTYPE;
                   13846:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
1.349     brouard  13847:          ncova++; /* Varying variables without age */
                   13848:          TvarV[ncova]=Tvar[k];
                   13849:          TvarVind[ncova]=k;
                   13850:          /* ncova++; /\* Varying variables without age *\/ */
                   13851:          /* TvarV[ncova]=Tvar[k]; */
                   13852:          /* TvarVind[ncova]=k; */
1.240     brouard  13853:        }
1.339     brouard  13854:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
1.240     brouard  13855:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  13856:          Fixed[k]= 2;
                   13857:          Dummy[k]= 2;
1.240     brouard  13858:          modell[k].maintype= VTYPE;
                   13859:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
1.349     brouard  13860:          /* ncova++; /\* Varying variables with age *\/ */
                   13861:          /* TvarV[ncova]=Tvar[k]; */
                   13862:          /* TvarVind[ncova]=k; */
1.240     brouard  13863:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  13864:          Fixed[k]= 2;
                   13865:          Dummy[k]= 3;
1.240     brouard  13866:          modell[k].maintype= VTYPE;
                   13867:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
1.349     brouard  13868:          /* ncova++; /\* Varying variables with age *\/ */
                   13869:          /* TvarV[ncova]=Tvar[k]; */
                   13870:          /* TvarVind[ncova]=k; */
1.240     brouard  13871:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349     brouard  13872:          Fixed[k]= 3;
                   13873:          Dummy[k]= 2;
1.240     brouard  13874:          modell[k].maintype= VTYPE;
                   13875:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
1.349     brouard  13876:          /* ncova++; /\* Varying variables with age *\/ */
                   13877:          /* TvarV[ncova]=Tvar[k]; */
                   13878:          /* TvarVind[ncova]=k; */
1.240     brouard  13879:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  13880:          Fixed[k]= 3;
                   13881:          Dummy[k]= 3;
1.240     brouard  13882:          modell[k].maintype= VTYPE;
                   13883:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
1.349     brouard  13884:          /* ncova++; /\* Varying variables with age *\/ */
                   13885:          /* TvarV[ncova]=Tvar[k]; */
                   13886:          /* TvarVind[ncova]=k; */
1.240     brouard  13887:        }
1.339     brouard  13888:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
1.240     brouard  13889:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  13890:          Fixed[k]= 2;
                   13891:          Dummy[k]= 2;
1.240     brouard  13892:          modell[k].maintype= VTYPE;
                   13893:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
1.349     brouard  13894:          /* ncova++; /\* Varying variables with age *\/ */
                   13895:          /* TvarV[ncova]=Tvar[k]; */
                   13896:          /* TvarVind[ncova]=k; */
1.240     brouard  13897:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  13898:          Fixed[k]= 2;
                   13899:          Dummy[k]= 3;
1.240     brouard  13900:          modell[k].maintype= VTYPE;
                   13901:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
1.349     brouard  13902:          /* ncova++; /\* Varying variables with age *\/ */
                   13903:          /* TvarV[ncova]=Tvar[k]; */
                   13904:          /* TvarVind[ncova]=k; */
1.240     brouard  13905:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349     brouard  13906:          Fixed[k]= 3;
                   13907:          Dummy[k]= 2;
1.240     brouard  13908:          modell[k].maintype= VTYPE;
                   13909:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
1.349     brouard  13910:          /* ncova++; /\* Varying variables with age *\/ */
                   13911:          /* TvarV[ncova]=Tvar[k]; */
                   13912:          /* TvarVind[ncova]=k; */
1.240     brouard  13913:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  13914:          Fixed[k]= 3;
                   13915:          Dummy[k]= 3;
1.240     brouard  13916:          modell[k].maintype= VTYPE;
                   13917:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
1.349     brouard  13918:          /* ncova++; /\* Varying variables with age *\/ */
                   13919:          /* TvarV[ncova]=Tvar[k]; */
                   13920:          /* TvarVind[ncova]=k; */
1.240     brouard  13921:        }
1.227     brouard  13922:       }else{
1.240     brouard  13923:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   13924:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   13925:       } /*end k1*/
1.349     brouard  13926:     } else{
1.226     brouard  13927:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   13928:       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  13929:     }
1.342     brouard  13930:     /* 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]); */
                   13931:     /* printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype); */
1.227     brouard  13932:     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]);
                   13933:   }
1.349     brouard  13934:   ncovvta=ncovva;
1.227     brouard  13935:   /* Searching for doublons in the model */
                   13936:   for(k1=1; k1<= cptcovt;k1++){
                   13937:     for(k2=1; k2 <k1;k2++){
1.285     brouard  13938:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   13939:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  13940:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   13941:          if(Tvar[k1]==Tvar[k2]){
1.338     brouard  13942:            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]);
                   13943:            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  13944:            return(1);
                   13945:          }
                   13946:        }else if (Typevar[k1] ==2){
                   13947:          k3=Tposprod[k1];
                   13948:          k4=Tposprod[k2];
                   13949:          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  13950:            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]]);
                   13951:            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  13952:            return(1);
                   13953:          }
                   13954:        }
1.227     brouard  13955:       }
                   13956:     }
1.225     brouard  13957:   }
                   13958:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   13959:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  13960:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   13961:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.349     brouard  13962: 
                   13963:   free_imatrix(existcomb,1,NCOVMAX,1,NCOVMAX);
1.137     brouard  13964:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  13965:   /*endread:*/
1.225     brouard  13966:   printf("Exiting decodemodel: ");
                   13967:   return (1);
1.136     brouard  13968: }
                   13969: 
1.169     brouard  13970: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  13971: {/* Check ages at death */
1.136     brouard  13972:   int i, m;
1.218     brouard  13973:   int firstone=0;
                   13974:   
1.136     brouard  13975:   for (i=1; i<=imx; i++) {
                   13976:     for(m=2; (m<= maxwav); m++) {
                   13977:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   13978:        anint[m][i]=9999;
1.216     brouard  13979:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   13980:          s[m][i]=-1;
1.136     brouard  13981:       }
                   13982:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  13983:        *nberr = *nberr + 1;
1.218     brouard  13984:        if(firstone == 0){
                   13985:          firstone=1;
1.260     brouard  13986:        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  13987:        }
1.262     brouard  13988:        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  13989:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  13990:       }
                   13991:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  13992:        (*nberr)++;
1.259     brouard  13993:        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  13994:        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  13995:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  13996:       }
                   13997:     }
                   13998:   }
                   13999: 
                   14000:   for (i=1; i<=imx; i++)  {
                   14001:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   14002:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  14003:       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  14004:        if (s[m][i] >= nlstate+1) {
1.169     brouard  14005:          if(agedc[i]>0){
                   14006:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  14007:              agev[m][i]=agedc[i];
1.214     brouard  14008:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  14009:            }else {
1.136     brouard  14010:              if ((int)andc[i]!=9999){
                   14011:                nbwarn++;
                   14012:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   14013:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   14014:                agev[m][i]=-1;
                   14015:              }
                   14016:            }
1.169     brouard  14017:          } /* agedc > 0 */
1.214     brouard  14018:        } /* end if */
1.136     brouard  14019:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   14020:                                 years but with the precision of a month */
                   14021:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   14022:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   14023:            agev[m][i]=1;
                   14024:          else if(agev[m][i] < *agemin){ 
                   14025:            *agemin=agev[m][i];
                   14026:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   14027:          }
                   14028:          else if(agev[m][i] >*agemax){
                   14029:            *agemax=agev[m][i];
1.156     brouard  14030:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  14031:          }
                   14032:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   14033:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  14034:        } /* en if 9*/
1.136     brouard  14035:        else { /* =9 */
1.214     brouard  14036:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  14037:          agev[m][i]=1;
                   14038:          s[m][i]=-1;
                   14039:        }
                   14040:       }
1.214     brouard  14041:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  14042:        agev[m][i]=1;
1.214     brouard  14043:       else{
                   14044:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   14045:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   14046:        agev[m][i]=0;
                   14047:       }
                   14048:     } /* End for lastpass */
                   14049:   }
1.136     brouard  14050:     
                   14051:   for (i=1; i<=imx; i++)  {
                   14052:     for(m=firstpass; (m<=lastpass); m++){
                   14053:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  14054:        (*nberr)++;
1.136     brouard  14055:        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);     
                   14056:        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);     
                   14057:        return 1;
                   14058:       }
                   14059:     }
                   14060:   }
                   14061: 
                   14062:   /*for (i=1; i<=imx; i++){
                   14063:   for (m=firstpass; (m<lastpass); m++){
                   14064:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   14065: }
                   14066: 
                   14067: }*/
                   14068: 
                   14069: 
1.139     brouard  14070:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   14071:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  14072: 
                   14073:   return (0);
1.164     brouard  14074:  /* endread:*/
1.136     brouard  14075:     printf("Exiting calandcheckages: ");
                   14076:     return (1);
                   14077: }
                   14078: 
1.172     brouard  14079: #if defined(_MSC_VER)
                   14080: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   14081: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   14082: //#include "stdafx.h"
                   14083: //#include <stdio.h>
                   14084: //#include <tchar.h>
                   14085: //#include <windows.h>
                   14086: //#include <iostream>
                   14087: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   14088: 
                   14089: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   14090: 
                   14091: BOOL IsWow64()
                   14092: {
                   14093:        BOOL bIsWow64 = FALSE;
                   14094: 
                   14095:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   14096:        //  (HANDLE, PBOOL);
                   14097: 
                   14098:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   14099: 
                   14100:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   14101:        const char funcName[] = "IsWow64Process";
                   14102:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   14103:                GetProcAddress(module, funcName);
                   14104: 
                   14105:        if (NULL != fnIsWow64Process)
                   14106:        {
                   14107:                if (!fnIsWow64Process(GetCurrentProcess(),
                   14108:                        &bIsWow64))
                   14109:                        //throw std::exception("Unknown error");
                   14110:                        printf("Unknown error\n");
                   14111:        }
                   14112:        return bIsWow64 != FALSE;
                   14113: }
                   14114: #endif
1.177     brouard  14115: 
1.191     brouard  14116: void syscompilerinfo(int logged)
1.292     brouard  14117: {
                   14118: #include <stdint.h>
                   14119: 
                   14120:   /* #include "syscompilerinfo.h"*/
1.185     brouard  14121:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   14122:    /* /GS /W3 /Gy
                   14123:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   14124:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   14125:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  14126:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   14127:    */ 
                   14128:    /* 64 bits */
1.185     brouard  14129:    /*
                   14130:      /GS /W3 /Gy
                   14131:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   14132:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   14133:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   14134:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   14135:    /* Optimization are useless and O3 is slower than O2 */
                   14136:    /*
                   14137:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   14138:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   14139:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   14140:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   14141:    */
1.186     brouard  14142:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  14143:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   14144:       /PDB:"visual studio
                   14145:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   14146:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   14147:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   14148:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   14149:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   14150:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   14151:       uiAccess='false'"
                   14152:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   14153:       /NOLOGO /TLBID:1
                   14154:    */
1.292     brouard  14155: 
                   14156: 
1.177     brouard  14157: #if defined __INTEL_COMPILER
1.178     brouard  14158: #if defined(__GNUC__)
                   14159:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   14160: #endif
1.177     brouard  14161: #elif defined(__GNUC__) 
1.179     brouard  14162: #ifndef  __APPLE__
1.174     brouard  14163: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  14164: #endif
1.177     brouard  14165:    struct utsname sysInfo;
1.178     brouard  14166:    int cross = CROSS;
                   14167:    if (cross){
                   14168:           printf("Cross-");
1.191     brouard  14169:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  14170:    }
1.174     brouard  14171: #endif
                   14172: 
1.191     brouard  14173:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  14174: #if defined(__clang__)
1.191     brouard  14175:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  14176: #endif
                   14177: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  14178:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  14179: #endif
                   14180: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  14181:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  14182: #endif
                   14183: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  14184:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  14185: #endif
                   14186: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  14187:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  14188: #endif
                   14189: #if defined(_MSC_VER)
1.191     brouard  14190:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  14191: #endif
                   14192: #if defined(__PGI)
1.191     brouard  14193:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  14194: #endif
                   14195: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  14196:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  14197: #endif
1.191     brouard  14198:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  14199:    
1.167     brouard  14200: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   14201: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   14202:     // Windows (x64 and x86)
1.191     brouard  14203:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  14204: #elif __unix__ // all unices, not all compilers
                   14205:     // Unix
1.191     brouard  14206:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  14207: #elif __linux__
                   14208:     // linux
1.191     brouard  14209:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  14210: #elif __APPLE__
1.174     brouard  14211:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  14212:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  14213: #endif
                   14214: 
                   14215: /*  __MINGW32__          */
                   14216: /*  __CYGWIN__  */
                   14217: /* __MINGW64__  */
                   14218: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   14219: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   14220: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   14221: /* _WIN64  // Defined for applications for Win64. */
                   14222: /* _M_X64 // Defined for compilations that target x64 processors. */
                   14223: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  14224: 
1.167     brouard  14225: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  14226:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  14227: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  14228:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  14229: #else
1.191     brouard  14230:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  14231: #endif
                   14232: 
1.169     brouard  14233: #if defined(__GNUC__)
                   14234: # if defined(__GNUC_PATCHLEVEL__)
                   14235: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   14236:                             + __GNUC_MINOR__ * 100 \
                   14237:                             + __GNUC_PATCHLEVEL__)
                   14238: # else
                   14239: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   14240:                             + __GNUC_MINOR__ * 100)
                   14241: # endif
1.174     brouard  14242:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  14243:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  14244: 
                   14245:    if (uname(&sysInfo) != -1) {
                   14246:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  14247:         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  14248:    }
                   14249:    else
                   14250:       perror("uname() error");
1.179     brouard  14251:    //#ifndef __INTEL_COMPILER 
                   14252: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  14253:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  14254:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  14255: #endif
1.169     brouard  14256: #endif
1.172     brouard  14257: 
1.286     brouard  14258:    //   void main ()
1.172     brouard  14259:    //   {
1.169     brouard  14260: #if defined(_MSC_VER)
1.174     brouard  14261:    if (IsWow64()){
1.191     brouard  14262:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   14263:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  14264:    }
                   14265:    else{
1.191     brouard  14266:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   14267:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  14268:    }
1.172     brouard  14269:    //     printf("\nPress Enter to continue...");
                   14270:    //     getchar();
                   14271:    //   }
                   14272: 
1.169     brouard  14273: #endif
                   14274:    
1.167     brouard  14275: 
1.219     brouard  14276: }
1.136     brouard  14277: 
1.219     brouard  14278: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  14279:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  14280:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  14281:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  14282:   /* double ftolpl = 1.e-10; */
1.180     brouard  14283:   double age, agebase, agelim;
1.203     brouard  14284:   double tot;
1.180     brouard  14285: 
1.202     brouard  14286:   strcpy(filerespl,"PL_");
                   14287:   strcat(filerespl,fileresu);
                   14288:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  14289:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   14290:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  14291:   }
1.288     brouard  14292:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   14293:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  14294:   pstamp(ficrespl);
1.288     brouard  14295:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  14296:   fprintf(ficrespl,"#Age ");
                   14297:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   14298:   fprintf(ficrespl,"\n");
1.180     brouard  14299:   
1.219     brouard  14300:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  14301: 
1.219     brouard  14302:   agebase=ageminpar;
                   14303:   agelim=agemaxpar;
1.180     brouard  14304: 
1.227     brouard  14305:   /* i1=pow(2,ncoveff); */
1.234     brouard  14306:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  14307:   if (cptcovn < 1){i1=1;}
1.180     brouard  14308: 
1.337     brouard  14309:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
1.238     brouard  14310:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  14311:       k=TKresult[nres];
1.338     brouard  14312:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  14313:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
                   14314:       /*       continue; */
1.235     brouard  14315: 
1.238     brouard  14316:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   14317:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   14318:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   14319:       /* k=k+1; */
                   14320:       /* to clean */
1.332     brouard  14321:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  14322:       fprintf(ficrespl,"#******");
                   14323:       printf("#******");
                   14324:       fprintf(ficlog,"#******");
1.337     brouard  14325:       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  14326:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
1.337     brouard  14327:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14328:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14329:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14330:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14331:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14332:       }
                   14333:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   14334:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14335:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14336:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14337:       /* } */
1.238     brouard  14338:       fprintf(ficrespl,"******\n");
                   14339:       printf("******\n");
                   14340:       fprintf(ficlog,"******\n");
                   14341:       if(invalidvarcomb[k]){
                   14342:        printf("\nCombination (%d) ignored because no case \n",k); 
                   14343:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   14344:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   14345:        continue;
                   14346:       }
1.219     brouard  14347: 
1.238     brouard  14348:       fprintf(ficrespl,"#Age ");
1.337     brouard  14349:       /* for(j=1;j<=cptcoveff;j++) { */
                   14350:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14351:       /* } */
                   14352:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
                   14353:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14354:       }
                   14355:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   14356:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  14357:     
1.238     brouard  14358:       for (age=agebase; age<=agelim; age++){
                   14359:        /* for (age=agebase; age<=agebase; age++){ */
1.337     brouard  14360:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
                   14361:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
1.238     brouard  14362:        fprintf(ficrespl,"%.0f ",age );
1.337     brouard  14363:        /* for(j=1;j<=cptcoveff;j++) */
                   14364:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14365:        for(j=1;j<=cptcovs;j++)
                   14366:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14367:        tot=0.;
                   14368:        for(i=1; i<=nlstate;i++){
                   14369:          tot +=  prlim[i][i];
                   14370:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   14371:        }
                   14372:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   14373:       } /* Age */
                   14374:       /* was end of cptcod */
1.337     brouard  14375:     } /* nres */
                   14376:   /* } /\* for each combination *\/ */
1.219     brouard  14377:   return 0;
1.180     brouard  14378: }
                   14379: 
1.218     brouard  14380: 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  14381:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  14382:        
                   14383:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   14384:    * at any age between ageminpar and agemaxpar
                   14385:         */
1.235     brouard  14386:   int i, j, k, i1, nres=0 ;
1.217     brouard  14387:   /* double ftolpl = 1.e-10; */
                   14388:   double age, agebase, agelim;
                   14389:   double tot;
1.218     brouard  14390:   /* double ***mobaverage; */
                   14391:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  14392: 
                   14393:   strcpy(fileresplb,"PLB_");
                   14394:   strcat(fileresplb,fileresu);
                   14395:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  14396:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   14397:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  14398:   }
1.288     brouard  14399:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   14400:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  14401:   pstamp(ficresplb);
1.288     brouard  14402:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  14403:   fprintf(ficresplb,"#Age ");
                   14404:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   14405:   fprintf(ficresplb,"\n");
                   14406:   
1.218     brouard  14407:   
                   14408:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   14409:   
                   14410:   agebase=ageminpar;
                   14411:   agelim=agemaxpar;
                   14412:   
                   14413:   
1.227     brouard  14414:   i1=pow(2,cptcoveff);
1.218     brouard  14415:   if (cptcovn < 1){i1=1;}
1.227     brouard  14416:   
1.238     brouard  14417:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.338     brouard  14418:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   14419:       k=TKresult[nres];
                   14420:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   14421:      /* if(i1 != 1 && TKresult[nres]!= k) */
                   14422:      /*        continue; */
                   14423:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
1.238     brouard  14424:       fprintf(ficresplb,"#******");
                   14425:       printf("#******");
                   14426:       fprintf(ficlog,"#******");
1.338     brouard  14427:       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) */
                   14428:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14429:        fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14430:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14431:       }
1.338     brouard  14432:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
                   14433:       /*       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14434:       /*       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14435:       /*       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14436:       /* } */
                   14437:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   14438:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14439:       /*       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14440:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14441:       /* } */
1.238     brouard  14442:       fprintf(ficresplb,"******\n");
                   14443:       printf("******\n");
                   14444:       fprintf(ficlog,"******\n");
                   14445:       if(invalidvarcomb[k]){
                   14446:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   14447:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   14448:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   14449:        continue;
                   14450:       }
1.218     brouard  14451:     
1.238     brouard  14452:       fprintf(ficresplb,"#Age ");
1.338     brouard  14453:       for(j=1;j<=cptcovs;j++) {
                   14454:        fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14455:       }
                   14456:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   14457:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  14458:     
                   14459:     
1.238     brouard  14460:       for (age=agebase; age<=agelim; age++){
                   14461:        /* for (age=agebase; age<=agebase; age++){ */
                   14462:        if(mobilavproj > 0){
                   14463:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   14464:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  14465:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  14466:        }else if (mobilavproj == 0){
                   14467:          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);
                   14468:          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);
                   14469:          exit(1);
                   14470:        }else{
                   14471:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  14472:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  14473:          /* printf("TOTOT\n"); */
                   14474:           /* exit(1); */
1.238     brouard  14475:        }
                   14476:        fprintf(ficresplb,"%.0f ",age );
1.338     brouard  14477:        for(j=1;j<=cptcovs;j++)
                   14478:          fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14479:        tot=0.;
                   14480:        for(i=1; i<=nlstate;i++){
                   14481:          tot +=  bprlim[i][i];
                   14482:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   14483:        }
                   14484:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   14485:       } /* Age */
                   14486:       /* was end of cptcod */
1.255     brouard  14487:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.338     brouard  14488:     /* } /\* end of any combination *\/ */
1.238     brouard  14489:   } /* end of nres */  
1.218     brouard  14490:   /* hBijx(p, bage, fage); */
                   14491:   /* fclose(ficrespijb); */
                   14492:   
                   14493:   return 0;
1.217     brouard  14494: }
1.218     brouard  14495:  
1.180     brouard  14496: int hPijx(double *p, int bage, int fage){
                   14497:     /*------------- h Pij x at various ages ------------*/
1.336     brouard  14498:   /* to be optimized with precov */
1.180     brouard  14499:   int stepsize;
                   14500:   int agelim;
                   14501:   int hstepm;
                   14502:   int nhstepm;
1.359     brouard  14503:   int h, i, i1, j, k, nres=0;
1.180     brouard  14504: 
                   14505:   double agedeb;
                   14506:   double ***p3mat;
                   14507: 
1.337     brouard  14508:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   14509:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   14510:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   14511:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   14512:   }
                   14513:   printf("Computing pij: result on file '%s' \n", filerespij);
                   14514:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   14515:   
                   14516:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   14517:   /*if (stepm<=24) stepsize=2;*/
                   14518:   
                   14519:   agelim=AGESUP;
                   14520:   hstepm=stepsize*YEARM; /* Every year of age */
                   14521:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   14522:   
                   14523:   /* hstepm=1;   aff par mois*/
                   14524:   pstamp(ficrespij);
                   14525:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   14526:   i1= pow(2,cptcoveff);
                   14527:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   14528:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   14529:   /*   k=k+1;  */
                   14530:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   14531:     k=TKresult[nres];
1.338     brouard  14532:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  14533:     /* for(k=1; k<=i1;k++){ */
                   14534:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   14535:     /*         continue; */
                   14536:     fprintf(ficrespij,"\n#****** ");
                   14537:     for(j=1;j<=cptcovs;j++){
                   14538:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14539:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14540:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   14541:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14542:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14543:     }
                   14544:     fprintf(ficrespij,"******\n");
                   14545:     
                   14546:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   14547:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   14548:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   14549:       
                   14550:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   14551:       
                   14552:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   14553:       oldm=oldms;savm=savms;
                   14554:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
                   14555:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   14556:       for(i=1; i<=nlstate;i++)
                   14557:        for(j=1; j<=nlstate+ndeath;j++)
                   14558:          fprintf(ficrespij," %1d-%1d",i,j);
                   14559:       fprintf(ficrespij,"\n");
                   14560:       for (h=0; h<=nhstepm; h++){
                   14561:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   14562:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.183     brouard  14563:        for(i=1; i<=nlstate;i++)
                   14564:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  14565:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.183     brouard  14566:        fprintf(ficrespij,"\n");
                   14567:       }
1.337     brouard  14568:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   14569:       fprintf(ficrespij,"\n");
1.180     brouard  14570:     }
1.337     brouard  14571:   }
                   14572:   /*}*/
                   14573:   return 0;
1.180     brouard  14574: }
1.218     brouard  14575:  
                   14576:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  14577:     /*------------- h Bij x at various ages ------------*/
1.336     brouard  14578:     /* To be optimized with precov */
1.217     brouard  14579:   int stepsize;
1.218     brouard  14580:   /* int agelim; */
                   14581:        int ageminl;
1.217     brouard  14582:   int hstepm;
                   14583:   int nhstepm;
1.238     brouard  14584:   int h, i, i1, j, k, nres;
1.218     brouard  14585:        
1.217     brouard  14586:   double agedeb;
                   14587:   double ***p3mat;
1.218     brouard  14588:        
                   14589:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   14590:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   14591:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   14592:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   14593:   }
                   14594:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   14595:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   14596:   
                   14597:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   14598:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  14599:   
1.218     brouard  14600:   /* agelim=AGESUP; */
1.289     brouard  14601:   ageminl=AGEINF; /* was 30 */
1.218     brouard  14602:   hstepm=stepsize*YEARM; /* Every year of age */
                   14603:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   14604:   
                   14605:   /* hstepm=1;   aff par mois*/
                   14606:   pstamp(ficrespijb);
1.255     brouard  14607:   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  14608:   i1= pow(2,cptcoveff);
1.218     brouard  14609:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   14610:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   14611:   /*   k=k+1;  */
1.238     brouard  14612:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  14613:     k=TKresult[nres];
1.338     brouard  14614:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  14615:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   14616:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   14617:     /*         continue; */
                   14618:     fprintf(ficrespijb,"\n#****** ");
                   14619:     for(j=1;j<=cptcovs;j++){
1.338     brouard  14620:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.337     brouard  14621:       /* for(j=1;j<=cptcoveff;j++) */
                   14622:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14623:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   14624:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14625:     }
                   14626:     fprintf(ficrespijb,"******\n");
                   14627:     if(invalidvarcomb[k]){  /* Is it necessary here? */
                   14628:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   14629:       continue;
                   14630:     }
                   14631:     
                   14632:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   14633:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   14634:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   14635:       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 */
                   14636:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
                   14637:       
                   14638:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   14639:       
                   14640:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   14641:       /* and memory limitations if stepm is small */
                   14642:       
                   14643:       /* oldm=oldms;savm=savms; */
                   14644:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   14645:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
                   14646:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   14647:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
                   14648:       for(i=1; i<=nlstate;i++)
                   14649:        for(j=1; j<=nlstate+ndeath;j++)
                   14650:          fprintf(ficrespijb," %1d-%1d",i,j);
                   14651:       fprintf(ficrespijb,"\n");
                   14652:       for (h=0; h<=nhstepm; h++){
                   14653:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   14654:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   14655:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  14656:        for(i=1; i<=nlstate;i++)
                   14657:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  14658:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.217     brouard  14659:        fprintf(ficrespijb,"\n");
1.337     brouard  14660:       }
                   14661:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   14662:       fprintf(ficrespijb,"\n");
                   14663:     } /* end age deb */
                   14664:     /* } /\* end combination *\/ */
1.238     brouard  14665:   } /* end nres */
1.218     brouard  14666:   return 0;
                   14667:  } /*  hBijx */
1.217     brouard  14668: 
1.180     brouard  14669: 
1.136     brouard  14670: /***********************************************/
                   14671: /**************** Main Program *****************/
                   14672: /***********************************************/
                   14673: 
                   14674: int main(int argc, char *argv[])
                   14675: {
                   14676: #ifdef GSL
                   14677:   const gsl_multimin_fminimizer_type *T;
                   14678:   size_t iteri = 0, it;
                   14679:   int rval = GSL_CONTINUE;
                   14680:   int status = GSL_SUCCESS;
                   14681:   double ssval;
                   14682: #endif
                   14683:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  14684:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   14685:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  14686:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  14687:   int jj, ll, li, lj, lk;
1.136     brouard  14688:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  14689:   int num_filled;
1.136     brouard  14690:   int itimes;
                   14691:   int NDIM=2;
                   14692:   int vpopbased=0;
1.235     brouard  14693:   int nres=0;
1.258     brouard  14694:   int endishere=0;
1.277     brouard  14695:   int noffset=0;
1.274     brouard  14696:   int ncurrv=0; /* Temporary variable */
                   14697:   
1.164     brouard  14698:   char ca[32], cb[32];
1.136     brouard  14699:   /*  FILE *fichtm; *//* Html File */
                   14700:   /* FILE *ficgp;*/ /*Gnuplot File */
                   14701:   struct stat info;
1.191     brouard  14702:   double agedeb=0.;
1.194     brouard  14703: 
                   14704:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  14705:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  14706: 
1.361     brouard  14707:   double stdpercent; /* for computing the std error of percent e.i: e.i/e.. */
1.165     brouard  14708:   double fret;
1.191     brouard  14709:   double dum=0.; /* Dummy variable */
1.359     brouard  14710:   /* double*** p3mat;*/
1.218     brouard  14711:   /* double ***mobaverage; */
1.319     brouard  14712:   double wald;
1.164     brouard  14713: 
1.351     brouard  14714:   char line[MAXLINE], linetmp[MAXLINE];
1.197     brouard  14715:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   14716: 
1.234     brouard  14717:   char  modeltemp[MAXLINE];
1.332     brouard  14718:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  14719:   
1.136     brouard  14720:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  14721:   char *tok, *val; /* pathtot */
1.334     brouard  14722:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.359     brouard  14723:   int c, h; /* c2; */
1.191     brouard  14724:   int jl=0;
                   14725:   int i1, j1, jk, stepsize=0;
1.194     brouard  14726:   int count=0;
                   14727: 
1.164     brouard  14728:   int *tab; 
1.136     brouard  14729:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  14730:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   14731:   /* double anprojf, mprojf, jprojf; */
                   14732:   /* double jintmean,mintmean,aintmean;   */
                   14733:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   14734:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   14735:   double yrfproj= 10.0; /* Number of years of forward projections */
                   14736:   double yrbproj= 10.0; /* Number of years of backward projections */
                   14737:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  14738:   int mobilav=0,popforecast=0;
1.191     brouard  14739:   int hstepm=0, nhstepm=0;
1.136     brouard  14740:   int agemortsup;
                   14741:   float  sumlpop=0.;
                   14742:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   14743:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   14744: 
1.191     brouard  14745:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  14746:   double ftolpl=FTOL;
                   14747:   double **prlim;
1.217     brouard  14748:   double **bprlim;
1.317     brouard  14749:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   14750:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  14751:   double ***paramstart; /* Matrix of starting parameter values */
                   14752:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  14753:   double **matcov; /* Matrix of covariance */
1.203     brouard  14754:   double **hess; /* Hessian matrix */
1.136     brouard  14755:   double ***delti3; /* Scale */
                   14756:   double *delti; /* Scale */
                   14757:   double ***eij, ***vareij;
1.359     brouard  14758:   //double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  14759: 
1.136     brouard  14760:   double *epj, vepp;
1.164     brouard  14761: 
1.273     brouard  14762:   double dateprev1, dateprev2;
1.296     brouard  14763:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   14764:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   14765: 
1.217     brouard  14766: 
1.136     brouard  14767:   double **ximort;
1.145     brouard  14768:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  14769:   int *dcwave;
                   14770: 
1.164     brouard  14771:   char z[1]="c";
1.136     brouard  14772: 
                   14773:   /*char  *strt;*/
                   14774:   char strtend[80];
1.126     brouard  14775: 
1.164     brouard  14776: 
1.126     brouard  14777: /*   setlocale (LC_ALL, ""); */
                   14778: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   14779: /*   textdomain (PACKAGE); */
                   14780: /*   setlocale (LC_CTYPE, ""); */
                   14781: /*   setlocale (LC_MESSAGES, ""); */
                   14782: 
                   14783:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  14784:   rstart_time = time(NULL);  
                   14785:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   14786:   start_time = *localtime(&rstart_time);
1.126     brouard  14787:   curr_time=start_time;
1.157     brouard  14788:   /*tml = *localtime(&start_time.tm_sec);*/
                   14789:   /* strcpy(strstart,asctime(&tml)); */
                   14790:   strcpy(strstart,asctime(&start_time));
1.126     brouard  14791: 
                   14792: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  14793: /*  tp.tm_sec = tp.tm_sec +86400; */
                   14794: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  14795: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   14796: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   14797: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  14798: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  14799: /*   strt=asctime(&tmg); */
                   14800: /*   printf("Time(after) =%s",strstart);  */
                   14801: /*  (void) time (&time_value);
                   14802: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   14803: *  tm = *localtime(&time_value);
                   14804: *  strstart=asctime(&tm);
                   14805: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   14806: */
                   14807: 
                   14808:   nberr=0; /* Number of errors and warnings */
                   14809:   nbwarn=0;
1.184     brouard  14810: #ifdef WIN32
                   14811:   _getcwd(pathcd, size);
                   14812: #else
1.126     brouard  14813:   getcwd(pathcd, size);
1.184     brouard  14814: #endif
1.191     brouard  14815:   syscompilerinfo(0);
1.359     brouard  14816:   printf("\nIMaCh prax version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  14817:   if(argc <=1){
                   14818:     printf("\nEnter the parameter file name: ");
1.205     brouard  14819:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   14820:       printf("ERROR Empty parameter file name\n");
                   14821:       goto end;
                   14822:     }
1.126     brouard  14823:     i=strlen(pathr);
                   14824:     if(pathr[i-1]=='\n')
                   14825:       pathr[i-1]='\0';
1.156     brouard  14826:     i=strlen(pathr);
1.205     brouard  14827:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  14828:       pathr[i-1]='\0';
1.205     brouard  14829:     }
                   14830:     i=strlen(pathr);
                   14831:     if( i==0 ){
                   14832:       printf("ERROR Empty parameter file name\n");
                   14833:       goto end;
                   14834:     }
                   14835:     for (tok = pathr; tok != NULL; ){
1.126     brouard  14836:       printf("Pathr |%s|\n",pathr);
                   14837:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   14838:       printf("val= |%s| pathr=%s\n",val,pathr);
                   14839:       strcpy (pathtot, val);
                   14840:       if(pathr[0] == '\0') break; /* Dirty */
                   14841:     }
                   14842:   }
1.281     brouard  14843:   else if (argc<=2){
                   14844:     strcpy(pathtot,argv[1]);
                   14845:   }
1.126     brouard  14846:   else{
                   14847:     strcpy(pathtot,argv[1]);
1.281     brouard  14848:     strcpy(z,argv[2]);
                   14849:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  14850:   }
                   14851:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   14852:   /*cygwin_split_path(pathtot,path,optionfile);
                   14853:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   14854:   /* cutv(path,optionfile,pathtot,'\\');*/
                   14855: 
                   14856:   /* Split argv[0], imach program to get pathimach */
                   14857:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   14858:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   14859:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   14860:  /*   strcpy(pathimach,argv[0]); */
                   14861:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   14862:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   14863:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  14864: #ifdef WIN32
                   14865:   _chdir(path); /* Can be a relative path */
                   14866:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   14867: #else
1.126     brouard  14868:   chdir(path); /* Can be a relative path */
1.184     brouard  14869:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   14870: #endif
                   14871:   printf("Current directory %s!\n",pathcd);
1.126     brouard  14872:   strcpy(command,"mkdir ");
                   14873:   strcat(command,optionfilefiname);
                   14874:   if((outcmd=system(command)) != 0){
1.169     brouard  14875:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  14876:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   14877:     /* fclose(ficlog); */
                   14878: /*     exit(1); */
                   14879:   }
                   14880: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   14881: /*     perror("mkdir"); */
                   14882: /*   } */
                   14883: 
                   14884:   /*-------- arguments in the command line --------*/
                   14885: 
1.186     brouard  14886:   /* Main Log file */
1.126     brouard  14887:   strcat(filelog, optionfilefiname);
                   14888:   strcat(filelog,".log");    /* */
                   14889:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   14890:     printf("Problem with logfile %s\n",filelog);
                   14891:     goto end;
                   14892:   }
                   14893:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  14894:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  14895:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   14896:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   14897:  path=%s \n\
                   14898:  optionfile=%s\n\
                   14899:  optionfilext=%s\n\
1.156     brouard  14900:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  14901: 
1.197     brouard  14902:   syscompilerinfo(1);
1.167     brouard  14903: 
1.126     brouard  14904:   printf("Local time (at start):%s",strstart);
                   14905:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   14906:   fflush(ficlog);
                   14907: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  14908: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  14909: 
                   14910:   /* */
                   14911:   strcpy(fileres,"r");
                   14912:   strcat(fileres, optionfilefiname);
1.201     brouard  14913:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  14914:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  14915:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  14916: 
1.186     brouard  14917:   /* Main ---------arguments file --------*/
1.126     brouard  14918: 
                   14919:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  14920:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   14921:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  14922:     fflush(ficlog);
1.149     brouard  14923:     /* goto end; */
                   14924:     exit(70); 
1.126     brouard  14925:   }
                   14926: 
                   14927:   strcpy(filereso,"o");
1.201     brouard  14928:   strcat(filereso,fileresu);
1.126     brouard  14929:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   14930:     printf("Problem with Output resultfile: %s\n", filereso);
                   14931:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   14932:     fflush(ficlog);
                   14933:     goto end;
                   14934:   }
1.278     brouard  14935:       /*-------- Rewriting parameter file ----------*/
                   14936:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   14937:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   14938:   strcat(rfileres,".");    /* */
                   14939:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   14940:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   14941:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   14942:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   14943:     fflush(ficlog);
                   14944:     goto end;
                   14945:   }
                   14946:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  14947: 
1.278     brouard  14948:                                      
1.126     brouard  14949:   /* Reads comments: lines beginning with '#' */
                   14950:   numlinepar=0;
1.277     brouard  14951:   /* Is it a BOM UTF-8 Windows file? */
                   14952:   /* First parameter line */
1.197     brouard  14953:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  14954:     noffset=0;
                   14955:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   14956:     {
                   14957:       noffset=noffset+3;
                   14958:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   14959:     }
1.302     brouard  14960: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   14961:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  14962:     {
                   14963:       noffset=noffset+2;
                   14964:       printf("# File is an UTF16BE BOM file\n");
                   14965:     }
                   14966:     else if( line[0] == 0 && line[1] == 0)
                   14967:     {
                   14968:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   14969:        noffset=noffset+4;
                   14970:        printf("# File is an UTF16BE BOM file\n");
                   14971:       }
                   14972:     } else{
                   14973:       ;/*printf(" Not a BOM file\n");*/
                   14974:     }
                   14975:   
1.197     brouard  14976:     /* If line starts with a # it is a comment */
1.277     brouard  14977:     if (line[noffset] == '#') {
1.197     brouard  14978:       numlinepar++;
                   14979:       fputs(line,stdout);
                   14980:       fputs(line,ficparo);
1.278     brouard  14981:       fputs(line,ficres);
1.197     brouard  14982:       fputs(line,ficlog);
                   14983:       continue;
                   14984:     }else
                   14985:       break;
                   14986:   }
                   14987:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   14988:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   14989:     if (num_filled != 5) {
                   14990:       printf("Should be 5 parameters\n");
1.283     brouard  14991:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  14992:     }
1.126     brouard  14993:     numlinepar++;
1.197     brouard  14994:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  14995:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   14996:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   14997:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  14998:   }
                   14999:   /* Second parameter line */
                   15000:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  15001:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   15002:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  15003:     if (line[0] == '#') {
                   15004:       numlinepar++;
1.283     brouard  15005:       printf("%s",line);
                   15006:       fprintf(ficres,"%s",line);
                   15007:       fprintf(ficparo,"%s",line);
                   15008:       fprintf(ficlog,"%s",line);
1.197     brouard  15009:       continue;
                   15010:     }else
                   15011:       break;
                   15012:   }
1.223     brouard  15013:   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", \
                   15014:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   15015:     if (num_filled != 11) {
                   15016:       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  15017:       printf("but line=%s\n",line);
1.283     brouard  15018:       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");
                   15019:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  15020:     }
1.286     brouard  15021:     if( lastpass > maxwav){
                   15022:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   15023:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   15024:       fflush(ficlog);
                   15025:       goto end;
                   15026:     }
                   15027:       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  15028:     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  15029:     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  15030:     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  15031:   }
1.203     brouard  15032:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  15033:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  15034:   /* Third parameter line */
                   15035:   while(fgets(line, MAXLINE, ficpar)) {
                   15036:     /* If line starts with a # it is a comment */
                   15037:     if (line[0] == '#') {
                   15038:       numlinepar++;
1.283     brouard  15039:       printf("%s",line);
                   15040:       fprintf(ficres,"%s",line);
                   15041:       fprintf(ficparo,"%s",line);
                   15042:       fprintf(ficlog,"%s",line);
1.197     brouard  15043:       continue;
                   15044:     }else
                   15045:       break;
                   15046:   }
1.351     brouard  15047:   if((num_filled=sscanf(line,"model=%[^.\n]", model)) !=EOF){ /* Every character after model but dot and  return */
                   15048:     if (num_filled != 1){
                   15049:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   15050:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   15051:       model[0]='\0';
                   15052:       goto end;
                   15053:     }else{
                   15054:       trimbtab(linetmp,line); /* Trims multiple blanks in line */
                   15055:       strcpy(line, linetmp);
                   15056:     }
                   15057:   }
                   15058:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){ /* Every character after 1+age but dot and  return */
1.279     brouard  15059:     if (num_filled != 1){
1.302     brouard  15060:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   15061:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  15062:       model[0]='\0';
                   15063:       goto end;
                   15064:     }
                   15065:     else{
                   15066:       if (model[0]=='+'){
                   15067:        for(i=1; i<=strlen(model);i++)
                   15068:          modeltemp[i-1]=model[i];
1.201     brouard  15069:        strcpy(model,modeltemp); 
1.197     brouard  15070:       }
                   15071:     }
1.338     brouard  15072:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  15073:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  15074:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   15075:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   15076:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  15077:   }
                   15078:   /* 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); */
                   15079:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   15080:   /* 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  15081:   /* 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); */
                   15082:   /* 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  15083:   fflush(ficlog);
1.190     brouard  15084:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   15085:   if(model[0]=='#'){
1.279     brouard  15086:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   15087:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   15088:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  15089:     if(mle != -1){
1.279     brouard  15090:       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  15091:       exit(1);
                   15092:     }
                   15093:   }
1.126     brouard  15094:   while((c=getc(ficpar))=='#' && c!= EOF){
                   15095:     ungetc(c,ficpar);
                   15096:     fgets(line, MAXLINE, ficpar);
                   15097:     numlinepar++;
1.195     brouard  15098:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   15099:       z[0]=line[1];
1.342     brouard  15100:     }else if(line[1]=='d'){ /* For debugging individual values of covariates in ficresilk */
1.343     brouard  15101:       debugILK=1;printf("DebugILK\n");
1.195     brouard  15102:     }
                   15103:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  15104:     fputs(line, stdout);
                   15105:     //puts(line);
1.126     brouard  15106:     fputs(line,ficparo);
                   15107:     fputs(line,ficlog);
                   15108:   }
                   15109:   ungetc(c,ficpar);
                   15110: 
                   15111:    
1.290     brouard  15112:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   15113:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   15114:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
1.341     brouard  15115:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /\**< Time varying covariate (dummy and quantitative)*\/ */
                   15116:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /**< Might be better */
1.136     brouard  15117:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   15118:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   15119:      v1+v2*age+v2*v3 makes cptcovn = 3
                   15120:   */
                   15121:   if (strlen(model)>1) 
1.187     brouard  15122:     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  15123:   else
1.187     brouard  15124:     ncovmodel=2; /* Constant and age */
1.133     brouard  15125:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   15126:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  15127:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   15128:     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);
                   15129:     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);
                   15130:     fflush(stdout);
                   15131:     fclose (ficlog);
                   15132:     goto end;
                   15133:   }
1.126     brouard  15134:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   15135:   delti=delti3[1][1];
                   15136:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   15137:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  15138: /* We could also provide initial parameters values giving by simple logistic regression 
                   15139:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   15140:       /* for(i=1;i<nlstate;i++){ */
                   15141:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   15142:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   15143:       /* } */
1.126     brouard  15144:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  15145:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   15146:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  15147:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   15148:     fclose (ficparo);
                   15149:     fclose (ficlog);
                   15150:     goto end;
                   15151:     exit(0);
1.220     brouard  15152:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  15153:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  15154:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   15155:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  15156:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   15157:     matcov=matrix(1,npar,1,npar);
1.203     brouard  15158:     hess=matrix(1,npar,1,npar);
1.220     brouard  15159:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  15160:     /* Read guessed parameters */
1.126     brouard  15161:     /* Reads comments: lines beginning with '#' */
                   15162:     while((c=getc(ficpar))=='#' && c!= EOF){
                   15163:       ungetc(c,ficpar);
                   15164:       fgets(line, MAXLINE, ficpar);
                   15165:       numlinepar++;
1.141     brouard  15166:       fputs(line,stdout);
1.126     brouard  15167:       fputs(line,ficparo);
                   15168:       fputs(line,ficlog);
                   15169:     }
                   15170:     ungetc(c,ficpar);
                   15171:     
                   15172:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  15173:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  15174:     for(i=1; i <=nlstate; i++){
1.234     brouard  15175:       j=0;
1.126     brouard  15176:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  15177:        if(jj==i) continue;
                   15178:        j++;
1.292     brouard  15179:        while((c=getc(ficpar))=='#' && c!= EOF){
                   15180:          ungetc(c,ficpar);
                   15181:          fgets(line, MAXLINE, ficpar);
                   15182:          numlinepar++;
                   15183:          fputs(line,stdout);
                   15184:          fputs(line,ficparo);
                   15185:          fputs(line,ficlog);
                   15186:        }
                   15187:        ungetc(c,ficpar);
1.234     brouard  15188:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   15189:        if ((i1 != i) || (j1 != jj)){
                   15190:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  15191: It might be a problem of design; if ncovcol and the model are correct\n \
                   15192: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  15193:          exit(1);
                   15194:        }
                   15195:        fprintf(ficparo,"%1d%1d",i1,j1);
                   15196:        if(mle==1)
                   15197:          printf("%1d%1d",i,jj);
                   15198:        fprintf(ficlog,"%1d%1d",i,jj);
                   15199:        for(k=1; k<=ncovmodel;k++){
                   15200:          fscanf(ficpar," %lf",&param[i][j][k]);
                   15201:          if(mle==1){
                   15202:            printf(" %lf",param[i][j][k]);
                   15203:            fprintf(ficlog," %lf",param[i][j][k]);
                   15204:          }
                   15205:          else
                   15206:            fprintf(ficlog," %lf",param[i][j][k]);
                   15207:          fprintf(ficparo," %lf",param[i][j][k]);
                   15208:        }
                   15209:        fscanf(ficpar,"\n");
                   15210:        numlinepar++;
                   15211:        if(mle==1)
                   15212:          printf("\n");
                   15213:        fprintf(ficlog,"\n");
                   15214:        fprintf(ficparo,"\n");
1.126     brouard  15215:       }
                   15216:     }  
                   15217:     fflush(ficlog);
1.234     brouard  15218:     
1.251     brouard  15219:     /* Reads parameters values */
1.126     brouard  15220:     p=param[1][1];
1.251     brouard  15221:     pstart=paramstart[1][1];
1.126     brouard  15222:     
                   15223:     /* Reads comments: lines beginning with '#' */
                   15224:     while((c=getc(ficpar))=='#' && c!= EOF){
                   15225:       ungetc(c,ficpar);
                   15226:       fgets(line, MAXLINE, ficpar);
                   15227:       numlinepar++;
1.141     brouard  15228:       fputs(line,stdout);
1.126     brouard  15229:       fputs(line,ficparo);
                   15230:       fputs(line,ficlog);
                   15231:     }
                   15232:     ungetc(c,ficpar);
                   15233: 
                   15234:     for(i=1; i <=nlstate; i++){
                   15235:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  15236:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   15237:        if ( (i1-i) * (j1-j) != 0){
                   15238:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   15239:          exit(1);
                   15240:        }
                   15241:        printf("%1d%1d",i,j);
                   15242:        fprintf(ficparo,"%1d%1d",i1,j1);
                   15243:        fprintf(ficlog,"%1d%1d",i1,j1);
                   15244:        for(k=1; k<=ncovmodel;k++){
                   15245:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   15246:          printf(" %le",delti3[i][j][k]);
                   15247:          fprintf(ficparo," %le",delti3[i][j][k]);
                   15248:          fprintf(ficlog," %le",delti3[i][j][k]);
                   15249:        }
                   15250:        fscanf(ficpar,"\n");
                   15251:        numlinepar++;
                   15252:        printf("\n");
                   15253:        fprintf(ficparo,"\n");
                   15254:        fprintf(ficlog,"\n");
1.126     brouard  15255:       }
                   15256:     }
                   15257:     fflush(ficlog);
1.234     brouard  15258:     
1.145     brouard  15259:     /* Reads covariance matrix */
1.126     brouard  15260:     delti=delti3[1][1];
1.220     brouard  15261:                
                   15262:                
1.126     brouard  15263:     /* 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  15264:                
1.126     brouard  15265:     /* Reads comments: lines beginning with '#' */
                   15266:     while((c=getc(ficpar))=='#' && c!= EOF){
                   15267:       ungetc(c,ficpar);
                   15268:       fgets(line, MAXLINE, ficpar);
                   15269:       numlinepar++;
1.141     brouard  15270:       fputs(line,stdout);
1.126     brouard  15271:       fputs(line,ficparo);
                   15272:       fputs(line,ficlog);
                   15273:     }
                   15274:     ungetc(c,ficpar);
1.220     brouard  15275:                
1.126     brouard  15276:     matcov=matrix(1,npar,1,npar);
1.203     brouard  15277:     hess=matrix(1,npar,1,npar);
1.131     brouard  15278:     for(i=1; i <=npar; i++)
                   15279:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  15280:                
1.194     brouard  15281:     /* Scans npar lines */
1.126     brouard  15282:     for(i=1; i <=npar; i++){
1.226     brouard  15283:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  15284:       if(count != 3){
1.226     brouard  15285:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  15286: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   15287: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  15288:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  15289: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   15290: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  15291:        exit(1);
1.220     brouard  15292:       }else{
1.226     brouard  15293:        if(mle==1)
                   15294:          printf("%1d%1d%d",i1,j1,jk);
                   15295:       }
                   15296:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   15297:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  15298:       for(j=1; j <=i; j++){
1.226     brouard  15299:        fscanf(ficpar," %le",&matcov[i][j]);
                   15300:        if(mle==1){
                   15301:          printf(" %.5le",matcov[i][j]);
                   15302:        }
                   15303:        fprintf(ficlog," %.5le",matcov[i][j]);
                   15304:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  15305:       }
                   15306:       fscanf(ficpar,"\n");
                   15307:       numlinepar++;
                   15308:       if(mle==1)
1.220     brouard  15309:                                printf("\n");
1.126     brouard  15310:       fprintf(ficlog,"\n");
                   15311:       fprintf(ficparo,"\n");
                   15312:     }
1.194     brouard  15313:     /* End of read covariance matrix npar lines */
1.126     brouard  15314:     for(i=1; i <=npar; i++)
                   15315:       for(j=i+1;j<=npar;j++)
1.226     brouard  15316:        matcov[i][j]=matcov[j][i];
1.126     brouard  15317:     
                   15318:     if(mle==1)
                   15319:       printf("\n");
                   15320:     fprintf(ficlog,"\n");
                   15321:     
                   15322:     fflush(ficlog);
                   15323:     
                   15324:   }    /* End of mle != -3 */
1.218     brouard  15325:   
1.186     brouard  15326:   /*  Main data
                   15327:    */
1.290     brouard  15328:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   15329:   /* num=lvector(1,n); */
                   15330:   /* moisnais=vector(1,n); */
                   15331:   /* annais=vector(1,n); */
                   15332:   /* moisdc=vector(1,n); */
                   15333:   /* andc=vector(1,n); */
                   15334:   /* weight=vector(1,n); */
                   15335:   /* agedc=vector(1,n); */
                   15336:   /* cod=ivector(1,n); */
                   15337:   /* for(i=1;i<=n;i++){ */
                   15338:   num=lvector(firstobs,lastobs);
                   15339:   moisnais=vector(firstobs,lastobs);
                   15340:   annais=vector(firstobs,lastobs);
                   15341:   moisdc=vector(firstobs,lastobs);
                   15342:   andc=vector(firstobs,lastobs);
                   15343:   weight=vector(firstobs,lastobs);
                   15344:   agedc=vector(firstobs,lastobs);
                   15345:   cod=ivector(firstobs,lastobs);
                   15346:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  15347:     num[i]=0;
                   15348:     moisnais[i]=0;
                   15349:     annais[i]=0;
                   15350:     moisdc[i]=0;
                   15351:     andc[i]=0;
                   15352:     agedc[i]=0;
                   15353:     cod[i]=0;
                   15354:     weight[i]=1.0; /* Equal weights, 1 by default */
                   15355:   }
1.290     brouard  15356:   mint=matrix(1,maxwav,firstobs,lastobs);
                   15357:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  15358:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
1.336     brouard  15359:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
1.126     brouard  15360:   tab=ivector(1,NCOVMAX);
1.144     brouard  15361:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  15362:   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  15363: 
1.136     brouard  15364:   /* Reads data from file datafile */
                   15365:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   15366:     goto end;
                   15367: 
                   15368:   /* Calculation of the number of parameters from char model */
1.234     brouard  15369:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  15370:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   15371:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   15372:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   15373:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  15374:   */
                   15375:   
                   15376:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   15377:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  15378:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335     brouard  15379:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  15380:   TvarsD=ivector(1,NCOVMAX); /*  */
                   15381:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   15382:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  15383:   TvarF=ivector(1,NCOVMAX); /*  */
                   15384:   TvarFind=ivector(1,NCOVMAX); /*  */
                   15385:   TvarV=ivector(1,NCOVMAX); /*  */
                   15386:   TvarVind=ivector(1,NCOVMAX); /*  */
                   15387:   TvarA=ivector(1,NCOVMAX); /*  */
                   15388:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  15389:   TvarFD=ivector(1,NCOVMAX); /*  */
                   15390:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   15391:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   15392:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   15393:   TvarVD=ivector(1,NCOVMAX); /*  */
                   15394:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   15395:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   15396:   TvarVQind=ivector(1,NCOVMAX); /*  */
1.339     brouard  15397:   TvarVV=ivector(1,NCOVMAX); /*  */
                   15398:   TvarVVind=ivector(1,NCOVMAX); /*  */
1.349     brouard  15399:   TvarVVA=ivector(1,NCOVMAX); /*  */
                   15400:   TvarVVAind=ivector(1,NCOVMAX); /*  */
                   15401:   TvarAVVA=ivector(1,NCOVMAX); /*  */
                   15402:   TvarAVVAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  15403: 
1.230     brouard  15404:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  15405:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  15406:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   15407:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   15408:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.349     brouard  15409:   DummyV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   15410:   FixedV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   15411: 
1.137     brouard  15412:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   15413:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   15414:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   15415:   */
                   15416:   /* For model-covariate k tells which data-covariate to use but
                   15417:     because this model-covariate is a construction we invent a new column
                   15418:     ncovcol + k1
                   15419:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   15420:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  15421:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   15422:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  15423:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   15424:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  15425:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  15426:   */
1.145     brouard  15427:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   15428:   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  15429:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   15430:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.351     brouard  15431:   Tvardk=imatrix(0,NCOVMAX,1,2);
1.145     brouard  15432:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  15433:                         4 covariates (3 plus signs)
                   15434:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  15435:                           */  
                   15436:   for(i=1;i<NCOVMAX;i++)
                   15437:     Tage[i]=0;
1.230     brouard  15438:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  15439:                                * individual dummy, fixed or varying:
                   15440:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   15441:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  15442:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   15443:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   15444:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   15445:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   15446:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  15447:                                * individual quantitative, fixed or varying:
                   15448:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   15449:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   15450:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.349     brouard  15451: 
                   15452: /* Probably useless zeroes */
                   15453:   for(i=1;i<NCOVMAX;i++){
                   15454:     DummyV[i]=0;
                   15455:     FixedV[i]=0;
                   15456:   }
                   15457: 
                   15458:   for(i=1; i <=ncovcol;i++){
                   15459:     DummyV[i]=0;
                   15460:     FixedV[i]=0;
                   15461:   }
                   15462:   for(i=ncovcol+1; i <=ncovcol+nqv;i++){
                   15463:     DummyV[i]=1;
                   15464:     FixedV[i]=0;
                   15465:   }
                   15466:   for(i=ncovcol+nqv+1; i <=ncovcol+nqv+ntv;i++){
                   15467:     DummyV[i]=0;
                   15468:     FixedV[i]=1;
                   15469:   }
                   15470:   for(i=ncovcol+nqv+ntv+1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   15471:     DummyV[i]=1;
                   15472:     FixedV[i]=1;
                   15473:   }
                   15474:   for(i=1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   15475:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",i,i,DummyV[i],i,FixedV[i]);
                   15476:     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]);
                   15477:   }
                   15478: 
                   15479: 
                   15480: 
1.186     brouard  15481: /* Main decodemodel */
                   15482: 
1.187     brouard  15483: 
1.223     brouard  15484:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  15485:     goto end;
                   15486: 
1.137     brouard  15487:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   15488:     nbwarn++;
                   15489:     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); 
                   15490:     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); 
                   15491:   }
1.136     brouard  15492:     /*  if(mle==1){*/
1.137     brouard  15493:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   15494:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  15495:   }
                   15496: 
                   15497:     /*-calculation of age at interview from date of interview and age at death -*/
                   15498:   agev=matrix(1,maxwav,1,imx);
                   15499: 
                   15500:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   15501:     goto end;
                   15502: 
1.126     brouard  15503: 
1.136     brouard  15504:   agegomp=(int)agemin;
1.290     brouard  15505:   free_vector(moisnais,firstobs,lastobs);
                   15506:   free_vector(annais,firstobs,lastobs);
1.126     brouard  15507:   /* free_matrix(mint,1,maxwav,1,n);
                   15508:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  15509:   /* free_vector(moisdc,1,n); */
                   15510:   /* free_vector(andc,1,n); */
1.145     brouard  15511:   /* */
                   15512:   
1.126     brouard  15513:   wav=ivector(1,imx);
1.214     brouard  15514:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   15515:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   15516:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   15517:   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.*/
                   15518:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   15519:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  15520:    
                   15521:   /* Concatenates waves */
1.214     brouard  15522:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   15523:      Death is a valid wave (if date is known).
                   15524:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   15525:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   15526:      and mw[mi+1][i]. dh depends on stepm.
                   15527:   */
                   15528: 
1.126     brouard  15529:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  15530:   /* Concatenates waves */
1.145     brouard  15531:  
1.290     brouard  15532:   free_vector(moisdc,firstobs,lastobs);
                   15533:   free_vector(andc,firstobs,lastobs);
1.215     brouard  15534: 
1.126     brouard  15535:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   15536:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   15537:   ncodemax[1]=1;
1.145     brouard  15538:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  15539:   cptcoveff=0;
1.220     brouard  15540:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335     brouard  15541:     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  15542:   }
                   15543:   
                   15544:   ncovcombmax=pow(2,cptcoveff);
1.338     brouard  15545:   invalidvarcomb=ivector(0, ncovcombmax); 
                   15546:   for(i=0;i<ncovcombmax;i++)
1.227     brouard  15547:     invalidvarcomb[i]=0;
                   15548:   
1.211     brouard  15549:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  15550:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  15551:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  15552:   
1.200     brouard  15553:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  15554:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  15555:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  15556:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   15557:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   15558:    * (currently 0 or 1) in the data.
                   15559:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   15560:    * corresponding modality (h,j).
                   15561:    */
                   15562: 
1.145     brouard  15563:   h=0;
                   15564:   /*if (cptcovn > 0) */
1.126     brouard  15565:   m=pow(2,cptcoveff);
                   15566:  
1.144     brouard  15567:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  15568:           * For k=4 covariates, h goes from 1 to m=2**k
                   15569:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   15570:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  15571:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   15572:           *______________________________   *______________________
                   15573:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   15574:           *     2     2     1     1     1   *     1     0  0  0  1 
                   15575:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   15576:           *     4     2     2     1     1   *     3     0  0  1  1 
                   15577:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   15578:           *     6     2     1     2     1   *     5     0  1  0  1 
                   15579:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   15580:           *     8     2     2     2     1   *     7     0  1  1  1 
                   15581:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   15582:           *    10     2     1     1     2   *     9     1  0  0  1 
                   15583:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   15584:           *    12     2     2     1     2   *    11     1  0  1  1 
                   15585:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   15586:           *    14     2     1     2     2   *    13     1  1  0  1 
                   15587:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   15588:           *    16     2     2     2     2   *    15     1  1  1  1          
                   15589:           */                                     
1.212     brouard  15590:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  15591:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   15592:      * and the value of each covariate?
                   15593:      * V1=1, V2=1, V3=2, V4=1 ?
                   15594:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   15595:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   15596:      * In order to get the real value in the data, we use nbcode
                   15597:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   15598:      * We are keeping this crazy system in order to be able (in the future?) 
                   15599:      * to have more than 2 values (0 or 1) for a covariate.
                   15600:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   15601:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   15602:      *              bbbbbbbb
                   15603:      *              76543210     
                   15604:      *   h-1        00000101 (6-1=5)
1.219     brouard  15605:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  15606:      *           &
                   15607:      *     1        00000001 (1)
1.219     brouard  15608:      *              00000000        = 1 & ((h-1) >> (k-1))
                   15609:      *          +1= 00000001 =1 
1.211     brouard  15610:      *
                   15611:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   15612:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   15613:      *    >>k'            11
                   15614:      *          &   00000001
                   15615:      *            = 00000001
                   15616:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   15617:      * Reverse h=6 and m=16?
                   15618:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   15619:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   15620:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   15621:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   15622:      * V3=decodtabm(14,3,2**4)=2
                   15623:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   15624:      *(h-1) >> (j-1)    0011 =13 >> 2
                   15625:      *          &1 000000001
                   15626:      *           = 000000001
                   15627:      *         +1= 000000010 =2
                   15628:      *                  2211
                   15629:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   15630:      *                  V3=2
1.220     brouard  15631:                 * codtabm and decodtabm are identical
1.211     brouard  15632:      */
                   15633: 
1.145     brouard  15634: 
                   15635:  free_ivector(Ndum,-1,NCOVMAX);
                   15636: 
                   15637: 
1.126     brouard  15638:     
1.186     brouard  15639:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  15640:   strcpy(optionfilegnuplot,optionfilefiname);
                   15641:   if(mle==-3)
1.201     brouard  15642:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  15643:   strcat(optionfilegnuplot,".gp");
                   15644: 
                   15645:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   15646:     printf("Problem with file %s",optionfilegnuplot);
                   15647:   }
                   15648:   else{
1.204     brouard  15649:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  15650:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  15651:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   15652:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  15653:   }
                   15654:   /*  fclose(ficgp);*/
1.186     brouard  15655: 
                   15656: 
                   15657:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  15658: 
                   15659:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   15660:   if(mle==-3)
1.201     brouard  15661:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  15662:   strcat(optionfilehtm,".htm");
                   15663:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  15664:     printf("Problem with %s \n",optionfilehtm);
                   15665:     exit(0);
1.126     brouard  15666:   }
                   15667: 
                   15668:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   15669:   strcat(optionfilehtmcov,"-cov.htm");
                   15670:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   15671:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   15672:   }
                   15673:   else{
                   15674:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   15675: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  15676: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  15677:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   15678:   }
                   15679: 
1.335     brouard  15680:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   15681: <title>IMaCh %s</title></head>\n\
                   15682:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   15683: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   15684: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   15685: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   15686: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   15687:   
                   15688:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  15689: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  15690: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.337     brouard  15691: 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  15692: \n\
                   15693: <hr  size=\"2\" color=\"#EC5E5E\">\
                   15694:  <ul><li><h4>Parameter files</h4>\n\
                   15695:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   15696:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   15697:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   15698:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   15699:  - Date and time at start: %s</ul>\n",\
1.335     brouard  15700:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  15701:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   15702:          fileres,fileres,\
                   15703:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   15704:   fflush(fichtm);
                   15705: 
                   15706:   strcpy(pathr,path);
                   15707:   strcat(pathr,optionfilefiname);
1.184     brouard  15708: #ifdef WIN32
                   15709:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   15710: #else
1.126     brouard  15711:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  15712: #endif
                   15713:          
1.126     brouard  15714:   
1.220     brouard  15715:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   15716:                 and for any valid combination of covariates
1.126     brouard  15717:      and prints on file fileres'p'. */
1.359     brouard  15718:   freqsummary(fileres, p, pstart, (double)agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  15719:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  15720: 
                   15721:   fprintf(fichtm,"\n");
1.286     brouard  15722:   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  15723:          ftol, stepm);
                   15724:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   15725:   ncurrv=1;
                   15726:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   15727:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   15728:   ncurrv=i;
                   15729:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  15730:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  15731:   ncurrv=i;
                   15732:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  15733:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  15734:   ncurrv=i;
                   15735:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   15736:   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", \
                   15737:           nlstate, ndeath, maxwav, mle, weightopt);
                   15738: 
                   15739:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   15740: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   15741: 
                   15742:   
1.317     brouard  15743:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  15744: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   15745: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  15746:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  15747:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  15748:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   15749:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   15750:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   15751:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  15752: 
1.126     brouard  15753:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   15754:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   15755:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   15756: 
                   15757:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  15758:   /* For mortality only */
1.126     brouard  15759:   if (mle==-3){
1.136     brouard  15760:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  15761:     for(i=1;i<=NDIM;i++)
                   15762:       for(j=1;j<=NDIM;j++)
                   15763:        ximort[i][j]=0.;
1.186     brouard  15764:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  15765:     cens=ivector(firstobs,lastobs);
                   15766:     ageexmed=vector(firstobs,lastobs);
                   15767:     agecens=vector(firstobs,lastobs);
                   15768:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  15769:                
1.126     brouard  15770:     for (i=1; i<=imx; i++){
                   15771:       dcwave[i]=-1;
                   15772:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  15773:        if (s[m][i]>nlstate) {
                   15774:          dcwave[i]=m;
                   15775:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   15776:          break;
                   15777:        }
1.126     brouard  15778:     }
1.226     brouard  15779:     
1.126     brouard  15780:     for (i=1; i<=imx; i++) {
                   15781:       if (wav[i]>0){
1.226     brouard  15782:        ageexmed[i]=agev[mw[1][i]][i];
                   15783:        j=wav[i];
                   15784:        agecens[i]=1.; 
                   15785:        
                   15786:        if (ageexmed[i]> 1 && wav[i] > 0){
                   15787:          agecens[i]=agev[mw[j][i]][i];
                   15788:          cens[i]= 1;
                   15789:        }else if (ageexmed[i]< 1) 
                   15790:          cens[i]= -1;
                   15791:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   15792:          cens[i]=0 ;
1.126     brouard  15793:       }
                   15794:       else cens[i]=-1;
                   15795:     }
                   15796:     
                   15797:     for (i=1;i<=NDIM;i++) {
                   15798:       for (j=1;j<=NDIM;j++)
1.226     brouard  15799:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  15800:     }
                   15801:     
1.302     brouard  15802:     p[1]=0.0268; p[NDIM]=0.083;
                   15803:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  15804:     
                   15805:     
1.136     brouard  15806: #ifdef GSL
                   15807:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  15808: #else
1.359     brouard  15809:     printf("Powell-mort\n");  fprintf(ficlog,"Powell-mort\n");
1.136     brouard  15810: #endif
1.201     brouard  15811:     strcpy(filerespow,"POW-MORT_"); 
                   15812:     strcat(filerespow,fileresu);
1.126     brouard  15813:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   15814:       printf("Problem with resultfile: %s\n", filerespow);
                   15815:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   15816:     }
1.136     brouard  15817: #ifdef GSL
                   15818:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  15819: #else
1.126     brouard  15820:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  15821: #endif
1.126     brouard  15822:     /*  for (i=1;i<=nlstate;i++)
                   15823:        for(j=1;j<=nlstate+ndeath;j++)
                   15824:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   15825:     */
                   15826:     fprintf(ficrespow,"\n");
1.136     brouard  15827: #ifdef GSL
                   15828:     /* gsl starts here */ 
                   15829:     T = gsl_multimin_fminimizer_nmsimplex;
                   15830:     gsl_multimin_fminimizer *sfm = NULL;
                   15831:     gsl_vector *ss, *x;
                   15832:     gsl_multimin_function minex_func;
                   15833: 
                   15834:     /* Initial vertex size vector */
                   15835:     ss = gsl_vector_alloc (NDIM);
                   15836:     
                   15837:     if (ss == NULL){
                   15838:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   15839:     }
                   15840:     /* Set all step sizes to 1 */
                   15841:     gsl_vector_set_all (ss, 0.001);
                   15842: 
                   15843:     /* Starting point */
1.126     brouard  15844:     
1.136     brouard  15845:     x = gsl_vector_alloc (NDIM);
                   15846:     
                   15847:     if (x == NULL){
                   15848:       gsl_vector_free(ss);
                   15849:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   15850:     }
                   15851:   
                   15852:     /* Initialize method and iterate */
                   15853:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  15854:     /*     gsl_vector_set(x, 0, 0.0268); */
                   15855:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  15856:     gsl_vector_set(x, 0, p[1]);
                   15857:     gsl_vector_set(x, 1, p[2]);
                   15858: 
                   15859:     minex_func.f = &gompertz_f;
                   15860:     minex_func.n = NDIM;
                   15861:     minex_func.params = (void *)&p; /* ??? */
                   15862:     
                   15863:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   15864:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   15865:     
                   15866:     printf("Iterations beginning .....\n\n");
                   15867:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   15868: 
                   15869:     iteri=0;
                   15870:     while (rval == GSL_CONTINUE){
                   15871:       iteri++;
                   15872:       status = gsl_multimin_fminimizer_iterate(sfm);
                   15873:       
                   15874:       if (status) printf("error: %s\n", gsl_strerror (status));
                   15875:       fflush(0);
                   15876:       
                   15877:       if (status) 
                   15878:         break;
                   15879:       
                   15880:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   15881:       ssval = gsl_multimin_fminimizer_size (sfm);
                   15882:       
                   15883:       if (rval == GSL_SUCCESS)
                   15884:         printf ("converged to a local maximum at\n");
                   15885:       
                   15886:       printf("%5d ", iteri);
                   15887:       for (it = 0; it < NDIM; it++){
                   15888:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   15889:       }
                   15890:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   15891:     }
                   15892:     
                   15893:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   15894:     
                   15895:     gsl_vector_free(x); /* initial values */
                   15896:     gsl_vector_free(ss); /* inital step size */
                   15897:     for (it=0; it<NDIM; it++){
                   15898:       p[it+1]=gsl_vector_get(sfm->x,it);
                   15899:       fprintf(ficrespow," %.12lf", p[it]);
                   15900:     }
                   15901:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   15902: #endif
                   15903: #ifdef POWELL
1.361     brouard  15904: #ifdef LINMINORIGINAL
                   15905: #else /* LINMINORIGINAL */
                   15906:   
                   15907:   flatdir=ivector(1,npar); 
                   15908:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   15909: #endif /*LINMINORIGINAL */
1.362     brouard  15910:     /* powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz); */
                   15911:   /* double h0=0.25; */
                   15912:   macheps=pow(16.0,-13.0);
                   15913:   printf("Praxis Gegenfurtner mle=%d\n",mle);
                   15914:   fprintf(ficlog, "Praxis  Gegenfurtner mle=%d\n", mle);fflush(ficlog);
                   15915:    /* ffmin = praxis(ftol,macheps, h0, npar, prin, p, gompertz); */
                   15916:   /* For the Gompertz we use only two parameters */
                   15917:   int _npar=2;
                   15918:    ffmin = praxis(ftol,macheps, h0, _npar, 4, p, gompertz);
                   15919:   printf("End Praxis\n");
1.126     brouard  15920:     fclose(ficrespow);
1.361     brouard  15921: #ifdef LINMINORIGINAL
                   15922: #else
                   15923:       free_ivector(flatdir,1,npar); 
                   15924: #endif  /* LINMINORIGINAL*/
1.364     brouard  15925: #endif /* POWELL */   
1.203     brouard  15926:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  15927: 
                   15928:     for(i=1; i <=NDIM; i++)
                   15929:       for(j=i+1;j<=NDIM;j++)
1.359     brouard  15930:        matcov[i][j]=matcov[j][i];
1.126     brouard  15931:     
                   15932:     printf("\nCovariance matrix\n ");
1.203     brouard  15933:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  15934:     for(i=1; i <=NDIM; i++) {
                   15935:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  15936:                                printf("%f ",matcov[i][j]);
                   15937:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  15938:       }
1.203     brouard  15939:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  15940:     }
                   15941:     
                   15942:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  15943:     for (i=1;i<=NDIM;i++) {
1.126     brouard  15944:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  15945:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   15946:     }
1.302     brouard  15947:     lsurv=vector(agegomp,AGESUP);
                   15948:     lpop=vector(agegomp,AGESUP);
                   15949:     tpop=vector(agegomp,AGESUP);
1.126     brouard  15950:     lsurv[agegomp]=100000;
                   15951:     
                   15952:     for (k=agegomp;k<=AGESUP;k++) {
                   15953:       agemortsup=k;
                   15954:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   15955:     }
                   15956:     
                   15957:     for (k=agegomp;k<agemortsup;k++)
                   15958:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   15959:     
                   15960:     for (k=agegomp;k<agemortsup;k++){
                   15961:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   15962:       sumlpop=sumlpop+lpop[k];
                   15963:     }
                   15964:     
                   15965:     tpop[agegomp]=sumlpop;
                   15966:     for (k=agegomp;k<(agemortsup-3);k++){
                   15967:       /*  tpop[k+1]=2;*/
                   15968:       tpop[k+1]=tpop[k]-lpop[k];
                   15969:     }
                   15970:     
                   15971:     
                   15972:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   15973:     for (k=agegomp;k<(agemortsup-2);k++) 
                   15974:       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]);
                   15975:     
                   15976:     
                   15977:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  15978:                ageminpar=50;
                   15979:                agemaxpar=100;
1.194     brouard  15980:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   15981:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   15982: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   15983: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   15984:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   15985: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   15986: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  15987:     }else{
                   15988:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   15989:                        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  15990:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  15991:                }
1.201     brouard  15992:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  15993:                     stepm, weightopt,\
                   15994:                     model,imx,p,matcov,agemortsup);
                   15995:     
1.302     brouard  15996:     free_vector(lsurv,agegomp,AGESUP);
                   15997:     free_vector(lpop,agegomp,AGESUP);
                   15998:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  15999:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  16000:     free_ivector(dcwave,firstobs,lastobs);
                   16001:     free_vector(agecens,firstobs,lastobs);
                   16002:     free_vector(ageexmed,firstobs,lastobs);
                   16003:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  16004: #ifdef GSL
1.136     brouard  16005: #endif
1.186     brouard  16006:   } /* Endof if mle==-3 mortality only */
1.205     brouard  16007:   /* Standard  */
                   16008:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   16009:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   16010:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  16011:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  16012:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   16013:     for (k=1; k<=npar;k++)
                   16014:       printf(" %d %8.5f",k,p[k]);
                   16015:     printf("\n");
1.205     brouard  16016:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   16017:       /* mlikeli uses func not funcone */
1.247     brouard  16018:       /* for(i=1;i<nlstate;i++){ */
                   16019:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   16020:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   16021:       /* } */
1.205     brouard  16022:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   16023:     }
                   16024:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   16025:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   16026:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   16027:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   16028:     }
                   16029:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  16030:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   16031:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335     brouard  16032:           /* exit(0); */
1.126     brouard  16033:     for (k=1; k<=npar;k++)
                   16034:       printf(" %d %8.5f",k,p[k]);
                   16035:     printf("\n");
                   16036:     
                   16037:     /*--------- results files --------------*/
1.283     brouard  16038:     /* 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  16039:     
                   16040:     
                   16041:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  16042:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  16043:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  16044: 
                   16045:     printf("#model=  1      +     age ");
                   16046:     fprintf(ficres,"#model=  1      +     age ");
                   16047:     fprintf(ficlog,"#model=  1      +     age ");
                   16048:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   16049: </ul>", model);
                   16050: 
                   16051:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   16052:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   16053:     if(nagesqr==1){
                   16054:       printf("  + age*age  ");
                   16055:       fprintf(ficres,"  + age*age  ");
                   16056:       fprintf(ficlog,"  + age*age  ");
                   16057:       fprintf(fichtm, "<th>+ age*age</th>");
                   16058:     }
1.362     brouard  16059:     for(j=1;j <=ncovmodel-2-nagesqr;j++){
1.319     brouard  16060:       if(Typevar[j]==0) {
                   16061:        printf("  +      V%d  ",Tvar[j]);
                   16062:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   16063:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   16064:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   16065:       }else if(Typevar[j]==1) {
                   16066:        printf("  +    V%d*age ",Tvar[j]);
                   16067:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   16068:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   16069:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   16070:       }else if(Typevar[j]==2) {
                   16071:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   16072:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   16073:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   16074:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  16075:       }else if(Typevar[j]==3) { /* TO VERIFY */
                   16076:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   16077:        fprintf(ficres,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   16078:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   16079:        fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  16080:       }
                   16081:     }
                   16082:     printf("\n");
                   16083:     fprintf(ficres,"\n");
                   16084:     fprintf(ficlog,"\n");
                   16085:     fprintf(fichtm, "</tr>");
                   16086:     fprintf(fichtm, "\n");
                   16087:     
                   16088:     
1.126     brouard  16089:     for(i=1,jk=1; i <=nlstate; i++){
                   16090:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  16091:        if (k != i) {
1.319     brouard  16092:          fprintf(fichtm, "<tr>");
1.225     brouard  16093:          printf("%d%d ",i,k);
                   16094:          fprintf(ficlog,"%d%d ",i,k);
                   16095:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  16096:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  16097:          for(j=1; j <=ncovmodel; j++){
                   16098:            printf("%12.7f ",p[jk]);
                   16099:            fprintf(ficlog,"%12.7f ",p[jk]);
                   16100:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  16101:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  16102:            jk++; 
                   16103:          }
                   16104:          printf("\n");
                   16105:          fprintf(ficlog,"\n");
                   16106:          fprintf(ficres,"\n");
1.319     brouard  16107:          fprintf(fichtm, "</tr>\n");
1.225     brouard  16108:        }
1.126     brouard  16109:       }
                   16110:     }
1.319     brouard  16111:     /* fprintf(fichtm,"</tr>\n"); */
                   16112:     fprintf(fichtm,"</table>\n");
                   16113:     fprintf(fichtm, "\n");
                   16114: 
1.203     brouard  16115:     if(mle != 0){
                   16116:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  16117:       ftolhess=ftol; /* Usually correct */
1.203     brouard  16118:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   16119:       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");
                   16120:       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  16121:       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  16122:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   16123:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   16124:       if(nagesqr==1){
                   16125:        printf("  + age*age  ");
                   16126:        fprintf(ficres,"  + age*age  ");
                   16127:        fprintf(ficlog,"  + age*age  ");
                   16128:        fprintf(fichtm, "<th>+ age*age</th>");
                   16129:       }
1.362     brouard  16130:       for(j=1;j <=ncovmodel-2-nagesqr;j++){
1.319     brouard  16131:        if(Typevar[j]==0) {
                   16132:          printf("  +      V%d  ",Tvar[j]);
                   16133:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   16134:        }else if(Typevar[j]==1) {
                   16135:          printf("  +    V%d*age ",Tvar[j]);
                   16136:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   16137:        }else if(Typevar[j]==2) {
                   16138:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  16139:        }else if(Typevar[j]==3) { /* TO VERIFY */
                   16140:          fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  16141:        }
                   16142:       }
                   16143:       fprintf(fichtm, "</tr>\n");
                   16144:  
1.203     brouard  16145:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  16146:        for(k=1; k <=(nlstate+ndeath); k++){
                   16147:          if (k != i) {
1.319     brouard  16148:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  16149:            printf("%d%d ",i,k);
                   16150:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  16151:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  16152:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  16153:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  16154:              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]));
                   16155:              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  16156:              if(fabs(wald) > 1.96){
1.321     brouard  16157:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  16158:              }else{
                   16159:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   16160:              }
1.324     brouard  16161:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  16162:              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  16163:              jk++; 
                   16164:            }
                   16165:            printf("\n");
                   16166:            fprintf(ficlog,"\n");
1.319     brouard  16167:            fprintf(fichtm, "</tr>\n");
1.225     brouard  16168:          }
                   16169:        }
1.193     brouard  16170:       }
1.203     brouard  16171:     } /* end of hesscov and Wald tests */
1.319     brouard  16172:     fprintf(fichtm,"</table>\n");
1.225     brouard  16173:     
1.203     brouard  16174:     /*  */
1.126     brouard  16175:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   16176:     printf("# Scales (for hessian or gradient estimation)\n");
                   16177:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   16178:     for(i=1,jk=1; i <=nlstate; i++){
                   16179:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  16180:        if (j!=i) {
                   16181:          fprintf(ficres,"%1d%1d",i,j);
                   16182:          printf("%1d%1d",i,j);
                   16183:          fprintf(ficlog,"%1d%1d",i,j);
                   16184:          for(k=1; k<=ncovmodel;k++){
                   16185:            printf(" %.5e",delti[jk]);
                   16186:            fprintf(ficlog," %.5e",delti[jk]);
                   16187:            fprintf(ficres," %.5e",delti[jk]);
                   16188:            jk++;
                   16189:          }
                   16190:          printf("\n");
                   16191:          fprintf(ficlog,"\n");
                   16192:          fprintf(ficres,"\n");
                   16193:        }
1.126     brouard  16194:       }
                   16195:     }
                   16196:     
                   16197:     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  16198:     if(mle >= 1) /* Too big for the screen */
1.126     brouard  16199:       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");
                   16200:     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");
                   16201:     /* # 121 Var(a12)\n\ */
                   16202:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   16203:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   16204:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   16205:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   16206:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   16207:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   16208:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   16209:     
                   16210:     
                   16211:     /* Just to have a covariance matrix which will be more understandable
                   16212:        even is we still don't want to manage dictionary of variables
                   16213:     */
                   16214:     for(itimes=1;itimes<=2;itimes++){
                   16215:       jj=0;
                   16216:       for(i=1; i <=nlstate; i++){
1.225     brouard  16217:        for(j=1; j <=nlstate+ndeath; j++){
                   16218:          if(j==i) continue;
                   16219:          for(k=1; k<=ncovmodel;k++){
                   16220:            jj++;
                   16221:            ca[0]= k+'a'-1;ca[1]='\0';
                   16222:            if(itimes==1){
                   16223:              if(mle>=1)
                   16224:                printf("#%1d%1d%d",i,j,k);
                   16225:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   16226:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   16227:            }else{
                   16228:              if(mle>=1)
                   16229:                printf("%1d%1d%d",i,j,k);
                   16230:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   16231:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   16232:            }
                   16233:            ll=0;
                   16234:            for(li=1;li <=nlstate; li++){
                   16235:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   16236:                if(lj==li) continue;
                   16237:                for(lk=1;lk<=ncovmodel;lk++){
                   16238:                  ll++;
                   16239:                  if(ll<=jj){
                   16240:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   16241:                    if(ll<jj){
                   16242:                      if(itimes==1){
                   16243:                        if(mle>=1)
                   16244:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   16245:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   16246:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   16247:                      }else{
                   16248:                        if(mle>=1)
                   16249:                          printf(" %.5e",matcov[jj][ll]); 
                   16250:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   16251:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   16252:                      }
                   16253:                    }else{
                   16254:                      if(itimes==1){
                   16255:                        if(mle>=1)
                   16256:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   16257:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   16258:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   16259:                      }else{
                   16260:                        if(mle>=1)
                   16261:                          printf(" %.7e",matcov[jj][ll]); 
                   16262:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   16263:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   16264:                      }
                   16265:                    }
                   16266:                  }
                   16267:                } /* end lk */
                   16268:              } /* end lj */
                   16269:            } /* end li */
                   16270:            if(mle>=1)
                   16271:              printf("\n");
                   16272:            fprintf(ficlog,"\n");
                   16273:            fprintf(ficres,"\n");
                   16274:            numlinepar++;
                   16275:          } /* end k*/
                   16276:        } /*end j */
1.126     brouard  16277:       } /* end i */
                   16278:     } /* end itimes */
                   16279:     
                   16280:     fflush(ficlog);
                   16281:     fflush(ficres);
1.225     brouard  16282:     while(fgets(line, MAXLINE, ficpar)) {
                   16283:       /* If line starts with a # it is a comment */
                   16284:       if (line[0] == '#') {
                   16285:        numlinepar++;
                   16286:        fputs(line,stdout);
                   16287:        fputs(line,ficparo);
                   16288:        fputs(line,ficlog);
1.299     brouard  16289:        fputs(line,ficres);
1.225     brouard  16290:        continue;
                   16291:       }else
                   16292:        break;
                   16293:     }
                   16294:     
1.209     brouard  16295:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   16296:     /*   ungetc(c,ficpar); */
                   16297:     /*   fgets(line, MAXLINE, ficpar); */
                   16298:     /*   fputs(line,stdout); */
                   16299:     /*   fputs(line,ficparo); */
                   16300:     /* } */
                   16301:     /* ungetc(c,ficpar); */
1.126     brouard  16302:     
                   16303:     estepm=0;
1.209     brouard  16304:     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  16305:       
                   16306:       if (num_filled != 6) {
                   16307:        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);
                   16308:        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);
                   16309:        goto end;
                   16310:       }
                   16311:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   16312:     }
                   16313:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   16314:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   16315:     
1.209     brouard  16316:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  16317:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   16318:     if (fage <= 2) {
                   16319:       bage = ageminpar;
                   16320:       fage = agemaxpar;
                   16321:     }
                   16322:     
                   16323:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  16324:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   16325:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  16326:                
1.186     brouard  16327:     /* Other stuffs, more or less useful */    
1.254     brouard  16328:     while(fgets(line, MAXLINE, ficpar)) {
                   16329:       /* If line starts with a # it is a comment */
                   16330:       if (line[0] == '#') {
                   16331:        numlinepar++;
                   16332:        fputs(line,stdout);
                   16333:        fputs(line,ficparo);
                   16334:        fputs(line,ficlog);
1.299     brouard  16335:        fputs(line,ficres);
1.254     brouard  16336:        continue;
                   16337:       }else
                   16338:        break;
                   16339:     }
                   16340: 
                   16341:     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){
                   16342:       
                   16343:       if (num_filled != 7) {
                   16344:        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);
                   16345:        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);
                   16346:        goto end;
                   16347:       }
                   16348:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   16349:       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);
                   16350:       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);
                   16351:       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  16352:     }
1.254     brouard  16353: 
                   16354:     while(fgets(line, MAXLINE, ficpar)) {
                   16355:       /* If line starts with a # it is a comment */
                   16356:       if (line[0] == '#') {
                   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;
                   16363:       }else
                   16364:        break;
1.126     brouard  16365:     }
                   16366:     
                   16367:     
                   16368:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   16369:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   16370:     
1.254     brouard  16371:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   16372:       if (num_filled != 1) {
                   16373:        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);
                   16374:        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);
                   16375:        goto end;
                   16376:       }
                   16377:       printf("pop_based=%d\n",popbased);
                   16378:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   16379:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   16380:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   16381:     }
                   16382:      
1.258     brouard  16383:     /* Results */
1.359     brouard  16384:     /* Value of covariate in each resultine will be computed (if product) and sorted according to model rank */
1.332     brouard  16385:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   16386:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  16387:     endishere=0;
1.258     brouard  16388:     nresult=0;
1.308     brouard  16389:     parameterline=0;
1.258     brouard  16390:     do{
                   16391:       if(!fgets(line, MAXLINE, ficpar)){
                   16392:        endishere=1;
1.308     brouard  16393:        parameterline=15;
1.258     brouard  16394:       }else if (line[0] == '#') {
                   16395:        /* If line starts with a # it is a comment */
1.254     brouard  16396:        numlinepar++;
                   16397:        fputs(line,stdout);
                   16398:        fputs(line,ficparo);
                   16399:        fputs(line,ficlog);
1.299     brouard  16400:        fputs(line,ficres);
1.254     brouard  16401:        continue;
1.258     brouard  16402:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   16403:        parameterline=11;
1.296     brouard  16404:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  16405:        parameterline=12;
1.307     brouard  16406:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  16407:        parameterline=13;
1.307     brouard  16408:       }
1.258     brouard  16409:       else{
                   16410:        parameterline=14;
1.254     brouard  16411:       }
1.308     brouard  16412:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  16413:       case 11:
1.296     brouard  16414:        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)){
                   16415:                  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  16416:          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);
                   16417:          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);
                   16418:          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);
                   16419:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  16420:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   16421:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  16422:           prvforecast = 1;
                   16423:        } 
                   16424:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  16425:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   16426:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   16427:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  16428:           prvforecast = 2;
                   16429:        }
                   16430:        else {
                   16431:          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);
                   16432:          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);
                   16433:          goto end;
1.258     brouard  16434:        }
1.254     brouard  16435:        break;
1.258     brouard  16436:       case 12:
1.296     brouard  16437:        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)){
                   16438:           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);
                   16439:          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);
                   16440:          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);
                   16441:          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);
                   16442:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  16443:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   16444:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  16445:           prvbackcast = 1;
                   16446:        } 
                   16447:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  16448:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   16449:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   16450:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  16451:           prvbackcast = 2;
                   16452:        }
                   16453:        else {
                   16454:          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);
                   16455:          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);
                   16456:          goto end;
1.258     brouard  16457:        }
1.230     brouard  16458:        break;
1.258     brouard  16459:       case 13:
1.332     brouard  16460:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  16461:        nresult++; /* Sum of resultlines */
1.342     brouard  16462:        /* printf("Result %d: result:%s\n",nresult, resultlineori); */
1.332     brouard  16463:        /* removefirstspace(&resultlineori); */
                   16464:        
                   16465:        if(strstr(resultlineori,"v") !=0){
                   16466:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   16467:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   16468:          return 1;
                   16469:        }
                   16470:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
1.342     brouard  16471:        /* printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori); */
1.318     brouard  16472:        if(nresult > MAXRESULTLINESPONE-1){
                   16473:          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);
                   16474:          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  16475:          goto end;
                   16476:        }
1.332     brouard  16477:        
1.310     brouard  16478:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  16479:          fprintf(ficparo,"result: %s\n",resultline);
                   16480:          fprintf(ficres,"result: %s\n",resultline);
                   16481:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  16482:        } else
                   16483:          goto end;
1.307     brouard  16484:        break;
                   16485:       case 14:
                   16486:        printf("Error: Unknown command '%s'\n",line);
                   16487:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  16488:        if(line[0] == ' ' || line[0] == '\n'){
                   16489:          printf("It should not be an empty line '%s'\n",line);
                   16490:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   16491:        }         
1.307     brouard  16492:        if(ncovmodel >=2 && nresult==0 ){
                   16493:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   16494:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  16495:        }
1.307     brouard  16496:        /* goto end; */
                   16497:        break;
1.308     brouard  16498:       case 15:
                   16499:        printf("End of resultlines.\n");
                   16500:        fprintf(ficlog,"End of resultlines.\n");
                   16501:        break;
                   16502:       default: /* parameterline =0 */
1.307     brouard  16503:        nresult=1;
                   16504:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  16505:       } /* End switch parameterline */
                   16506:     }while(endishere==0); /* End do */
1.126     brouard  16507:     
1.230     brouard  16508:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  16509:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  16510:     
                   16511:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  16512:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  16513:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  16514: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   16515: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  16516:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  16517: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   16518: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  16519:     }else{
1.270     brouard  16520:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  16521:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   16522:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   16523:       if(prvforecast==1){
                   16524:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   16525:         jprojd=jproj1;
                   16526:         mprojd=mproj1;
                   16527:         anprojd=anproj1;
                   16528:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   16529:         jprojf=jproj2;
                   16530:         mprojf=mproj2;
                   16531:         anprojf=anproj2;
                   16532:       } else if(prvforecast == 2){
                   16533:         dateprojd=dateintmean;
                   16534:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   16535:         dateprojf=dateintmean+yrfproj;
                   16536:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   16537:       }
                   16538:       if(prvbackcast==1){
                   16539:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   16540:         jbackd=jback1;
                   16541:         mbackd=mback1;
                   16542:         anbackd=anback1;
                   16543:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   16544:         jbackf=jback2;
                   16545:         mbackf=mback2;
                   16546:         anbackf=anback2;
                   16547:       } else if(prvbackcast == 2){
                   16548:         datebackd=dateintmean;
                   16549:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   16550:         datebackf=dateintmean-yrbproj;
                   16551:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   16552:       }
                   16553:       
1.350     brouard  16554:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);/* HERE valgrind Tvard*/
1.220     brouard  16555:     }
                   16556:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  16557:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   16558:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  16559:                
1.225     brouard  16560:     /*------------ free_vector  -------------*/
                   16561:     /*  chdir(path); */
1.220     brouard  16562:                
1.215     brouard  16563:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   16564:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   16565:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   16566:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  16567:     free_lvector(num,firstobs,lastobs);
                   16568:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  16569:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   16570:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   16571:     fclose(ficparo);
                   16572:     fclose(ficres);
1.220     brouard  16573:                
                   16574:                
1.186     brouard  16575:     /* Other results (useful)*/
1.220     brouard  16576:                
                   16577:                
1.126     brouard  16578:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  16579:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   16580:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  16581:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  16582:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  16583:     fclose(ficrespl);
                   16584: 
                   16585:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  16586:     /*#include "hpijx.h"*/
1.332     brouard  16587:     /** 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?*/
                   16588:     /* calls hpxij with combination k */
1.180     brouard  16589:     hPijx(p, bage, fage);
1.145     brouard  16590:     fclose(ficrespij);
1.227     brouard  16591:     
1.220     brouard  16592:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  16593:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  16594:     k=1;
1.126     brouard  16595:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  16596:     
1.269     brouard  16597:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   16598:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   16599:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  16600:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  16601:        for(k=1;k<=ncovcombmax;k++)
                   16602:          probs[i][j][k]=0.;
1.269     brouard  16603:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   16604:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  16605:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  16606:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   16607:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  16608:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  16609:          for(k=1;k<=ncovcombmax;k++)
                   16610:            mobaverages[i][j][k]=0.;
1.219     brouard  16611:       mobaverage=mobaverages;
                   16612:       if (mobilav!=0) {
1.235     brouard  16613:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  16614:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  16615:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   16616:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   16617:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   16618:        }
1.269     brouard  16619:       } else if (mobilavproj !=0) {
1.235     brouard  16620:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  16621:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  16622:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   16623:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   16624:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   16625:        }
1.269     brouard  16626:       }else{
                   16627:        printf("Internal error moving average\n");
                   16628:        fflush(stdout);
                   16629:        exit(1);
1.219     brouard  16630:       }
                   16631:     }/* end if moving average */
1.227     brouard  16632:     
1.126     brouard  16633:     /*---------- Forecasting ------------------*/
1.296     brouard  16634:     if(prevfcast==1){ 
                   16635:       /*   /\*    if(stepm ==1){*\/ */
                   16636:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   16637:       /*This done previously after freqsummary.*/
                   16638:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   16639:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   16640:       
                   16641:       /* } else if (prvforecast==2){ */
                   16642:       /*   /\*    if(stepm ==1){*\/ */
                   16643:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   16644:       /* } */
                   16645:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   16646:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  16647:     }
1.269     brouard  16648: 
1.296     brouard  16649:     /* Prevbcasting */
                   16650:     if(prevbcast==1){
1.219     brouard  16651:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   16652:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   16653:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   16654: 
                   16655:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   16656: 
                   16657:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  16658: 
1.219     brouard  16659:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   16660:       fclose(ficresplb);
                   16661: 
1.222     brouard  16662:       hBijx(p, bage, fage, mobaverage);
                   16663:       fclose(ficrespijb);
1.219     brouard  16664: 
1.296     brouard  16665:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   16666:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   16667:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   16668:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   16669:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   16670:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   16671: 
                   16672:       
1.269     brouard  16673:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  16674: 
                   16675:       
1.269     brouard  16676:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  16677:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   16678:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   16679:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  16680:     }    /* end  Prevbcasting */
1.268     brouard  16681:  
1.186     brouard  16682:  
                   16683:     /* ------ Other prevalence ratios------------ */
1.126     brouard  16684: 
1.215     brouard  16685:     free_ivector(wav,1,imx);
                   16686:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   16687:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   16688:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  16689:                
                   16690:                
1.127     brouard  16691:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  16692:                
1.201     brouard  16693:     strcpy(filerese,"E_");
                   16694:     strcat(filerese,fileresu);
1.126     brouard  16695:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   16696:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   16697:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   16698:     }
1.208     brouard  16699:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   16700:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  16701: 
                   16702:     pstamp(ficreseij);
1.219     brouard  16703:                
1.351     brouard  16704:     /* i1=pow(2,cptcoveff); /\* Number of combination of dummy covariates *\/ */
                   16705:     /* if (cptcovn < 1){i1=1;} */
1.235     brouard  16706:     
1.351     brouard  16707:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   16708:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   16709:       /* if(i1 != 1 && TKresult[nres]!= k) */
                   16710:       /*       continue; */
1.219     brouard  16711:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  16712:       printf("\n#****** ");
1.351     brouard  16713:       for(j=1;j<=cptcovs;j++){
                   16714:       /* for(j=1;j<=cptcoveff;j++) { */
                   16715:        /* fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16716:        fprintf(ficreseij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   16717:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   16718:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.235     brouard  16719:       }
                   16720:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.337     brouard  16721:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   16722:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  16723:       }
                   16724:       fprintf(ficreseij,"******\n");
1.235     brouard  16725:       printf("******\n");
1.219     brouard  16726:       
                   16727:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   16728:       oldm=oldms;savm=savms;
1.330     brouard  16729:       /* 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  16730:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  16731:       
1.219     brouard  16732:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  16733:     }
                   16734:     fclose(ficreseij);
1.208     brouard  16735:     printf("done evsij\n");fflush(stdout);
                   16736:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  16737: 
1.218     brouard  16738:                
1.227     brouard  16739:     /*---------- State-specific expectancies and variances ------------*/
1.336     brouard  16740:     /* Should be moved in a function */                
1.201     brouard  16741:     strcpy(filerest,"T_");
                   16742:     strcat(filerest,fileresu);
1.127     brouard  16743:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   16744:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   16745:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   16746:     }
1.208     brouard  16747:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   16748:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  16749:     strcpy(fileresstde,"STDE_");
                   16750:     strcat(fileresstde,fileresu);
1.126     brouard  16751:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  16752:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   16753:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  16754:     }
1.227     brouard  16755:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   16756:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  16757: 
1.201     brouard  16758:     strcpy(filerescve,"CVE_");
                   16759:     strcat(filerescve,fileresu);
1.126     brouard  16760:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  16761:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   16762:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  16763:     }
1.227     brouard  16764:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   16765:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  16766: 
1.201     brouard  16767:     strcpy(fileresv,"V_");
                   16768:     strcat(fileresv,fileresu);
1.126     brouard  16769:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   16770:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   16771:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   16772:     }
1.227     brouard  16773:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   16774:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  16775: 
1.235     brouard  16776:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   16777:     if (cptcovn < 1){i1=1;}
                   16778:     
1.334     brouard  16779:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   16780:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   16781:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   16782:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   16783:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   16784:       /* */
                   16785:       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  16786:        continue;
1.359     brouard  16787:       printf("\n# model=1+age+%s \n#****** Result for:", model);  /* HERE model is empty */
                   16788:       fprintf(ficrest,"\n# model=1+age+%s \n#****** Result for:", model);
                   16789:       fprintf(ficlog,"\n# model=1+age+%s \n#****** Result for:", model);
1.334     brouard  16790:       /* It might not be a good idea to mix dummies and quantitative */
                   16791:       /* 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 *\/ */
                   16792:       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 */
                   16793:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   16794:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   16795:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   16796:         * (V5 is quanti) V4 and V3 are dummies
                   16797:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   16798:         *                                                              l=1 l=2
                   16799:         *                                                           k=1  1   1   0   0
                   16800:         *                                                           k=2  2   1   1   0
                   16801:         *                                                           k=3 [1] [2]  0   1
                   16802:         *                                                           k=4  2   2   1   1
                   16803:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   16804:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   16805:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   16806:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   16807:         */
                   16808:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   16809:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   16810: /* We give up with the combinations!! */
1.342     brouard  16811:        /* if(debugILK) */
                   16812:        /*   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  16813: 
                   16814:        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  16815:          /* 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] */
                   16816:          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  */
                   16817:          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  */
                   16818:          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  16819:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   16820:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   16821:          }else{
                   16822:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   16823:          }
                   16824:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16825:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16826:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   16827:          /* For each selected (single) quantitative value */
1.337     brouard  16828:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   16829:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   16830:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
1.334     brouard  16831:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   16832:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   16833:          }else{
                   16834:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   16835:          }
                   16836:        }else{
                   16837:          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 */
                   16838:          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 */
                   16839:          exit(1);
                   16840:        }
1.335     brouard  16841:       } /* End loop for each variable in the resultline */
1.334     brouard  16842:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   16843:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   16844:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   16845:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   16846:       /* }      */
1.208     brouard  16847:       fprintf(ficrest,"******\n");
1.227     brouard  16848:       fprintf(ficlog,"******\n");
                   16849:       printf("******\n");
1.208     brouard  16850:       
                   16851:       fprintf(ficresstdeij,"\n#****** ");
                   16852:       fprintf(ficrescveij,"\n#****** ");
1.337     brouard  16853:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
                   16854:       /* But it won't be sorted and depends on how the resultline is ordered */
1.225     brouard  16855:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  16856:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   16857:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16858:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16859:       }
                   16860:       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  16861:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   16862:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  16863:       }        
1.208     brouard  16864:       fprintf(ficresstdeij,"******\n");
                   16865:       fprintf(ficrescveij,"******\n");
                   16866:       
                   16867:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  16868:       /* pstamp(ficresvij); */
1.225     brouard  16869:       for(j=1;j<=cptcoveff;j++) 
1.335     brouard  16870:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   16871:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  16872:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  16873:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
1.337     brouard  16874:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  16875:       }        
1.208     brouard  16876:       fprintf(ficresvij,"******\n");
                   16877:       
                   16878:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   16879:       oldm=oldms;savm=savms;
1.235     brouard  16880:       printf(" cvevsij ");
                   16881:       fprintf(ficlog, " cvevsij ");
                   16882:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  16883:       printf(" end cvevsij \n ");
                   16884:       fprintf(ficlog, " end cvevsij \n ");
                   16885:       
                   16886:       /*
                   16887:        */
                   16888:       /* goto endfree; */
                   16889:       
                   16890:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   16891:       pstamp(ficrest);
                   16892:       
1.269     brouard  16893:       epj=vector(1,nlstate+1);
1.208     brouard  16894:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  16895:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   16896:        cptcod= 0; /* To be deleted */
1.360     brouard  16897:        printf("varevsij vpopbased=%d popbased=%d \n",vpopbased,popbased);
                   16898:        fprintf(ficlog, "varevsij vpopbased=%d popbased=%d \n",vpopbased,popbased);
1.361     brouard  16899:        /* 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 */
                   16900:        /* Depending of popbased which changes the prevalences, either cross-sectional or period */
1.235     brouard  16901:        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  16902:        fprintf(ficrest,"# Total life expectancy with std error and decomposition into time to be expected in each state\n\
                   16903: #  (these are weighted average of eij where weights are ");
1.227     brouard  16904:        if(vpopbased==1)
1.360     brouard  16905:          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  16906:        else
1.360     brouard  16907:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each state) \n");
                   16908:        fprintf(ficrest,"# with proportions of time spent in each state with standard error (on the right of the table.\n ");
1.335     brouard  16909:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  16910:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
1.360     brouard  16911:        for (i=1;i<=nlstate;i++) fprintf(ficrest," %% e.%d/e.. (std) ",i);
1.227     brouard  16912:        fprintf(ficrest,"\n");
                   16913:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  16914:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   16915:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  16916:        for(age=bage; age <=fage ;age++){
1.235     brouard  16917:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  16918:          if (vpopbased==1) {
                   16919:            if(mobilav ==0){
                   16920:              for(i=1; i<=nlstate;i++)
                   16921:                prlim[i][i]=probs[(int)age][i][k];
                   16922:            }else{ /* mobilav */ 
                   16923:              for(i=1; i<=nlstate;i++)
                   16924:                prlim[i][i]=mobaverage[(int)age][i][k];
                   16925:            }
                   16926:          }
1.219     brouard  16927:          
1.227     brouard  16928:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   16929:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   16930:          /* printf(" age %4.0f ",age); */
                   16931:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   16932:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   16933:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   16934:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   16935:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   16936:            }
1.361     brouard  16937:            epj[nlstate+1] +=epj[j]; /* epp=sum_j epj = sum_j sum_i w_i e_ij */
1.227     brouard  16938:          }
                   16939:          /* printf(" age %4.0f \n",age); */
1.219     brouard  16940:          
1.361     brouard  16941:          for(i=1, vepp=0.;i <=nlstate;i++)  /* Variance of total life expectancy e.. */
1.227     brouard  16942:            for(j=1;j <=nlstate;j++)
1.361     brouard  16943:              vepp += vareij[i][j][(int)age]; /* sum_i sum_j cov(e.i, e.j) = var(e..) */
1.227     brouard  16944:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
1.361     brouard  16945:          /* vareij[i][j] is the covariance  cov(e.i, e.j) and vareij[j][j] is the variance  of e.j  */
1.227     brouard  16946:          for(j=1;j <=nlstate;j++){
                   16947:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   16948:          }
1.360     brouard  16949:          /* And proportion of time spent in state j */
                   16950:          /* $$ 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  16951:           /* \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}) */
                   16952:          /* \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})*/
                   16953:          /*\mu_x = epj[j], \sigma^2_x = vareij[j][j][(int)age] and \mu_y=epj[nlstate+1], \sigma^2_y=vepp \sigmaxy= */
                   16954:          /* vareij[j][j][(int)age]/epj[nlstate+1]^2 + vepp/epj[nlstate+1]^4 */
1.360     brouard  16955:          for(j=1;j <=nlstate;j++){
                   16956:            /* 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  16957:            /* 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] )); */
                   16958:            
                   16959:            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) */
                   16960:              stdpercent += vareij[i][j][(int)age];
                   16961:            }
                   16962:            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]);
                   16963:            /* 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 */
                   16964:            /* 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] )); */
                   16965:            fprintf(ficrest," %7.3f (%7.3f)", epj[j]/epj[nlstate+1], sqrt(stdpercent));
1.360     brouard  16966:          }
1.227     brouard  16967:          fprintf(ficrest,"\n");
                   16968:        }
1.208     brouard  16969:       } /* End vpopbased */
1.269     brouard  16970:       free_vector(epj,1,nlstate+1);
1.208     brouard  16971:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   16972:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  16973:       printf("done selection\n");fflush(stdout);
                   16974:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  16975:       
1.335     brouard  16976:     } /* End k selection or end covariate selection for nres */
1.227     brouard  16977: 
                   16978:     printf("done State-specific expectancies\n");fflush(stdout);
                   16979:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   16980: 
1.335     brouard  16981:     /* variance-covariance of forward period prevalence */
1.269     brouard  16982:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  16983: 
1.227     brouard  16984:     
1.290     brouard  16985:     free_vector(weight,firstobs,lastobs);
1.351     brouard  16986:     free_imatrix(Tvardk,0,NCOVMAX,1,2);
1.227     brouard  16987:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  16988:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   16989:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   16990:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   16991:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  16992:     free_ivector(tab,1,NCOVMAX);
                   16993:     fclose(ficresstdeij);
                   16994:     fclose(ficrescveij);
                   16995:     fclose(ficresvij);
                   16996:     fclose(ficrest);
                   16997:     fclose(ficpar);
                   16998:     
                   16999:     
1.126     brouard  17000:     /*---------- End : free ----------------*/
1.219     brouard  17001:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  17002:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   17003:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  17004:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   17005:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  17006:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  17007:   /* endfree:*/
1.359     brouard  17008:   if(mle!=-3) free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
1.227     brouard  17009:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   17010:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   17011:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.341     brouard  17012:   /* if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs); */
                   17013:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);
1.290     brouard  17014:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   17015:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   17016:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  17017:   free_matrix(matcov,1,npar,1,npar);
                   17018:   free_matrix(hess,1,npar,1,npar);
                   17019:   /*free_vector(delti,1,npar);*/
                   17020:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   17021:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  17022:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  17023:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   17024:   
                   17025:   free_ivector(ncodemax,1,NCOVMAX);
                   17026:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   17027:   free_ivector(Dummy,-1,NCOVMAX);
                   17028:   free_ivector(Fixed,-1,NCOVMAX);
1.349     brouard  17029:   free_ivector(DummyV,-1,NCOVMAX);
                   17030:   free_ivector(FixedV,-1,NCOVMAX);
1.227     brouard  17031:   free_ivector(Typevar,-1,NCOVMAX);
                   17032:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  17033:   free_ivector(TvarsQ,1,NCOVMAX);
                   17034:   free_ivector(TvarsQind,1,NCOVMAX);
                   17035:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  17036:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  17037:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  17038:   free_ivector(TvarFD,1,NCOVMAX);
                   17039:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  17040:   free_ivector(TvarF,1,NCOVMAX);
                   17041:   free_ivector(TvarFind,1,NCOVMAX);
                   17042:   free_ivector(TvarV,1,NCOVMAX);
                   17043:   free_ivector(TvarVind,1,NCOVMAX);
                   17044:   free_ivector(TvarA,1,NCOVMAX);
                   17045:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  17046:   free_ivector(TvarFQ,1,NCOVMAX);
                   17047:   free_ivector(TvarFQind,1,NCOVMAX);
                   17048:   free_ivector(TvarVD,1,NCOVMAX);
                   17049:   free_ivector(TvarVDind,1,NCOVMAX);
                   17050:   free_ivector(TvarVQ,1,NCOVMAX);
                   17051:   free_ivector(TvarVQind,1,NCOVMAX);
1.349     brouard  17052:   free_ivector(TvarAVVA,1,NCOVMAX);
                   17053:   free_ivector(TvarAVVAind,1,NCOVMAX);
                   17054:   free_ivector(TvarVVA,1,NCOVMAX);
                   17055:   free_ivector(TvarVVAind,1,NCOVMAX);
1.339     brouard  17056:   free_ivector(TvarVV,1,NCOVMAX);
                   17057:   free_ivector(TvarVVind,1,NCOVMAX);
                   17058:   
1.230     brouard  17059:   free_ivector(Tvarsel,1,NCOVMAX);
                   17060:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  17061:   free_ivector(Tposprod,1,NCOVMAX);
                   17062:   free_ivector(Tprod,1,NCOVMAX);
                   17063:   free_ivector(Tvaraff,1,NCOVMAX);
1.338     brouard  17064:   free_ivector(invalidvarcomb,0,ncovcombmax);
1.227     brouard  17065:   free_ivector(Tage,1,NCOVMAX);
                   17066:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  17067:   free_ivector(TmodelInvind,1,NCOVMAX);
                   17068:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  17069: 
1.359     brouard  17070:   /* free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /\* Could be elsewhere ?*\/ */
1.332     brouard  17071: 
1.227     brouard  17072:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   17073:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  17074:   fflush(fichtm);
                   17075:   fflush(ficgp);
                   17076:   
1.227     brouard  17077:   
1.126     brouard  17078:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  17079:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   17080:     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  17081:   }else{
                   17082:     printf("End of Imach\n");
                   17083:     fprintf(ficlog,"End of Imach\n");
                   17084:   }
                   17085:   printf("See log file on %s\n",filelog);
                   17086:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  17087:   /*(void) gettimeofday(&end_time,&tzp);*/
                   17088:   rend_time = time(NULL);  
                   17089:   end_time = *localtime(&rend_time);
                   17090:   /* tml = *localtime(&end_time.tm_sec); */
                   17091:   strcpy(strtend,asctime(&end_time));
1.126     brouard  17092:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   17093:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  17094:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  17095:   
1.157     brouard  17096:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   17097:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   17098:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  17099:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   17100: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   17101:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   17102:   fclose(fichtm);
                   17103:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   17104:   fclose(fichtmcov);
                   17105:   fclose(ficgp);
                   17106:   fclose(ficlog);
                   17107:   /*------ End -----------*/
1.227     brouard  17108:   
1.281     brouard  17109: 
                   17110: /* Executes gnuplot */
1.227     brouard  17111:   
                   17112:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  17113: #ifdef WIN32
1.227     brouard  17114:   if (_chdir(pathcd) != 0)
                   17115:     printf("Can't move to directory %s!\n",path);
                   17116:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  17117: #else
1.227     brouard  17118:     if(chdir(pathcd) != 0)
                   17119:       printf("Can't move to directory %s!\n", path);
                   17120:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  17121: #endif 
1.126     brouard  17122:     printf("Current directory %s!\n",pathcd);
                   17123:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   17124:   sprintf(plotcmd,"gnuplot");
1.157     brouard  17125: #ifdef _WIN32
1.126     brouard  17126:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   17127: #endif
                   17128:   if(!stat(plotcmd,&info)){
1.158     brouard  17129:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  17130:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  17131:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  17132:     }else
                   17133:       strcpy(pplotcmd,plotcmd);
1.157     brouard  17134: #ifdef __unix
1.126     brouard  17135:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   17136:     if(!stat(plotcmd,&info)){
1.158     brouard  17137:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  17138:     }else
                   17139:       strcpy(pplotcmd,plotcmd);
                   17140: #endif
                   17141:   }else
                   17142:     strcpy(pplotcmd,plotcmd);
                   17143:   
                   17144:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  17145:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  17146:   strcpy(pplotcmd,plotcmd);
1.227     brouard  17147:   
1.126     brouard  17148:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  17149:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  17150:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  17151:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  17152:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  17153:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  17154:       strcpy(plotcmd,pplotcmd);
                   17155:     }
1.126     brouard  17156:   }
1.158     brouard  17157:   printf(" Successful, please wait...");
1.126     brouard  17158:   while (z[0] != 'q') {
                   17159:     /* chdir(path); */
1.154     brouard  17160:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  17161:     scanf("%s",z);
                   17162: /*     if (z[0] == 'c') system("./imach"); */
                   17163:     if (z[0] == 'e') {
1.158     brouard  17164: #ifdef __APPLE__
1.152     brouard  17165:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  17166: #elif __linux
                   17167:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  17168: #else
1.152     brouard  17169:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  17170: #endif
                   17171:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   17172:       system(pplotcmd);
1.126     brouard  17173:     }
                   17174:     else if (z[0] == 'g') system(plotcmd);
                   17175:     else if (z[0] == 'q') exit(0);
                   17176:   }
1.227     brouard  17177: end:
1.126     brouard  17178:   while (z[0] != 'q') {
1.195     brouard  17179:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  17180:     scanf("%s",z);
                   17181:   }
1.283     brouard  17182:   printf("End\n");
1.282     brouard  17183:   exit(0);
1.126     brouard  17184: }

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