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

1.360   ! brouard     1: /* $Id: imach.c,v 1.359 2024/04/24 21:21:17 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.360   ! brouard     3:   $Log: imach.c,v $
        !             4:   Revision 1.359  2024/04/24 21:21:17  brouard
        !             5:   Summary: First IMaCh version using Brent Praxis software based on Buckhardt and Gegenfürtner C codes
        !             6: 
1.359     brouard     7:   Revision 1.6  2024/04/24 21:10:29  brouard
                      8:   Summary: First IMaCh version using Brent Praxis software based on Buckhardt and Gegenfürtner C codes
1.358     brouard     9: 
1.359     brouard    10:   Revision 1.5  2023/10/09 09:10:01  brouard
                     11:   Summary: trying to reconsider
1.357     brouard    12: 
1.359     brouard    13:   Revision 1.4  2023/06/22 12:50:51  brouard
                     14:   Summary: stil on going
1.357     brouard    15: 
1.359     brouard    16:   Revision 1.3  2023/06/22 11:28:07  brouard
                     17:   *** empty log message ***
1.356     brouard    18: 
1.359     brouard    19:   Revision 1.2  2023/06/22 11:22:40  brouard
                     20:   Summary: with svd but not working yet
1.355     brouard    21: 
1.354     brouard    22:   Revision 1.353  2023/05/08 18:48:22  brouard
                     23:   *** empty log message ***
                     24: 
1.353     brouard    25:   Revision 1.352  2023/04/29 10:46:21  brouard
                     26:   *** empty log message ***
                     27: 
1.352     brouard    28:   Revision 1.351  2023/04/29 10:43:47  brouard
                     29:   Summary: 099r45
                     30: 
1.351     brouard    31:   Revision 1.350  2023/04/24 11:38:06  brouard
                     32:   *** empty log message ***
                     33: 
1.350     brouard    34:   Revision 1.349  2023/01/31 09:19:37  brouard
                     35:   Summary: Improvements in models with age*Vn*Vm
                     36: 
1.348     brouard    37:   Revision 1.347  2022/09/18 14:36:44  brouard
                     38:   Summary: version 0.99r42
                     39: 
1.347     brouard    40:   Revision 1.346  2022/09/16 13:52:36  brouard
                     41:   * src/imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     42: 
1.346     brouard    43:   Revision 1.345  2022/09/16 13:40:11  brouard
                     44:   Summary: Version 0.99r41
                     45: 
                     46:   * imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     47: 
1.345     brouard    48:   Revision 1.344  2022/09/14 19:33:30  brouard
                     49:   Summary: version 0.99r40
                     50: 
                     51:   * imach.c (Module): Fixing names of variables in T_ (thanks to Feinuo)
                     52: 
1.344     brouard    53:   Revision 1.343  2022/09/14 14:22:16  brouard
                     54:   Summary: version 0.99r39
                     55: 
                     56:   * imach.c (Module): Version 0.99r39 with colored dummy covariates
                     57:   (fixed or time varying), using new last columns of
                     58:   ILK_parameter.txt file.
                     59: 
1.343     brouard    60:   Revision 1.342  2022/09/11 19:54:09  brouard
                     61:   Summary: 0.99r38
                     62: 
                     63:   * imach.c (Module): Adding timevarying products of any kinds,
                     64:   should work before shifting cotvar from ncovcol+nqv columns in
                     65:   order to have a correspondance between the column of cotvar and
                     66:   the id of column.
                     67:   (Module): Some cleaning and adding covariates in ILK.txt
                     68: 
1.342     brouard    69:   Revision 1.341  2022/09/11 07:58:42  brouard
                     70:   Summary: Version 0.99r38
                     71: 
                     72:   After adding change in cotvar.
                     73: 
1.341     brouard    74:   Revision 1.340  2022/09/11 07:53:11  brouard
                     75:   Summary: Version imach 0.99r37
                     76: 
                     77:   * imach.c (Module): Adding timevarying products of any kinds,
                     78:   should work before shifting cotvar from ncovcol+nqv columns in
                     79:   order to have a correspondance between the column of cotvar and
                     80:   the id of column.
                     81: 
1.340     brouard    82:   Revision 1.339  2022/09/09 17:55:22  brouard
                     83:   Summary: version 0.99r37
                     84: 
                     85:   * imach.c (Module): Many improvements for fixing products of fixed
                     86:   timevarying as well as fixed * fixed, and test with quantitative
                     87:   covariate.
                     88: 
1.339     brouard    89:   Revision 1.338  2022/09/04 17:40:33  brouard
                     90:   Summary: 0.99r36
                     91: 
                     92:   * imach.c (Module): Now the easy runs i.e. without result or
                     93:   model=1+age only did not work. The defautl combination should be 1
                     94:   and not 0 because everything hasn't been tranformed yet.
                     95: 
1.338     brouard    96:   Revision 1.337  2022/09/02 14:26:02  brouard
                     97:   Summary: version 0.99r35
                     98: 
                     99:   * src/imach.c: Version 0.99r35 because it outputs same results with
                    100:   1+age+V1+V1*age for females and 1+age for females only
                    101:   (education=1 noweight)
                    102: 
1.337     brouard   103:   Revision 1.336  2022/08/31 09:52:36  brouard
                    104:   *** empty log message ***
                    105: 
1.336     brouard   106:   Revision 1.335  2022/08/31 08:23:16  brouard
                    107:   Summary: improvements...
                    108: 
1.335     brouard   109:   Revision 1.334  2022/08/25 09:08:41  brouard
                    110:   Summary: In progress for quantitative
                    111: 
1.334     brouard   112:   Revision 1.333  2022/08/21 09:10:30  brouard
                    113:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                    114:   reassigning covariates: my first idea was that people will always
                    115:   use the first covariate V1 into the model but in fact they are
                    116:   producing data with many covariates and can use an equation model
                    117:   with some of the covariate; it means that in a model V2+V3 instead
                    118:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    119:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    120:   the equation model is restricted to two variables only (V2, V3)
                    121:   and the combination for V2 should be codtabm(k,1) instead of
                    122:   (codtabm(k,2), and the code should be
                    123:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    124:   made. All of these should be simplified once a day like we did in
                    125:   hpxij() for example by using precov[nres] which is computed in
                    126:   decoderesult for each nres of each resultline. Loop should be done
                    127:   on the equation model globally by distinguishing only product with
                    128:   age (which are changing with age) and no more on type of
                    129:   covariates, single dummies, single covariates.
                    130: 
1.333     brouard   131:   Revision 1.332  2022/08/21 09:06:25  brouard
                    132:   Summary: Version 0.99r33
                    133: 
                    134:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                    135:   reassigning covariates: my first idea was that people will always
                    136:   use the first covariate V1 into the model but in fact they are
                    137:   producing data with many covariates and can use an equation model
                    138:   with some of the covariate; it means that in a model V2+V3 instead
                    139:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    140:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    141:   the equation model is restricted to two variables only (V2, V3)
                    142:   and the combination for V2 should be codtabm(k,1) instead of
                    143:   (codtabm(k,2), and the code should be
                    144:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    145:   made. All of these should be simplified once a day like we did in
                    146:   hpxij() for example by using precov[nres] which is computed in
                    147:   decoderesult for each nres of each resultline. Loop should be done
                    148:   on the equation model globally by distinguishing only product with
                    149:   age (which are changing with age) and no more on type of
                    150:   covariates, single dummies, single covariates.
                    151: 
1.332     brouard   152:   Revision 1.331  2022/08/07 05:40:09  brouard
                    153:   *** empty log message ***
                    154: 
1.331     brouard   155:   Revision 1.330  2022/08/06 07:18:25  brouard
                    156:   Summary: last 0.99r31
                    157: 
                    158:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                    159: 
1.330     brouard   160:   Revision 1.329  2022/08/03 17:29:54  brouard
                    161:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                    162: 
1.329     brouard   163:   Revision 1.328  2022/07/27 17:40:48  brouard
                    164:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                    165: 
1.328     brouard   166:   Revision 1.327  2022/07/27 14:47:35  brouard
                    167:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                    168: 
1.327     brouard   169:   Revision 1.326  2022/07/26 17:33:55  brouard
                    170:   Summary: some test with nres=1
                    171: 
1.326     brouard   172:   Revision 1.325  2022/07/25 14:27:23  brouard
                    173:   Summary: r30
                    174: 
                    175:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                    176:   coredumped, revealed by Feiuno, thank you.
                    177: 
1.325     brouard   178:   Revision 1.324  2022/07/23 17:44:26  brouard
                    179:   *** empty log message ***
                    180: 
1.324     brouard   181:   Revision 1.323  2022/07/22 12:30:08  brouard
                    182:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    183: 
1.323     brouard   184:   Revision 1.322  2022/07/22 12:27:48  brouard
                    185:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    186: 
1.322     brouard   187:   Revision 1.321  2022/07/22 12:04:24  brouard
                    188:   Summary: r28
                    189: 
                    190:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    191: 
1.321     brouard   192:   Revision 1.320  2022/06/02 05:10:11  brouard
                    193:   *** empty log message ***
                    194: 
1.320     brouard   195:   Revision 1.319  2022/06/02 04:45:11  brouard
                    196:   * imach.c (Module): Adding the Wald tests from the log to the main
                    197:   htm for better display of the maximum likelihood estimators.
                    198: 
1.319     brouard   199:   Revision 1.318  2022/05/24 08:10:59  brouard
                    200:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                    201:   of confidencce intervals with product in the equation modelC
                    202: 
1.318     brouard   203:   Revision 1.317  2022/05/15 15:06:23  brouard
                    204:   * imach.c (Module):  Some minor improvements
                    205: 
1.317     brouard   206:   Revision 1.316  2022/05/11 15:11:31  brouard
                    207:   Summary: r27
                    208: 
1.316     brouard   209:   Revision 1.315  2022/05/11 15:06:32  brouard
                    210:   *** empty log message ***
                    211: 
1.315     brouard   212:   Revision 1.314  2022/04/13 17:43:09  brouard
                    213:   * imach.c (Module): Adding link to text data files
                    214: 
1.314     brouard   215:   Revision 1.313  2022/04/11 15:57:42  brouard
                    216:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    217: 
1.313     brouard   218:   Revision 1.312  2022/04/05 21:24:39  brouard
                    219:   *** empty log message ***
                    220: 
1.312     brouard   221:   Revision 1.311  2022/04/05 21:03:51  brouard
                    222:   Summary: Fixed quantitative covariates
                    223: 
                    224:          Fixed covariates (dummy or quantitative)
                    225:        with missing values have never been allowed but are ERRORS and
                    226:        program quits. Standard deviations of fixed covariates were
                    227:        wrongly computed. Mean and standard deviations of time varying
                    228:        covariates are still not computed.
                    229: 
1.311     brouard   230:   Revision 1.310  2022/03/17 08:45:53  brouard
                    231:   Summary: 99r25
                    232: 
                    233:   Improving detection of errors: result lines should be compatible with
                    234:   the model.
                    235: 
1.310     brouard   236:   Revision 1.309  2021/05/20 12:39:14  brouard
                    237:   Summary: Version 0.99r24
                    238: 
1.309     brouard   239:   Revision 1.308  2021/03/31 13:11:57  brouard
                    240:   Summary: Version 0.99r23
                    241: 
                    242: 
                    243:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    244: 
1.308     brouard   245:   Revision 1.307  2021/03/08 18:11:32  brouard
                    246:   Summary: 0.99r22 fixed bug on result:
                    247: 
1.307     brouard   248:   Revision 1.306  2021/02/20 15:44:02  brouard
                    249:   Summary: Version 0.99r21
                    250: 
                    251:   * imach.c (Module): Fix bug on quitting after result lines!
                    252:   (Module): Version 0.99r21
                    253: 
1.306     brouard   254:   Revision 1.305  2021/02/20 15:28:30  brouard
                    255:   * imach.c (Module): Fix bug on quitting after result lines!
                    256: 
1.305     brouard   257:   Revision 1.304  2021/02/12 11:34:20  brouard
                    258:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    259: 
1.304     brouard   260:   Revision 1.303  2021/02/11 19:50:15  brouard
                    261:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    262: 
1.303     brouard   263:   Revision 1.302  2020/02/22 21:00:05  brouard
                    264:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    265:   and life table from the data without any state)
                    266: 
1.302     brouard   267:   Revision 1.301  2019/06/04 13:51:20  brouard
                    268:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    269: 
1.301     brouard   270:   Revision 1.300  2019/05/22 19:09:45  brouard
                    271:   Summary: version 0.99r19 of May 2019
                    272: 
1.300     brouard   273:   Revision 1.299  2019/05/22 18:37:08  brouard
                    274:   Summary: Cleaned 0.99r19
                    275: 
1.299     brouard   276:   Revision 1.298  2019/05/22 18:19:56  brouard
                    277:   *** empty log message ***
                    278: 
1.298     brouard   279:   Revision 1.297  2019/05/22 17:56:10  brouard
                    280:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    281: 
1.297     brouard   282:   Revision 1.296  2019/05/20 13:03:18  brouard
                    283:   Summary: Projection syntax simplified
                    284: 
                    285: 
                    286:   We can now start projections, forward or backward, from the mean date
                    287:   of inteviews up to or down to a number of years of projection:
                    288:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    289:   or
                    290:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    291:   or
                    292:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    293:   or
                    294:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    295: 
1.296     brouard   296:   Revision 1.295  2019/05/18 09:52:50  brouard
                    297:   Summary: doxygen tex bug
                    298: 
1.295     brouard   299:   Revision 1.294  2019/05/16 14:54:33  brouard
                    300:   Summary: There was some wrong lines added
                    301: 
1.294     brouard   302:   Revision 1.293  2019/05/09 15:17:34  brouard
                    303:   *** empty log message ***
                    304: 
1.293     brouard   305:   Revision 1.292  2019/05/09 14:17:20  brouard
                    306:   Summary: Some updates
                    307: 
1.292     brouard   308:   Revision 1.291  2019/05/09 13:44:18  brouard
                    309:   Summary: Before ncovmax
                    310: 
1.291     brouard   311:   Revision 1.290  2019/05/09 13:39:37  brouard
                    312:   Summary: 0.99r18 unlimited number of individuals
                    313: 
                    314:   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.
                    315: 
1.290     brouard   316:   Revision 1.289  2018/12/13 09:16:26  brouard
                    317:   Summary: Bug for young ages (<-30) will be in r17
                    318: 
1.289     brouard   319:   Revision 1.288  2018/05/02 20:58:27  brouard
                    320:   Summary: Some bugs fixed
                    321: 
1.288     brouard   322:   Revision 1.287  2018/05/01 17:57:25  brouard
                    323:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    324: 
1.287     brouard   325:   Revision 1.286  2018/04/27 14:27:04  brouard
                    326:   Summary: some minor bugs
                    327: 
1.286     brouard   328:   Revision 1.285  2018/04/21 21:02:16  brouard
                    329:   Summary: Some bugs fixed, valgrind tested
                    330: 
1.285     brouard   331:   Revision 1.284  2018/04/20 05:22:13  brouard
                    332:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    333: 
1.284     brouard   334:   Revision 1.283  2018/04/19 14:49:16  brouard
                    335:   Summary: Some minor bugs fixed
                    336: 
1.283     brouard   337:   Revision 1.282  2018/02/27 22:50:02  brouard
                    338:   *** empty log message ***
                    339: 
1.282     brouard   340:   Revision 1.281  2018/02/27 19:25:23  brouard
                    341:   Summary: Adding second argument for quitting
                    342: 
1.281     brouard   343:   Revision 1.280  2018/02/21 07:58:13  brouard
                    344:   Summary: 0.99r15
                    345: 
                    346:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    347: 
1.280     brouard   348:   Revision 1.279  2017/07/20 13:35:01  brouard
                    349:   Summary: temporary working
                    350: 
1.279     brouard   351:   Revision 1.278  2017/07/19 14:09:02  brouard
                    352:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    353: 
1.278     brouard   354:   Revision 1.277  2017/07/17 08:53:49  brouard
                    355:   Summary: BOM files can be read now
                    356: 
1.277     brouard   357:   Revision 1.276  2017/06/30 15:48:31  brouard
                    358:   Summary: Graphs improvements
                    359: 
1.276     brouard   360:   Revision 1.275  2017/06/30 13:39:33  brouard
                    361:   Summary: Saito's color
                    362: 
1.275     brouard   363:   Revision 1.274  2017/06/29 09:47:08  brouard
                    364:   Summary: Version 0.99r14
                    365: 
1.274     brouard   366:   Revision 1.273  2017/06/27 11:06:02  brouard
                    367:   Summary: More documentation on projections
                    368: 
1.273     brouard   369:   Revision 1.272  2017/06/27 10:22:40  brouard
                    370:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    371: 
1.272     brouard   372:   Revision 1.271  2017/06/27 10:17:50  brouard
                    373:   Summary: Some bug with rint
                    374: 
1.271     brouard   375:   Revision 1.270  2017/05/24 05:45:29  brouard
                    376:   *** empty log message ***
                    377: 
1.270     brouard   378:   Revision 1.269  2017/05/23 08:39:25  brouard
                    379:   Summary: Code into subroutine, cleanings
                    380: 
1.269     brouard   381:   Revision 1.268  2017/05/18 20:09:32  brouard
                    382:   Summary: backprojection and confidence intervals of backprevalence
                    383: 
1.268     brouard   384:   Revision 1.267  2017/05/13 10:25:05  brouard
                    385:   Summary: temporary save for backprojection
                    386: 
1.267     brouard   387:   Revision 1.266  2017/05/13 07:26:12  brouard
                    388:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    389: 
1.266     brouard   390:   Revision 1.265  2017/04/26 16:22:11  brouard
                    391:   Summary: imach 0.99r13 Some bugs fixed
                    392: 
1.265     brouard   393:   Revision 1.264  2017/04/26 06:01:29  brouard
                    394:   Summary: Labels in graphs
                    395: 
1.264     brouard   396:   Revision 1.263  2017/04/24 15:23:15  brouard
                    397:   Summary: to save
                    398: 
1.263     brouard   399:   Revision 1.262  2017/04/18 16:48:12  brouard
                    400:   *** empty log message ***
                    401: 
1.262     brouard   402:   Revision 1.261  2017/04/05 10:14:09  brouard
                    403:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    404: 
1.261     brouard   405:   Revision 1.260  2017/04/04 17:46:59  brouard
                    406:   Summary: Gnuplot indexations fixed (humm)
                    407: 
1.260     brouard   408:   Revision 1.259  2017/04/04 13:01:16  brouard
                    409:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    410: 
1.259     brouard   411:   Revision 1.258  2017/04/03 10:17:47  brouard
                    412:   Summary: Version 0.99r12
                    413: 
                    414:   Some cleanings, conformed with updated documentation.
                    415: 
1.258     brouard   416:   Revision 1.257  2017/03/29 16:53:30  brouard
                    417:   Summary: Temp
                    418: 
1.257     brouard   419:   Revision 1.256  2017/03/27 05:50:23  brouard
                    420:   Summary: Temporary
                    421: 
1.256     brouard   422:   Revision 1.255  2017/03/08 16:02:28  brouard
                    423:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    424: 
1.255     brouard   425:   Revision 1.254  2017/03/08 07:13:00  brouard
                    426:   Summary: Fixing data parameter line
                    427: 
1.254     brouard   428:   Revision 1.253  2016/12/15 11:59:41  brouard
                    429:   Summary: 0.99 in progress
                    430: 
1.253     brouard   431:   Revision 1.252  2016/09/15 21:15:37  brouard
                    432:   *** empty log message ***
                    433: 
1.252     brouard   434:   Revision 1.251  2016/09/15 15:01:13  brouard
                    435:   Summary: not working
                    436: 
1.251     brouard   437:   Revision 1.250  2016/09/08 16:07:27  brouard
                    438:   Summary: continue
                    439: 
1.250     brouard   440:   Revision 1.249  2016/09/07 17:14:18  brouard
                    441:   Summary: Starting values from frequencies
                    442: 
1.249     brouard   443:   Revision 1.248  2016/09/07 14:10:18  brouard
                    444:   *** empty log message ***
                    445: 
1.248     brouard   446:   Revision 1.247  2016/09/02 11:11:21  brouard
                    447:   *** empty log message ***
                    448: 
1.247     brouard   449:   Revision 1.246  2016/09/02 08:49:22  brouard
                    450:   *** empty log message ***
                    451: 
1.246     brouard   452:   Revision 1.245  2016/09/02 07:25:01  brouard
                    453:   *** empty log message ***
                    454: 
1.245     brouard   455:   Revision 1.244  2016/09/02 07:17:34  brouard
                    456:   *** empty log message ***
                    457: 
1.244     brouard   458:   Revision 1.243  2016/09/02 06:45:35  brouard
                    459:   *** empty log message ***
                    460: 
1.243     brouard   461:   Revision 1.242  2016/08/30 15:01:20  brouard
                    462:   Summary: Fixing a lots
                    463: 
1.242     brouard   464:   Revision 1.241  2016/08/29 17:17:25  brouard
                    465:   Summary: gnuplot problem in Back projection to fix
                    466: 
1.241     brouard   467:   Revision 1.240  2016/08/29 07:53:18  brouard
                    468:   Summary: Better
                    469: 
1.240     brouard   470:   Revision 1.239  2016/08/26 15:51:03  brouard
                    471:   Summary: Improvement in Powell output in order to copy and paste
                    472: 
                    473:   Author:
                    474: 
1.239     brouard   475:   Revision 1.238  2016/08/26 14:23:35  brouard
                    476:   Summary: Starting tests of 0.99
                    477: 
1.238     brouard   478:   Revision 1.237  2016/08/26 09:20:19  brouard
                    479:   Summary: to valgrind
                    480: 
1.237     brouard   481:   Revision 1.236  2016/08/25 10:50:18  brouard
                    482:   *** empty log message ***
                    483: 
1.236     brouard   484:   Revision 1.235  2016/08/25 06:59:23  brouard
                    485:   *** empty log message ***
                    486: 
1.235     brouard   487:   Revision 1.234  2016/08/23 16:51:20  brouard
                    488:   *** empty log message ***
                    489: 
1.234     brouard   490:   Revision 1.233  2016/08/23 07:40:50  brouard
                    491:   Summary: not working
                    492: 
1.233     brouard   493:   Revision 1.232  2016/08/22 14:20:21  brouard
                    494:   Summary: not working
                    495: 
1.232     brouard   496:   Revision 1.231  2016/08/22 07:17:15  brouard
                    497:   Summary: not working
                    498: 
1.231     brouard   499:   Revision 1.230  2016/08/22 06:55:53  brouard
                    500:   Summary: Not working
                    501: 
1.230     brouard   502:   Revision 1.229  2016/07/23 09:45:53  brouard
                    503:   Summary: Completing for func too
                    504: 
1.229     brouard   505:   Revision 1.228  2016/07/22 17:45:30  brouard
                    506:   Summary: Fixing some arrays, still debugging
                    507: 
1.227     brouard   508:   Revision 1.226  2016/07/12 18:42:34  brouard
                    509:   Summary: temp
                    510: 
1.226     brouard   511:   Revision 1.225  2016/07/12 08:40:03  brouard
                    512:   Summary: saving but not running
                    513: 
1.225     brouard   514:   Revision 1.224  2016/07/01 13:16:01  brouard
                    515:   Summary: Fixes
                    516: 
1.224     brouard   517:   Revision 1.223  2016/02/19 09:23:35  brouard
                    518:   Summary: temporary
                    519: 
1.223     brouard   520:   Revision 1.222  2016/02/17 08:14:50  brouard
                    521:   Summary: Probably last 0.98 stable version 0.98r6
                    522: 
1.222     brouard   523:   Revision 1.221  2016/02/15 23:35:36  brouard
                    524:   Summary: minor bug
                    525: 
1.220     brouard   526:   Revision 1.219  2016/02/15 00:48:12  brouard
                    527:   *** empty log message ***
                    528: 
1.219     brouard   529:   Revision 1.218  2016/02/12 11:29:23  brouard
                    530:   Summary: 0.99 Back projections
                    531: 
1.218     brouard   532:   Revision 1.217  2015/12/23 17:18:31  brouard
                    533:   Summary: Experimental backcast
                    534: 
1.217     brouard   535:   Revision 1.216  2015/12/18 17:32:11  brouard
                    536:   Summary: 0.98r4 Warning and status=-2
                    537: 
                    538:   Version 0.98r4 is now:
                    539:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    540:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    541:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    542: 
1.216     brouard   543:   Revision 1.215  2015/12/16 08:52:24  brouard
                    544:   Summary: 0.98r4 working
                    545: 
1.215     brouard   546:   Revision 1.214  2015/12/16 06:57:54  brouard
                    547:   Summary: temporary not working
                    548: 
1.214     brouard   549:   Revision 1.213  2015/12/11 18:22:17  brouard
                    550:   Summary: 0.98r4
                    551: 
1.213     brouard   552:   Revision 1.212  2015/11/21 12:47:24  brouard
                    553:   Summary: minor typo
                    554: 
1.212     brouard   555:   Revision 1.211  2015/11/21 12:41:11  brouard
                    556:   Summary: 0.98r3 with some graph of projected cross-sectional
                    557: 
                    558:   Author: Nicolas Brouard
                    559: 
1.211     brouard   560:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   561:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   562:   Summary: Adding ftolpl parameter
                    563:   Author: N Brouard
                    564: 
                    565:   We had difficulties to get smoothed confidence intervals. It was due
                    566:   to the period prevalence which wasn't computed accurately. The inner
                    567:   parameter ftolpl is now an outer parameter of the .imach parameter
                    568:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    569:   computation are long.
                    570: 
1.209     brouard   571:   Revision 1.208  2015/11/17 14:31:57  brouard
                    572:   Summary: temporary
                    573: 
1.208     brouard   574:   Revision 1.207  2015/10/27 17:36:57  brouard
                    575:   *** empty log message ***
                    576: 
1.207     brouard   577:   Revision 1.206  2015/10/24 07:14:11  brouard
                    578:   *** empty log message ***
                    579: 
1.206     brouard   580:   Revision 1.205  2015/10/23 15:50:53  brouard
                    581:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    582: 
1.205     brouard   583:   Revision 1.204  2015/10/01 16:20:26  brouard
                    584:   Summary: Some new graphs of contribution to likelihood
                    585: 
1.204     brouard   586:   Revision 1.203  2015/09/30 17:45:14  brouard
                    587:   Summary: looking at better estimation of the hessian
                    588: 
                    589:   Also a better criteria for convergence to the period prevalence And
                    590:   therefore adding the number of years needed to converge. (The
                    591:   prevalence in any alive state shold sum to one
                    592: 
1.203     brouard   593:   Revision 1.202  2015/09/22 19:45:16  brouard
                    594:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    595: 
1.202     brouard   596:   Revision 1.201  2015/09/15 17:34:58  brouard
                    597:   Summary: 0.98r0
                    598: 
                    599:   - Some new graphs like suvival functions
                    600:   - Some bugs fixed like model=1+age+V2.
                    601: 
1.201     brouard   602:   Revision 1.200  2015/09/09 16:53:55  brouard
                    603:   Summary: Big bug thanks to Flavia
                    604: 
                    605:   Even model=1+age+V2. did not work anymore
                    606: 
1.200     brouard   607:   Revision 1.199  2015/09/07 14:09:23  brouard
                    608:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    609: 
1.199     brouard   610:   Revision 1.198  2015/09/03 07:14:39  brouard
                    611:   Summary: 0.98q5 Flavia
                    612: 
1.198     brouard   613:   Revision 1.197  2015/09/01 18:24:39  brouard
                    614:   *** empty log message ***
                    615: 
1.197     brouard   616:   Revision 1.196  2015/08/18 23:17:52  brouard
                    617:   Summary: 0.98q5
                    618: 
1.196     brouard   619:   Revision 1.195  2015/08/18 16:28:39  brouard
                    620:   Summary: Adding a hack for testing purpose
                    621: 
                    622:   After reading the title, ftol and model lines, if the comment line has
                    623:   a q, starting with #q, the answer at the end of the run is quit. It
                    624:   permits to run test files in batch with ctest. The former workaround was
                    625:   $ echo q | imach foo.imach
                    626: 
1.195     brouard   627:   Revision 1.194  2015/08/18 13:32:00  brouard
                    628:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    629: 
1.194     brouard   630:   Revision 1.193  2015/08/04 07:17:42  brouard
                    631:   Summary: 0.98q4
                    632: 
1.193     brouard   633:   Revision 1.192  2015/07/16 16:49:02  brouard
                    634:   Summary: Fixing some outputs
                    635: 
1.192     brouard   636:   Revision 1.191  2015/07/14 10:00:33  brouard
                    637:   Summary: Some fixes
                    638: 
1.191     brouard   639:   Revision 1.190  2015/05/05 08:51:13  brouard
                    640:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    641: 
                    642:   Fix 1+age+.
                    643: 
1.190     brouard   644:   Revision 1.189  2015/04/30 14:45:16  brouard
                    645:   Summary: 0.98q2
                    646: 
1.189     brouard   647:   Revision 1.188  2015/04/30 08:27:53  brouard
                    648:   *** empty log message ***
                    649: 
1.188     brouard   650:   Revision 1.187  2015/04/29 09:11:15  brouard
                    651:   *** empty log message ***
                    652: 
1.187     brouard   653:   Revision 1.186  2015/04/23 12:01:52  brouard
                    654:   Summary: V1*age is working now, version 0.98q1
                    655: 
                    656:   Some codes had been disabled in order to simplify and Vn*age was
                    657:   working in the optimization phase, ie, giving correct MLE parameters,
                    658:   but, as usual, outputs were not correct and program core dumped.
                    659: 
1.186     brouard   660:   Revision 1.185  2015/03/11 13:26:42  brouard
                    661:   Summary: Inclusion of compile and links command line for Intel Compiler
                    662: 
1.185     brouard   663:   Revision 1.184  2015/03/11 11:52:39  brouard
                    664:   Summary: Back from Windows 8. Intel Compiler
                    665: 
1.184     brouard   666:   Revision 1.183  2015/03/10 20:34:32  brouard
                    667:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    668: 
                    669:   We use directest instead of original Powell test; probably no
                    670:   incidence on the results, but better justifications;
                    671:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    672:   wrong results.
                    673: 
1.183     brouard   674:   Revision 1.182  2015/02/12 08:19:57  brouard
                    675:   Summary: Trying to keep directest which seems simpler and more general
                    676:   Author: Nicolas Brouard
                    677: 
1.182     brouard   678:   Revision 1.181  2015/02/11 23:22:24  brouard
                    679:   Summary: Comments on Powell added
                    680: 
                    681:   Author:
                    682: 
1.181     brouard   683:   Revision 1.180  2015/02/11 17:33:45  brouard
                    684:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    685: 
1.180     brouard   686:   Revision 1.179  2015/01/04 09:57:06  brouard
                    687:   Summary: back to OS/X
                    688: 
1.179     brouard   689:   Revision 1.178  2015/01/04 09:35:48  brouard
                    690:   *** empty log message ***
                    691: 
1.178     brouard   692:   Revision 1.177  2015/01/03 18:40:56  brouard
                    693:   Summary: Still testing ilc32 on OSX
                    694: 
1.177     brouard   695:   Revision 1.176  2015/01/03 16:45:04  brouard
                    696:   *** empty log message ***
                    697: 
1.176     brouard   698:   Revision 1.175  2015/01/03 16:33:42  brouard
                    699:   *** empty log message ***
                    700: 
1.175     brouard   701:   Revision 1.174  2015/01/03 16:15:49  brouard
                    702:   Summary: Still in cross-compilation
                    703: 
1.174     brouard   704:   Revision 1.173  2015/01/03 12:06:26  brouard
                    705:   Summary: trying to detect cross-compilation
                    706: 
1.173     brouard   707:   Revision 1.172  2014/12/27 12:07:47  brouard
                    708:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    709: 
1.172     brouard   710:   Revision 1.171  2014/12/23 13:26:59  brouard
                    711:   Summary: Back from Visual C
                    712: 
                    713:   Still problem with utsname.h on Windows
                    714: 
1.171     brouard   715:   Revision 1.170  2014/12/23 11:17:12  brouard
                    716:   Summary: Cleaning some \%% back to %%
                    717: 
                    718:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    719: 
1.170     brouard   720:   Revision 1.169  2014/12/22 23:08:31  brouard
                    721:   Summary: 0.98p
                    722: 
                    723:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    724: 
1.169     brouard   725:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   726:   Summary: update
1.169     brouard   727: 
1.168     brouard   728:   Revision 1.167  2014/12/22 13:50:56  brouard
                    729:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    730: 
                    731:   Testing on Linux 64
                    732: 
1.167     brouard   733:   Revision 1.166  2014/12/22 11:40:47  brouard
                    734:   *** empty log message ***
                    735: 
1.166     brouard   736:   Revision 1.165  2014/12/16 11:20:36  brouard
                    737:   Summary: After compiling on Visual C
                    738: 
                    739:   * imach.c (Module): Merging 1.61 to 1.162
                    740: 
1.165     brouard   741:   Revision 1.164  2014/12/16 10:52:11  brouard
                    742:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    743: 
                    744:   * imach.c (Module): Merging 1.61 to 1.162
                    745: 
1.164     brouard   746:   Revision 1.163  2014/12/16 10:30:11  brouard
                    747:   * imach.c (Module): Merging 1.61 to 1.162
                    748: 
1.163     brouard   749:   Revision 1.162  2014/09/25 11:43:39  brouard
                    750:   Summary: temporary backup 0.99!
                    751: 
1.162     brouard   752:   Revision 1.1  2014/09/16 11:06:58  brouard
                    753:   Summary: With some code (wrong) for nlopt
                    754: 
                    755:   Author:
                    756: 
                    757:   Revision 1.161  2014/09/15 20:41:41  brouard
                    758:   Summary: Problem with macro SQR on Intel compiler
                    759: 
1.161     brouard   760:   Revision 1.160  2014/09/02 09:24:05  brouard
                    761:   *** empty log message ***
                    762: 
1.160     brouard   763:   Revision 1.159  2014/09/01 10:34:10  brouard
                    764:   Summary: WIN32
                    765:   Author: Brouard
                    766: 
1.159     brouard   767:   Revision 1.158  2014/08/27 17:11:51  brouard
                    768:   *** empty log message ***
                    769: 
1.158     brouard   770:   Revision 1.157  2014/08/27 16:26:55  brouard
                    771:   Summary: Preparing windows Visual studio version
                    772:   Author: Brouard
                    773: 
                    774:   In order to compile on Visual studio, time.h is now correct and time_t
                    775:   and tm struct should be used. difftime should be used but sometimes I
                    776:   just make the differences in raw time format (time(&now).
                    777:   Trying to suppress #ifdef LINUX
                    778:   Add xdg-open for __linux in order to open default browser.
                    779: 
1.157     brouard   780:   Revision 1.156  2014/08/25 20:10:10  brouard
                    781:   *** empty log message ***
                    782: 
1.156     brouard   783:   Revision 1.155  2014/08/25 18:32:34  brouard
                    784:   Summary: New compile, minor changes
                    785:   Author: Brouard
                    786: 
1.155     brouard   787:   Revision 1.154  2014/06/20 17:32:08  brouard
                    788:   Summary: Outputs now all graphs of convergence to period prevalence
                    789: 
1.154     brouard   790:   Revision 1.153  2014/06/20 16:45:46  brouard
                    791:   Summary: If 3 live state, convergence to period prevalence on same graph
                    792:   Author: Brouard
                    793: 
1.153     brouard   794:   Revision 1.152  2014/06/18 17:54:09  brouard
                    795:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    796: 
1.152     brouard   797:   Revision 1.151  2014/06/18 16:43:30  brouard
                    798:   *** empty log message ***
                    799: 
1.151     brouard   800:   Revision 1.150  2014/06/18 16:42:35  brouard
                    801:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    802:   Author: brouard
                    803: 
1.150     brouard   804:   Revision 1.149  2014/06/18 15:51:14  brouard
                    805:   Summary: Some fixes in parameter files errors
                    806:   Author: Nicolas Brouard
                    807: 
1.149     brouard   808:   Revision 1.148  2014/06/17 17:38:48  brouard
                    809:   Summary: Nothing new
                    810:   Author: Brouard
                    811: 
                    812:   Just a new packaging for OS/X version 0.98nS
                    813: 
1.148     brouard   814:   Revision 1.147  2014/06/16 10:33:11  brouard
                    815:   *** empty log message ***
                    816: 
1.147     brouard   817:   Revision 1.146  2014/06/16 10:20:28  brouard
                    818:   Summary: Merge
                    819:   Author: Brouard
                    820: 
                    821:   Merge, before building revised version.
                    822: 
1.146     brouard   823:   Revision 1.145  2014/06/10 21:23:15  brouard
                    824:   Summary: Debugging with valgrind
                    825:   Author: Nicolas Brouard
                    826: 
                    827:   Lot of changes in order to output the results with some covariates
                    828:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    829:   improve the code.
                    830:   No more memory valgrind error but a lot has to be done in order to
                    831:   continue the work of splitting the code into subroutines.
                    832:   Also, decodemodel has been improved. Tricode is still not
                    833:   optimal. nbcode should be improved. Documentation has been added in
                    834:   the source code.
                    835: 
1.144     brouard   836:   Revision 1.143  2014/01/26 09:45:38  brouard
                    837:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    838: 
                    839:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    840:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    841: 
1.143     brouard   842:   Revision 1.142  2014/01/26 03:57:36  brouard
                    843:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    844: 
                    845:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    846: 
1.142     brouard   847:   Revision 1.141  2014/01/26 02:42:01  brouard
                    848:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    849: 
1.141     brouard   850:   Revision 1.140  2011/09/02 10:37:54  brouard
                    851:   Summary: times.h is ok with mingw32 now.
                    852: 
1.140     brouard   853:   Revision 1.139  2010/06/14 07:50:17  brouard
                    854:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    855:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    856: 
1.139     brouard   857:   Revision 1.138  2010/04/30 18:19:40  brouard
                    858:   *** empty log message ***
                    859: 
1.138     brouard   860:   Revision 1.137  2010/04/29 18:11:38  brouard
                    861:   (Module): Checking covariates for more complex models
                    862:   than V1+V2. A lot of change to be done. Unstable.
                    863: 
1.137     brouard   864:   Revision 1.136  2010/04/26 20:30:53  brouard
                    865:   (Module): merging some libgsl code. Fixing computation
                    866:   of likelione (using inter/intrapolation if mle = 0) in order to
                    867:   get same likelihood as if mle=1.
                    868:   Some cleaning of code and comments added.
                    869: 
1.136     brouard   870:   Revision 1.135  2009/10/29 15:33:14  brouard
                    871:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    872: 
1.135     brouard   873:   Revision 1.134  2009/10/29 13:18:53  brouard
                    874:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    875: 
1.134     brouard   876:   Revision 1.133  2009/07/06 10:21:25  brouard
                    877:   just nforces
                    878: 
1.133     brouard   879:   Revision 1.132  2009/07/06 08:22:05  brouard
                    880:   Many tings
                    881: 
1.132     brouard   882:   Revision 1.131  2009/06/20 16:22:47  brouard
                    883:   Some dimensions resccaled
                    884: 
1.131     brouard   885:   Revision 1.130  2009/05/26 06:44:34  brouard
                    886:   (Module): Max Covariate is now set to 20 instead of 8. A
                    887:   lot of cleaning with variables initialized to 0. Trying to make
                    888:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    889: 
1.130     brouard   890:   Revision 1.129  2007/08/31 13:49:27  lievre
                    891:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    892: 
1.129     lievre    893:   Revision 1.128  2006/06/30 13:02:05  brouard
                    894:   (Module): Clarifications on computing e.j
                    895: 
1.128     brouard   896:   Revision 1.127  2006/04/28 18:11:50  brouard
                    897:   (Module): Yes the sum of survivors was wrong since
                    898:   imach-114 because nhstepm was no more computed in the age
                    899:   loop. Now we define nhstepma in the age loop.
                    900:   (Module): In order to speed up (in case of numerous covariates) we
                    901:   compute health expectancies (without variances) in a first step
                    902:   and then all the health expectancies with variances or standard
                    903:   deviation (needs data from the Hessian matrices) which slows the
                    904:   computation.
                    905:   In the future we should be able to stop the program is only health
                    906:   expectancies and graph are needed without standard deviations.
                    907: 
1.127     brouard   908:   Revision 1.126  2006/04/28 17:23:28  brouard
                    909:   (Module): Yes the sum of survivors was wrong since
                    910:   imach-114 because nhstepm was no more computed in the age
                    911:   loop. Now we define nhstepma in the age loop.
                    912:   Version 0.98h
                    913: 
1.126     brouard   914:   Revision 1.125  2006/04/04 15:20:31  lievre
                    915:   Errors in calculation of health expectancies. Age was not initialized.
                    916:   Forecasting file added.
                    917: 
                    918:   Revision 1.124  2006/03/22 17:13:53  lievre
                    919:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    920:   The log-likelihood is printed in the log file
                    921: 
                    922:   Revision 1.123  2006/03/20 10:52:43  brouard
                    923:   * imach.c (Module): <title> changed, corresponds to .htm file
                    924:   name. <head> headers where missing.
                    925: 
                    926:   * imach.c (Module): Weights can have a decimal point as for
                    927:   English (a comma might work with a correct LC_NUMERIC environment,
                    928:   otherwise the weight is truncated).
                    929:   Modification of warning when the covariates values are not 0 or
                    930:   1.
                    931:   Version 0.98g
                    932: 
                    933:   Revision 1.122  2006/03/20 09:45:41  brouard
                    934:   (Module): Weights can have a decimal point as for
                    935:   English (a comma might work with a correct LC_NUMERIC environment,
                    936:   otherwise the weight is truncated).
                    937:   Modification of warning when the covariates values are not 0 or
                    938:   1.
                    939:   Version 0.98g
                    940: 
                    941:   Revision 1.121  2006/03/16 17:45:01  lievre
                    942:   * imach.c (Module): Comments concerning covariates added
                    943: 
                    944:   * imach.c (Module): refinements in the computation of lli if
                    945:   status=-2 in order to have more reliable computation if stepm is
                    946:   not 1 month. Version 0.98f
                    947: 
                    948:   Revision 1.120  2006/03/16 15:10:38  lievre
                    949:   (Module): refinements in the computation of lli if
                    950:   status=-2 in order to have more reliable computation if stepm is
                    951:   not 1 month. Version 0.98f
                    952: 
                    953:   Revision 1.119  2006/03/15 17:42:26  brouard
                    954:   (Module): Bug if status = -2, the loglikelihood was
                    955:   computed as likelihood omitting the logarithm. Version O.98e
                    956: 
                    957:   Revision 1.118  2006/03/14 18:20:07  brouard
                    958:   (Module): varevsij Comments added explaining the second
                    959:   table of variances if popbased=1 .
                    960:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    961:   (Module): Function pstamp added
                    962:   (Module): Version 0.98d
                    963: 
                    964:   Revision 1.117  2006/03/14 17:16:22  brouard
                    965:   (Module): varevsij Comments added explaining the second
                    966:   table of variances if popbased=1 .
                    967:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    968:   (Module): Function pstamp added
                    969:   (Module): Version 0.98d
                    970: 
                    971:   Revision 1.116  2006/03/06 10:29:27  brouard
                    972:   (Module): Variance-covariance wrong links and
                    973:   varian-covariance of ej. is needed (Saito).
                    974: 
                    975:   Revision 1.115  2006/02/27 12:17:45  brouard
                    976:   (Module): One freematrix added in mlikeli! 0.98c
                    977: 
                    978:   Revision 1.114  2006/02/26 12:57:58  brouard
                    979:   (Module): Some improvements in processing parameter
                    980:   filename with strsep.
                    981: 
                    982:   Revision 1.113  2006/02/24 14:20:24  brouard
                    983:   (Module): Memory leaks checks with valgrind and:
                    984:   datafile was not closed, some imatrix were not freed and on matrix
                    985:   allocation too.
                    986: 
                    987:   Revision 1.112  2006/01/30 09:55:26  brouard
                    988:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    989: 
                    990:   Revision 1.111  2006/01/25 20:38:18  brouard
                    991:   (Module): Lots of cleaning and bugs added (Gompertz)
                    992:   (Module): Comments can be added in data file. Missing date values
                    993:   can be a simple dot '.'.
                    994: 
                    995:   Revision 1.110  2006/01/25 00:51:50  brouard
                    996:   (Module): Lots of cleaning and bugs added (Gompertz)
                    997: 
                    998:   Revision 1.109  2006/01/24 19:37:15  brouard
                    999:   (Module): Comments (lines starting with a #) are allowed in data.
                   1000: 
                   1001:   Revision 1.108  2006/01/19 18:05:42  lievre
                   1002:   Gnuplot problem appeared...
                   1003:   To be fixed
                   1004: 
                   1005:   Revision 1.107  2006/01/19 16:20:37  brouard
                   1006:   Test existence of gnuplot in imach path
                   1007: 
                   1008:   Revision 1.106  2006/01/19 13:24:36  brouard
                   1009:   Some cleaning and links added in html output
                   1010: 
                   1011:   Revision 1.105  2006/01/05 20:23:19  lievre
                   1012:   *** empty log message ***
                   1013: 
                   1014:   Revision 1.104  2005/09/30 16:11:43  lievre
                   1015:   (Module): sump fixed, loop imx fixed, and simplifications.
                   1016:   (Module): If the status is missing at the last wave but we know
                   1017:   that the person is alive, then we can code his/her status as -2
                   1018:   (instead of missing=-1 in earlier versions) and his/her
                   1019:   contributions to the likelihood is 1 - Prob of dying from last
                   1020:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                   1021:   the healthy state at last known wave). Version is 0.98
                   1022: 
                   1023:   Revision 1.103  2005/09/30 15:54:49  lievre
                   1024:   (Module): sump fixed, loop imx fixed, and simplifications.
                   1025: 
                   1026:   Revision 1.102  2004/09/15 17:31:30  brouard
                   1027:   Add the possibility to read data file including tab characters.
                   1028: 
                   1029:   Revision 1.101  2004/09/15 10:38:38  brouard
                   1030:   Fix on curr_time
                   1031: 
                   1032:   Revision 1.100  2004/07/12 18:29:06  brouard
                   1033:   Add version for Mac OS X. Just define UNIX in Makefile
                   1034: 
                   1035:   Revision 1.99  2004/06/05 08:57:40  brouard
                   1036:   *** empty log message ***
                   1037: 
                   1038:   Revision 1.98  2004/05/16 15:05:56  brouard
                   1039:   New version 0.97 . First attempt to estimate force of mortality
                   1040:   directly from the data i.e. without the need of knowing the health
                   1041:   state at each age, but using a Gompertz model: log u =a + b*age .
                   1042:   This is the basic analysis of mortality and should be done before any
                   1043:   other analysis, in order to test if the mortality estimated from the
                   1044:   cross-longitudinal survey is different from the mortality estimated
                   1045:   from other sources like vital statistic data.
                   1046: 
                   1047:   The same imach parameter file can be used but the option for mle should be -3.
                   1048: 
1.324     brouard  1049:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard  1050:   former routines in order to include the new code within the former code.
                   1051: 
                   1052:   The output is very simple: only an estimate of the intercept and of
                   1053:   the slope with 95% confident intervals.
                   1054: 
                   1055:   Current limitations:
                   1056:   A) Even if you enter covariates, i.e. with the
                   1057:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                   1058:   B) There is no computation of Life Expectancy nor Life Table.
                   1059: 
                   1060:   Revision 1.97  2004/02/20 13:25:42  lievre
                   1061:   Version 0.96d. Population forecasting command line is (temporarily)
                   1062:   suppressed.
                   1063: 
                   1064:   Revision 1.96  2003/07/15 15:38:55  brouard
                   1065:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                   1066:   rewritten within the same printf. Workaround: many printfs.
                   1067: 
                   1068:   Revision 1.95  2003/07/08 07:54:34  brouard
                   1069:   * imach.c (Repository):
                   1070:   (Repository): Using imachwizard code to output a more meaningful covariance
                   1071:   matrix (cov(a12,c31) instead of numbers.
                   1072: 
                   1073:   Revision 1.94  2003/06/27 13:00:02  brouard
                   1074:   Just cleaning
                   1075: 
                   1076:   Revision 1.93  2003/06/25 16:33:55  brouard
                   1077:   (Module): On windows (cygwin) function asctime_r doesn't
                   1078:   exist so I changed back to asctime which exists.
                   1079:   (Module): Version 0.96b
                   1080: 
                   1081:   Revision 1.92  2003/06/25 16:30:45  brouard
                   1082:   (Module): On windows (cygwin) function asctime_r doesn't
                   1083:   exist so I changed back to asctime which exists.
                   1084: 
                   1085:   Revision 1.91  2003/06/25 15:30:29  brouard
                   1086:   * imach.c (Repository): Duplicated warning errors corrected.
                   1087:   (Repository): Elapsed time after each iteration is now output. It
                   1088:   helps to forecast when convergence will be reached. Elapsed time
                   1089:   is stamped in powell.  We created a new html file for the graphs
                   1090:   concerning matrix of covariance. It has extension -cov.htm.
                   1091: 
                   1092:   Revision 1.90  2003/06/24 12:34:15  brouard
                   1093:   (Module): Some bugs corrected for windows. Also, when
                   1094:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1095:   of the covariance matrix to be input.
                   1096: 
                   1097:   Revision 1.89  2003/06/24 12:30:52  brouard
                   1098:   (Module): Some bugs corrected for windows. Also, when
                   1099:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1100:   of the covariance matrix to be input.
                   1101: 
                   1102:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1103:   * 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.
                   1104: 
                   1105:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1106:   Version 0.96
                   1107: 
                   1108:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1109:   (Module): Change position of html and gnuplot routines and added
                   1110:   routine fileappend.
                   1111: 
                   1112:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1113:   * imach.c (Repository): Check when date of death was earlier that
                   1114:   current date of interview. It may happen when the death was just
                   1115:   prior to the death. In this case, dh was negative and likelihood
                   1116:   was wrong (infinity). We still send an "Error" but patch by
                   1117:   assuming that the date of death was just one stepm after the
                   1118:   interview.
                   1119:   (Repository): Because some people have very long ID (first column)
                   1120:   we changed int to long in num[] and we added a new lvector for
                   1121:   memory allocation. But we also truncated to 8 characters (left
                   1122:   truncation)
                   1123:   (Repository): No more line truncation errors.
                   1124: 
                   1125:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1126:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1127:   place. It differs from routine "prevalence" which may be called
                   1128:   many times. Probs is memory consuming and must be used with
                   1129:   parcimony.
                   1130:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1131: 
                   1132:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1133:   *** empty log message ***
                   1134: 
                   1135:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1136:   Add log in  imach.c and  fullversion number is now printed.
                   1137: 
                   1138: */
                   1139: /*
                   1140:    Interpolated Markov Chain
                   1141: 
                   1142:   Short summary of the programme:
                   1143:   
1.227     brouard  1144:   This program computes Healthy Life Expectancies or State-specific
                   1145:   (if states aren't health statuses) Expectancies from
                   1146:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1147: 
                   1148:   -1- a first survey ("cross") where individuals from different ages
                   1149:   are interviewed on their health status or degree of disability (in
                   1150:   the case of a health survey which is our main interest)
                   1151: 
                   1152:   -2- at least a second wave of interviews ("longitudinal") which
                   1153:   measure each change (if any) in individual health status.  Health
                   1154:   expectancies are computed from the time spent in each health state
                   1155:   according to a model. More health states you consider, more time is
                   1156:   necessary to reach the Maximum Likelihood of the parameters involved
                   1157:   in the model.  The simplest model is the multinomial logistic model
                   1158:   where pij is the probability to be observed in state j at the second
                   1159:   wave conditional to be observed in state i at the first
                   1160:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1161:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1162:   have a more complex model than "constant and age", you should modify
                   1163:   the program where the markup *Covariates have to be included here
                   1164:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1165:   convergence.
                   1166: 
                   1167:   The advantage of this computer programme, compared to a simple
                   1168:   multinomial logistic model, is clear when the delay between waves is not
                   1169:   identical for each individual. Also, if a individual missed an
                   1170:   intermediate interview, the information is lost, but taken into
                   1171:   account using an interpolation or extrapolation.  
                   1172: 
                   1173:   hPijx is the probability to be observed in state i at age x+h
                   1174:   conditional to the observed state i at age x. The delay 'h' can be
                   1175:   split into an exact number (nh*stepm) of unobserved intermediate
                   1176:   states. This elementary transition (by month, quarter,
                   1177:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1178:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1179:   and the contribution of each individual to the likelihood is simply
                   1180:   hPijx.
                   1181: 
                   1182:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1183:   of the life expectancies. It also computes the period (stable) prevalence.
                   1184: 
                   1185: Back prevalence and projections:
1.227     brouard  1186: 
                   1187:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1188:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1189:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1190:    mobilavproj)
                   1191: 
                   1192:     Computes the back prevalence limit for any combination of
                   1193:     covariate values k at any age between ageminpar and agemaxpar and
                   1194:     returns it in **bprlim. In the loops,
                   1195: 
                   1196:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1197:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1198: 
                   1199:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1200:    Computes for any combination of covariates k and any age between bage and fage 
                   1201:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1202:                        oldm=oldms;savm=savms;
1.227     brouard  1203: 
1.267     brouard  1204:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1205:      Computes the transition matrix starting at age 'age' over
                   1206:      'nhstepm*hstepm*stepm' months (i.e. until
                   1207:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1208:      nhstepm*hstepm matrices. 
                   1209: 
                   1210:      Returns p3mat[i][j][h] after calling
                   1211:      p3mat[i][j][h]=matprod2(newm,
                   1212:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1213:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1214:      oldm);
1.226     brouard  1215: 
                   1216: Important routines
                   1217: 
                   1218: - func (or funcone), computes logit (pij) distinguishing
                   1219:   o fixed variables (single or product dummies or quantitative);
                   1220:   o varying variables by:
                   1221:    (1) wave (single, product dummies, quantitative), 
                   1222:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1223:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1224:        % varying dummy (not done) or quantitative (not done);
                   1225: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1226:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1227: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1228:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1229:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1230: 
1.226     brouard  1231: 
                   1232:   
1.324     brouard  1233:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1234:            Institut national d'études démographiques, Paris.
1.126     brouard  1235:   This software have been partly granted by Euro-REVES, a concerted action
                   1236:   from the European Union.
                   1237:   It is copyrighted identically to a GNU software product, ie programme and
                   1238:   software can be distributed freely for non commercial use. Latest version
                   1239:   can be accessed at http://euroreves.ined.fr/imach .
                   1240: 
                   1241:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1242:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1243:   
                   1244:   **********************************************************************/
                   1245: /*
                   1246:   main
                   1247:   read parameterfile
                   1248:   read datafile
                   1249:   concatwav
                   1250:   freqsummary
                   1251:   if (mle >= 1)
                   1252:     mlikeli
                   1253:   print results files
                   1254:   if mle==1 
                   1255:      computes hessian
                   1256:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1257:       begin-prev-date,...
                   1258:   open gnuplot file
                   1259:   open html file
1.145     brouard  1260:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1261:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1262:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1263:     freexexit2 possible for memory heap.
                   1264: 
                   1265:   h Pij x                         | pij_nom  ficrestpij
                   1266:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1267:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1268:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1269: 
                   1270:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1271:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1272:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1273:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1274:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1275: 
1.126     brouard  1276:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1277:   health expectancies
                   1278:   Variance-covariance of DFLE
                   1279:   prevalence()
                   1280:    movingaverage()
                   1281:   varevsij() 
                   1282:   if popbased==1 varevsij(,popbased)
                   1283:   total life expectancies
                   1284:   Variance of period (stable) prevalence
                   1285:  end
                   1286: */
                   1287: 
1.187     brouard  1288: /* #define DEBUG */
                   1289: /* #define DEBUGBRENT */
1.203     brouard  1290: /* #define DEBUGLINMIN */
                   1291: /* #define DEBUGHESS */
                   1292: #define DEBUGHESSIJ
1.224     brouard  1293: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1294: #define POWELL /* Instead of NLOPT */
1.224     brouard  1295: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1296: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1297: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1298: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.359     brouard  1299: /* #define POWELLORIGINCONJUGATE  /\* Don't use conjugate but biggest decrease if valuable *\/ */
                   1300: /* #define NOTMINFIT */
1.126     brouard  1301: 
                   1302: #include <math.h>
                   1303: #include <stdio.h>
                   1304: #include <stdlib.h>
                   1305: #include <string.h>
1.226     brouard  1306: #include <ctype.h>
1.159     brouard  1307: 
                   1308: #ifdef _WIN32
                   1309: #include <io.h>
1.172     brouard  1310: #include <windows.h>
                   1311: #include <tchar.h>
1.159     brouard  1312: #else
1.126     brouard  1313: #include <unistd.h>
1.159     brouard  1314: #endif
1.126     brouard  1315: 
                   1316: #include <limits.h>
                   1317: #include <sys/types.h>
1.171     brouard  1318: 
                   1319: #if defined(__GNUC__)
                   1320: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1321: #endif
                   1322: 
1.126     brouard  1323: #include <sys/stat.h>
                   1324: #include <errno.h>
1.159     brouard  1325: /* extern int errno; */
1.126     brouard  1326: 
1.157     brouard  1327: /* #ifdef LINUX */
                   1328: /* #include <time.h> */
                   1329: /* #include "timeval.h" */
                   1330: /* #else */
                   1331: /* #include <sys/time.h> */
                   1332: /* #endif */
                   1333: 
1.126     brouard  1334: #include <time.h>
                   1335: 
1.136     brouard  1336: #ifdef GSL
                   1337: #include <gsl/gsl_errno.h>
                   1338: #include <gsl/gsl_multimin.h>
                   1339: #endif
                   1340: 
1.167     brouard  1341: 
1.162     brouard  1342: #ifdef NLOPT
                   1343: #include <nlopt.h>
                   1344: typedef struct {
                   1345:   double (* function)(double [] );
                   1346: } myfunc_data ;
                   1347: #endif
                   1348: 
1.126     brouard  1349: /* #include <libintl.h> */
                   1350: /* #define _(String) gettext (String) */
                   1351: 
1.349     brouard  1352: #define MAXLINE 16384 /* Was 256 and 1024 and 2048. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1353: 
                   1354: #define GNUPLOTPROGRAM "gnuplot"
1.343     brouard  1355: #define GNUPLOTVERSION 5.1
                   1356: double gnuplotversion=GNUPLOTVERSION;
1.126     brouard  1357: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1358: #define FILENAMELENGTH 256
1.126     brouard  1359: 
                   1360: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1361: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1362: 
1.349     brouard  1363: #define MAXPARM 216 /**< Maximum number of parameters for the optimization was 128 */
1.144     brouard  1364: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1365: 
                   1366: #define NINTERVMAX 8
1.144     brouard  1367: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1368: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1369: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1370: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1371: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1372: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1373: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1374: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1375: /* #define AGESUP 130 */
1.288     brouard  1376: /* #define AGESUP 150 */
                   1377: #define AGESUP 200
1.268     brouard  1378: #define AGEINF 0
1.218     brouard  1379: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1380: #define AGEBASE 40
1.194     brouard  1381: #define AGEOVERFLOW 1.e20
1.164     brouard  1382: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1383: #ifdef _WIN32
                   1384: #define DIRSEPARATOR '\\'
                   1385: #define CHARSEPARATOR "\\"
                   1386: #define ODIRSEPARATOR '/'
                   1387: #else
1.126     brouard  1388: #define DIRSEPARATOR '/'
                   1389: #define CHARSEPARATOR "/"
                   1390: #define ODIRSEPARATOR '\\'
                   1391: #endif
                   1392: 
1.360   ! brouard  1393: /* $Id: imach.c,v 1.359 2024/04/24 21:21:17 brouard Exp $ */
1.126     brouard  1394: /* $State: Exp $ */
1.196     brouard  1395: #include "version.h"
                   1396: char version[]=__IMACH_VERSION__;
1.360   ! brouard  1397: 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";
        !          1398: char fullversion[]="$Revision: 1.359 $ $Date: 2024/04/24 21:21:17 $"; 
1.126     brouard  1399: char strstart[80];
                   1400: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1401: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.342     brouard  1402: int debugILK=0; /* debugILK is set by a #d in a comment line */
1.187     brouard  1403: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1404: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1405: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
1.335     brouard  1406: 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  1407: 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  1408: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1409: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1410: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
1.349     brouard  1411: int cptcovprodage=0; /**< Number of fixed covariates with age: V3*age or V2*V3*age 1 */
                   1412: int cptcovprodvage=0; /**< Number of varying covariates with age: V7*age or V7*V6*age */
                   1413: int cptcovdageprod=0; /**< Number of doubleproducts with age, since 0.99r44 only: age*Vn*Vm for gnuplot printing*/
1.145     brouard  1414: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335     brouard  1415: 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  1416: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1417: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.339     brouard  1418: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
1.349     brouard  1419: 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 */
                   1420: 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 */
                   1421: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (single or product, dummy or quantitative) in the model */
                   1422: 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  1423: int nsd=0; /**< Total number of single dummy variables (output) */
                   1424: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1425: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1426: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1427: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1428: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1429: int cptcov=0; /* Working variable */
1.334     brouard  1430: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1431: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1432: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1433: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1434: int nlstate=2; /* Number of live states */
                   1435: int ndeath=1; /* Number of dead states */
1.130     brouard  1436: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.339     brouard  1437: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
                   1438: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
1.126     brouard  1439: int popbased=0;
                   1440: 
                   1441: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1442: int maxwav=0; /* Maxim number of waves */
                   1443: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1444: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
1.359     brouard  1445: int gipmx = 0;
                   1446: double gsw = 0; /* Global variables on the number of contributions
1.126     brouard  1447:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1448: int mle=1, weightopt=0;
1.126     brouard  1449: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1450: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1451: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1452:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1453: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1454: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1455: 
1.130     brouard  1456: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1457: double **matprod2(); /* test */
1.126     brouard  1458: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1459: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1460: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1461: 
1.136     brouard  1462: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1463: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1464: FILE *ficlog, *ficrespow;
1.130     brouard  1465: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1466: double fretone; /* Only one call to likelihood */
1.130     brouard  1467: long ipmx=0; /* Number of contributions */
1.126     brouard  1468: double sw; /* Sum of weights */
                   1469: char filerespow[FILENAMELENGTH];
                   1470: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1471: FILE *ficresilk;
                   1472: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1473: FILE *ficresprobmorprev;
                   1474: FILE *fichtm, *fichtmcov; /* Html File */
                   1475: FILE *ficreseij;
                   1476: char filerese[FILENAMELENGTH];
                   1477: FILE *ficresstdeij;
                   1478: char fileresstde[FILENAMELENGTH];
                   1479: FILE *ficrescveij;
                   1480: char filerescve[FILENAMELENGTH];
                   1481: FILE  *ficresvij;
                   1482: char fileresv[FILENAMELENGTH];
1.269     brouard  1483: 
1.126     brouard  1484: char title[MAXLINE];
1.234     brouard  1485: char model[MAXLINE]; /**< The model line */
1.217     brouard  1486: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1487: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1488: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1489: char command[FILENAMELENGTH];
                   1490: int  outcmd=0;
                   1491: 
1.217     brouard  1492: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1493: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1494: char filelog[FILENAMELENGTH]; /* Log file */
                   1495: char filerest[FILENAMELENGTH];
                   1496: char fileregp[FILENAMELENGTH];
                   1497: char popfile[FILENAMELENGTH];
                   1498: 
                   1499: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1500: 
1.157     brouard  1501: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1502: /* struct timezone tzp; */
                   1503: /* extern int gettimeofday(); */
                   1504: struct tm tml, *gmtime(), *localtime();
                   1505: 
                   1506: extern time_t time();
                   1507: 
                   1508: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1509: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
1.349     brouard  1510: time_t   rlast_btime; /* raw time */
1.157     brouard  1511: struct tm tm;
                   1512: 
1.126     brouard  1513: char strcurr[80], strfor[80];
                   1514: 
                   1515: char *endptr;
                   1516: long lval;
                   1517: double dval;
                   1518: 
                   1519: #define NR_END 1
                   1520: #define FREE_ARG char*
                   1521: #define FTOL 1.0e-10
                   1522: 
                   1523: #define NRANSI 
1.240     brouard  1524: #define ITMAX 200
                   1525: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1526: 
                   1527: #define TOL 2.0e-4 
                   1528: 
                   1529: #define CGOLD 0.3819660 
                   1530: #define ZEPS 1.0e-10 
                   1531: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1532: 
                   1533: #define GOLD 1.618034 
                   1534: #define GLIMIT 100.0 
                   1535: #define TINY 1.0e-20 
                   1536: 
                   1537: static double maxarg1,maxarg2;
                   1538: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1539: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1540:   
                   1541: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1542: #define rint(a) floor(a+0.5)
1.166     brouard  1543: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1544: #define mytinydouble 1.0e-16
1.166     brouard  1545: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1546: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1547: /* static double dsqrarg; */
                   1548: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1549: static double sqrarg;
                   1550: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1551: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1552: int agegomp= AGEGOMP;
                   1553: 
                   1554: int imx; 
                   1555: int stepm=1;
                   1556: /* Stepm, step in month: minimum step interpolation*/
                   1557: 
                   1558: int estepm;
                   1559: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1560: 
                   1561: int m,nb;
                   1562: long *num;
1.197     brouard  1563: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1564: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1565:                   covariate for which somebody answered excluding 
                   1566:                   undefined. Usually 2: 0 and 1. */
                   1567: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1568:                             covariate for which somebody answered including 
                   1569:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1570: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1571: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1572: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1573: 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  1574: double *ageexmed,*agecens;
                   1575: double dateintmean=0;
1.296     brouard  1576:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1577:   double anprojf, mprojf, jprojf;
1.126     brouard  1578: 
1.296     brouard  1579:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1580:   double anbackf, mbackf, jbackf;
                   1581:   double jintmean,mintmean,aintmean;  
1.126     brouard  1582: double *weight;
                   1583: int **s; /* Status */
1.141     brouard  1584: double *agedc;
1.145     brouard  1585: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1586:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1587:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1588: double **coqvar; /* Fixed quantitative covariate nqv */
1.341     brouard  1589: double ***cotvar; /* Time varying covariate start at ncovcol + nqv + (1 to ntv) */
1.225     brouard  1590: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1591: double  idx; 
                   1592: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1593: /* Some documentation */
                   1594:       /*   Design original data
                   1595:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1596:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1597:        *                                                             ntv=3     nqtv=1
1.330     brouard  1598:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1599:        * For time varying covariate, quanti or dummies
                   1600:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
1.341     brouard  1601:        *       cotvar[wav][ncovcol+nqv+ iv(1 to nqtv)][i]= [(1 to nqtv)][i]=(V12) quanti
1.319     brouard  1602:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1603:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1604:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1605:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1606:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1607:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1608:        */
                   1609: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1610: /* 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
                   1611:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1612:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1613: */
1.349     brouard  1614: /*           V5+V4+ V3+V4*V3 +V5*age+V2 +V1*V2+V1*age+V1+V4*V3*age */
                   1615: /*    kmodel  1  2   3    4     5     6    7     8     9    10 */
                   1616: /*Typevar[k]=  0  0   0   2     1    0    2     1     0    3 *//*0 for simple covariate (dummy, quantitative,*/
                   1617:                                                                /* fixed or varying), 1 for age product, 2 for*/
                   1618:                                                                /* product without age, 3 for age and double product   */
                   1619: /*Dummy[k]=    1  0   0   1     3    1    1     2     0     3  *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1620:                                                                 /*(single or product without age), 2 dummy*/
                   1621:                                                                /* with age product, 3 quant with age product*/
                   1622: /*Tvar[k]=     5  4   3   6     5    2    7     1     1     6 */
                   1623: /*    nsd         1   2                               3 */ /* Counting single dummies covar fixed or tv */
                   1624: /*TnsdVar[Tvar]   1   2                               3 */ 
                   1625: /*Tvaraff[nsd]    4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1626: /*TvarsD[nsd]     4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1627: /*TvarsDind[nsd]  2   3                               9 */ /* position K of single dummy cova */
                   1628: /*    nsq      1                     2                  */ /* Counting single quantit tv */
                   1629: /* TvarsQ[k]   5                     2                  */ /* Number of single quantitative cova */
                   1630: /* TvarsQind   1                     6                  */ /* position K of single quantitative cova */
                   1631: /* Tprod[i]=k             1               2             */ /* Position in model of the ith prod without age */
                   1632: /* cptcovage                    1               2         3 */ /* Counting cov*age in the model equation */
                   1633: /* Tage[cptcovage]=k            5               8         10 */ /* Position in the model of ith cov*age */
1.350     brouard  1634: /* 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"*/
                   1635: /*  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  1636: /*  p Tvard[2][1]@21 = {7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0 <repeats 11 times>} */
1.350     brouard  1637: /* 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}*/
                   1638: /* 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  1639: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2               */ /* Position in model of the ith prod without age */
1.330     brouard  1640: /* 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  1641: /* 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  1642: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1643: /* Type                    */
                   1644: /* V         1  2  3  4  5 */
                   1645: /*           F  F  V  V  V */
                   1646: /*           D  Q  D  D  Q */
                   1647: /*                         */
                   1648: int *TvarsD;
1.330     brouard  1649: int *TnsdVar;
1.234     brouard  1650: int *TvarsDind;
                   1651: int *TvarsQ;
                   1652: int *TvarsQind;
                   1653: 
1.318     brouard  1654: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1655: int nresult=0;
1.258     brouard  1656: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1657: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1658: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1659: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1660: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1661: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1662: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1663: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1664: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1665: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1666: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1667: 
                   1668: /* 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
                   1669:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1670:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1671: */
1.234     brouard  1672: /* 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  1673: 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 */
                   1674: 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 */
                   1675: 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 */
                   1676: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1677: 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 */
                   1678: 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  1679: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1680: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1681: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1682: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1683: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1684: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1685: 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 */
                   1686: 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  1687: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1688: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
1.349     brouard  1689: int *TvarVVA; /* We count ncovvt time varying covariates (single or products with age) and put their name into TvarVVA */
                   1690: int *TvarVVAind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1691: int *TvarAVVA; /* We count ALL ncovta time varying covariates (single or products with age) and put their name into TvarVVA */
                   1692: int *TvarAVVAind; /* We count ALL ncovta time varying covariates (single or products without age) and put their name into TvarVV */
1.339     brouard  1693:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  1694:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age */
                   1695:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   1696:       /* TvarVV={3,1,3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */        
                   1697:       /* 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  1698: int *Tvarsel; /**< Selected covariates for output */
                   1699: double *Tvalsel; /**< Selected modality value of covariate for output */
1.349     brouard  1700: 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  1701: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1702: 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  1703: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1704: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1705: int *Tage;
1.227     brouard  1706: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1707: 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  1708: 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*/ 
                   1709: 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  1710: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1711: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1712: int **Tvard;
1.330     brouard  1713: int **Tvardk;
1.227     brouard  1714: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1715: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1716: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1717:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1718:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1719: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1720: double *lsurv, *lpop, *tpop;
                   1721: 
1.231     brouard  1722: #define FD 1; /* Fixed dummy covariate */
                   1723: #define FQ 2; /* Fixed quantitative covariate */
                   1724: #define FP 3; /* Fixed product covariate */
                   1725: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1726: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1727: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1728: #define VD 10; /* Varying dummy covariate */
                   1729: #define VQ 11; /* Varying quantitative covariate */
                   1730: #define VP 12; /* Varying product covariate */
                   1731: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1732: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1733: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1734: #define APFD 16; /* Age product * fixed dummy covariate */
                   1735: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1736: #define APVD 18; /* Age product * varying dummy covariate */
                   1737: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1738: 
                   1739: #define FTYPE 1; /* Fixed covariate */
                   1740: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1741: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1742: 
                   1743: struct kmodel{
                   1744:        int maintype; /* main type */
                   1745:        int subtype; /* subtype */
                   1746: };
                   1747: struct kmodel modell[NCOVMAX];
                   1748: 
1.143     brouard  1749: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1750: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1751: 
                   1752: /**************** split *************************/
                   1753: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1754: {
                   1755:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1756:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1757:   */ 
                   1758:   char *ss;                            /* pointer */
1.186     brouard  1759:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1760: 
                   1761:   l1 = strlen(path );                  /* length of path */
                   1762:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1763:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1764:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1765:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1766:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1767:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1768:     /* get current working directory */
                   1769:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1770: #ifdef WIN32
                   1771:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1772: #else
                   1773:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1774: #endif
1.126     brouard  1775:       return( GLOCK_ERROR_GETCWD );
                   1776:     }
                   1777:     /* got dirc from getcwd*/
                   1778:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1779:   } else {                             /* strip directory from path */
1.126     brouard  1780:     ss++;                              /* after this, the filename */
                   1781:     l2 = strlen( ss );                 /* length of filename */
                   1782:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1783:     strcpy( name, ss );                /* save file name */
                   1784:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1785:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1786:     printf(" DIRC2 = %s \n",dirc);
                   1787:   }
                   1788:   /* We add a separator at the end of dirc if not exists */
                   1789:   l1 = strlen( dirc );                 /* length of directory */
                   1790:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1791:     dirc[l1] =  DIRSEPARATOR;
                   1792:     dirc[l1+1] = 0; 
                   1793:     printf(" DIRC3 = %s \n",dirc);
                   1794:   }
                   1795:   ss = strrchr( name, '.' );           /* find last / */
                   1796:   if (ss >0){
                   1797:     ss++;
                   1798:     strcpy(ext,ss);                    /* save extension */
                   1799:     l1= strlen( name);
                   1800:     l2= strlen(ss)+1;
                   1801:     strncpy( finame, name, l1-l2);
                   1802:     finame[l1-l2]= 0;
                   1803:   }
                   1804: 
                   1805:   return( 0 );                         /* we're done */
                   1806: }
                   1807: 
                   1808: 
                   1809: /******************************************/
                   1810: 
                   1811: void replace_back_to_slash(char *s, char*t)
                   1812: {
                   1813:   int i;
                   1814:   int lg=0;
                   1815:   i=0;
                   1816:   lg=strlen(t);
                   1817:   for(i=0; i<= lg; i++) {
                   1818:     (s[i] = t[i]);
                   1819:     if (t[i]== '\\') s[i]='/';
                   1820:   }
                   1821: }
                   1822: 
1.132     brouard  1823: char *trimbb(char *out, char *in)
1.137     brouard  1824: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1825:   char *s;
                   1826:   s=out;
                   1827:   while (*in != '\0'){
1.137     brouard  1828:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1829:       in++;
                   1830:     }
                   1831:     *out++ = *in++;
                   1832:   }
                   1833:   *out='\0';
                   1834:   return s;
                   1835: }
                   1836: 
1.351     brouard  1837: char *trimbtab(char *out, char *in)
                   1838: { /* Trim  blanks or tabs in line but keeps first blanks if line starts with blanks */
                   1839:   char *s;
                   1840:   s=out;
                   1841:   while (*in != '\0'){
                   1842:     while( (*in == ' ' || *in == '\t')){ /* && *(in+1) != '\0'){*/
                   1843:       in++;
                   1844:     }
                   1845:     *out++ = *in++;
                   1846:   }
                   1847:   *out='\0';
                   1848:   return s;
                   1849: }
                   1850: 
1.187     brouard  1851: /* char *substrchaine(char *out, char *in, char *chain) */
                   1852: /* { */
                   1853: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1854: /*   char *s, *t; */
                   1855: /*   t=in;s=out; */
                   1856: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1857: /*     *out++ = *in++; */
                   1858: /*   } */
                   1859: 
                   1860: /*   /\* *in matches *chain *\/ */
                   1861: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1862: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1863: /*   } */
                   1864: /*   in--; chain--; */
                   1865: /*   while ( (*in != '\0')){ */
                   1866: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1867: /*     *out++ = *in++; */
                   1868: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1869: /*   } */
                   1870: /*   *out='\0'; */
                   1871: /*   out=s; */
                   1872: /*   return out; */
                   1873: /* } */
                   1874: char *substrchaine(char *out, char *in, char *chain)
                   1875: {
                   1876:   /* Substract chain 'chain' from 'in', return and output 'out' */
1.349     brouard  1877:   /* in="V1+V1*age+age*age+V2", chain="+age*age" out="V1+V1*age+V2" */
1.187     brouard  1878: 
                   1879:   char *strloc;
                   1880: 
1.349     brouard  1881:   strcpy (out, in);                   /* out="V1+V1*age+age*age+V2" */
                   1882:   strloc = strstr(out, chain); /* strloc points to out at "+age*age+V2"  */
                   1883:   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  1884:   if(strloc != NULL){ 
1.349     brouard  1885:     /* will affect out */ /* strloc+strlen(chain)=|+V2 = "V1+V1*age+age*age|+V2" */ /* Will also work in Unicodek */
                   1886:     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)*/
                   1887:     /* equivalent to strcpy (strloc, strloc +strlen(chain)) if no overlap; Copies from "+V2" to V1+V1*age+ */
1.187     brouard  1888:   }
1.349     brouard  1889:   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  1890:   return out;
                   1891: }
                   1892: 
                   1893: 
1.145     brouard  1894: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1895: {
1.187     brouard  1896:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.349     brouard  1897:      and alocc starts after first occurence of char 'occ' : ex cutl(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1898:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1899:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1900:   */
1.160     brouard  1901:   char *s, *t;
1.145     brouard  1902:   t=in;s=in;
                   1903:   while ((*in != occ) && (*in != '\0')){
                   1904:     *alocc++ = *in++;
                   1905:   }
                   1906:   if( *in == occ){
                   1907:     *(alocc)='\0';
                   1908:     s=++in;
                   1909:   }
                   1910:  
                   1911:   if (s == t) {/* occ not found */
                   1912:     *(alocc-(in-s))='\0';
                   1913:     in=s;
                   1914:   }
                   1915:   while ( *in != '\0'){
                   1916:     *blocc++ = *in++;
                   1917:   }
                   1918: 
                   1919:   *blocc='\0';
                   1920:   return t;
                   1921: }
1.137     brouard  1922: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1923: {
1.187     brouard  1924:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1925:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1926:      gives blocc="abcdef2ghi" and alocc="j".
                   1927:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1928:   */
                   1929:   char *s, *t;
                   1930:   t=in;s=in;
                   1931:   while (*in != '\0'){
                   1932:     while( *in == occ){
                   1933:       *blocc++ = *in++;
                   1934:       s=in;
                   1935:     }
                   1936:     *blocc++ = *in++;
                   1937:   }
                   1938:   if (s == t) /* occ not found */
                   1939:     *(blocc-(in-s))='\0';
                   1940:   else
                   1941:     *(blocc-(in-s)-1)='\0';
                   1942:   in=s;
                   1943:   while ( *in != '\0'){
                   1944:     *alocc++ = *in++;
                   1945:   }
                   1946: 
                   1947:   *alocc='\0';
                   1948:   return s;
                   1949: }
                   1950: 
1.126     brouard  1951: int nbocc(char *s, char occ)
                   1952: {
                   1953:   int i,j=0;
                   1954:   int lg=20;
                   1955:   i=0;
                   1956:   lg=strlen(s);
                   1957:   for(i=0; i<= lg; i++) {
1.234     brouard  1958:     if  (s[i] == occ ) j++;
1.126     brouard  1959:   }
                   1960:   return j;
                   1961: }
                   1962: 
1.349     brouard  1963: int nboccstr(char *textin, char *chain)
                   1964: {
                   1965:   /* Counts the number of occurence of "chain"  in string textin */
                   1966:   /*  in="+V7*V4+age*V2+age*V3+age*V4"  chain="age" */
                   1967:   char *strloc;
                   1968:   
                   1969:   int i,j=0;
                   1970: 
                   1971:   i=0;
                   1972: 
                   1973:   strloc=textin; /* strloc points to "^+V7*V4+age+..." in textin */
                   1974:   for(;;) {
                   1975:     strloc= strstr(strloc,chain); /* strloc points to first character of chain in textin if found. Example strloc points^ to "+V7*V4+^age" in textin  */
                   1976:     if(strloc != NULL){
                   1977:       strloc = strloc+strlen(chain); /* strloc points to "+V7*V4+age^" in textin */
                   1978:       j++;
                   1979:     }else
                   1980:       break;
                   1981:   }
                   1982:   return j;
                   1983:   
                   1984: }
1.137     brouard  1985: /* void cutv(char *u,char *v, char*t, char occ) */
                   1986: /* { */
                   1987: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1988: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1989: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1990: /*   int i,lg,j,p=0; */
                   1991: /*   i=0; */
                   1992: /*   lg=strlen(t); */
                   1993: /*   for(j=0; j<=lg-1; j++) { */
                   1994: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1995: /*   } */
1.126     brouard  1996: 
1.137     brouard  1997: /*   for(j=0; j<p; j++) { */
                   1998: /*     (u[j] = t[j]); */
                   1999: /*   } */
                   2000: /*      u[p]='\0'; */
1.126     brouard  2001: 
1.137     brouard  2002: /*    for(j=0; j<= lg; j++) { */
                   2003: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   2004: /*   } */
                   2005: /* } */
1.126     brouard  2006: 
1.160     brouard  2007: #ifdef _WIN32
                   2008: char * strsep(char **pp, const char *delim)
                   2009: {
                   2010:   char *p, *q;
                   2011:          
                   2012:   if ((p = *pp) == NULL)
                   2013:     return 0;
                   2014:   if ((q = strpbrk (p, delim)) != NULL)
                   2015:   {
                   2016:     *pp = q + 1;
                   2017:     *q = '\0';
                   2018:   }
                   2019:   else
                   2020:     *pp = 0;
                   2021:   return p;
                   2022: }
                   2023: #endif
                   2024: 
1.126     brouard  2025: /********************** nrerror ********************/
                   2026: 
                   2027: void nrerror(char error_text[])
                   2028: {
                   2029:   fprintf(stderr,"ERREUR ...\n");
                   2030:   fprintf(stderr,"%s\n",error_text);
                   2031:   exit(EXIT_FAILURE);
                   2032: }
                   2033: /*********************** vector *******************/
                   2034: double *vector(int nl, int nh)
                   2035: {
                   2036:   double *v;
                   2037:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   2038:   if (!v) nrerror("allocation failure in vector");
                   2039:   return v-nl+NR_END;
                   2040: }
                   2041: 
                   2042: /************************ free vector ******************/
                   2043: void free_vector(double*v, int nl, int nh)
                   2044: {
                   2045:   free((FREE_ARG)(v+nl-NR_END));
                   2046: }
                   2047: 
                   2048: /************************ivector *******************************/
                   2049: int *ivector(long nl,long nh)
                   2050: {
                   2051:   int *v;
                   2052:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   2053:   if (!v) nrerror("allocation failure in ivector");
                   2054:   return v-nl+NR_END;
                   2055: }
                   2056: 
                   2057: /******************free ivector **************************/
                   2058: void free_ivector(int *v, long nl, long nh)
                   2059: {
                   2060:   free((FREE_ARG)(v+nl-NR_END));
                   2061: }
                   2062: 
                   2063: /************************lvector *******************************/
                   2064: long *lvector(long nl,long nh)
                   2065: {
                   2066:   long *v;
                   2067:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   2068:   if (!v) nrerror("allocation failure in ivector");
                   2069:   return v-nl+NR_END;
                   2070: }
                   2071: 
                   2072: /******************free lvector **************************/
                   2073: void free_lvector(long *v, long nl, long nh)
                   2074: {
                   2075:   free((FREE_ARG)(v+nl-NR_END));
                   2076: }
                   2077: 
                   2078: /******************* imatrix *******************************/
                   2079: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   2080:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   2081: { 
                   2082:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   2083:   int **m; 
                   2084:   
                   2085:   /* allocate pointers to rows */ 
                   2086:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   2087:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   2088:   m += NR_END; 
                   2089:   m -= nrl; 
                   2090:   
                   2091:   
                   2092:   /* allocate rows and set pointers to them */ 
                   2093:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   2094:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   2095:   m[nrl] += NR_END; 
                   2096:   m[nrl] -= ncl; 
                   2097:   
                   2098:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   2099:   
                   2100:   /* return pointer to array of pointers to rows */ 
                   2101:   return m; 
                   2102: } 
                   2103: 
                   2104: /****************** free_imatrix *************************/
                   2105: void free_imatrix(m,nrl,nrh,ncl,nch)
                   2106:       int **m;
                   2107:       long nch,ncl,nrh,nrl; 
                   2108:      /* free an int matrix allocated by imatrix() */ 
                   2109: { 
                   2110:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   2111:   free((FREE_ARG) (m+nrl-NR_END)); 
                   2112: } 
                   2113: 
                   2114: /******************* matrix *******************************/
                   2115: double **matrix(long nrl, long nrh, long ncl, long nch)
                   2116: {
                   2117:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   2118:   double **m;
                   2119: 
                   2120:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2121:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2122:   m += NR_END;
                   2123:   m -= nrl;
                   2124: 
                   2125:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2126:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2127:   m[nrl] += NR_END;
                   2128:   m[nrl] -= ncl;
                   2129: 
                   2130:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2131:   return m;
1.145     brouard  2132:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   2133: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   2134: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  2135:    */
                   2136: }
                   2137: 
                   2138: /*************************free matrix ************************/
                   2139: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   2140: {
                   2141:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2142:   free((FREE_ARG)(m+nrl-NR_END));
                   2143: }
                   2144: 
                   2145: /******************* ma3x *******************************/
                   2146: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   2147: {
                   2148:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   2149:   double ***m;
                   2150: 
                   2151:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2152:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2153:   m += NR_END;
                   2154:   m -= nrl;
                   2155: 
                   2156:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2157:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2158:   m[nrl] += NR_END;
                   2159:   m[nrl] -= ncl;
                   2160: 
                   2161:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2162: 
                   2163:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   2164:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2165:   m[nrl][ncl] += NR_END;
                   2166:   m[nrl][ncl] -= nll;
                   2167:   for (j=ncl+1; j<=nch; j++) 
                   2168:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2169:   
                   2170:   for (i=nrl+1; i<=nrh; i++) {
                   2171:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2172:     for (j=ncl+1; j<=nch; j++) 
                   2173:       m[i][j]=m[i][j-1]+nlay;
                   2174:   }
                   2175:   return m; 
                   2176:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2177:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2178:   */
                   2179: }
                   2180: 
                   2181: /*************************free ma3x ************************/
                   2182: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2183: {
                   2184:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2185:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2186:   free((FREE_ARG)(m+nrl-NR_END));
                   2187: }
                   2188: 
                   2189: /*************** function subdirf ***********/
                   2190: char *subdirf(char fileres[])
                   2191: {
                   2192:   /* Caution optionfilefiname is hidden */
                   2193:   strcpy(tmpout,optionfilefiname);
                   2194:   strcat(tmpout,"/"); /* Add to the right */
                   2195:   strcat(tmpout,fileres);
                   2196:   return tmpout;
                   2197: }
                   2198: 
                   2199: /*************** function subdirf2 ***********/
                   2200: char *subdirf2(char fileres[], char *preop)
                   2201: {
1.314     brouard  2202:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2203:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2204:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2205:   /* Caution optionfilefiname is hidden */
                   2206:   strcpy(tmpout,optionfilefiname);
                   2207:   strcat(tmpout,"/");
                   2208:   strcat(tmpout,preop);
                   2209:   strcat(tmpout,fileres);
                   2210:   return tmpout;
                   2211: }
                   2212: 
                   2213: /*************** function subdirf3 ***********/
                   2214: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2215: {
                   2216:   
                   2217:   /* Caution optionfilefiname is hidden */
                   2218:   strcpy(tmpout,optionfilefiname);
                   2219:   strcat(tmpout,"/");
                   2220:   strcat(tmpout,preop);
                   2221:   strcat(tmpout,preop2);
                   2222:   strcat(tmpout,fileres);
                   2223:   return tmpout;
                   2224: }
1.213     brouard  2225:  
                   2226: /*************** function subdirfext ***********/
                   2227: char *subdirfext(char fileres[], char *preop, char *postop)
                   2228: {
                   2229:   
                   2230:   strcpy(tmpout,preop);
                   2231:   strcat(tmpout,fileres);
                   2232:   strcat(tmpout,postop);
                   2233:   return tmpout;
                   2234: }
1.126     brouard  2235: 
1.213     brouard  2236: /*************** function subdirfext3 ***********/
                   2237: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2238: {
                   2239:   
                   2240:   /* Caution optionfilefiname is hidden */
                   2241:   strcpy(tmpout,optionfilefiname);
                   2242:   strcat(tmpout,"/");
                   2243:   strcat(tmpout,preop);
                   2244:   strcat(tmpout,fileres);
                   2245:   strcat(tmpout,postop);
                   2246:   return tmpout;
                   2247: }
                   2248:  
1.162     brouard  2249: char *asc_diff_time(long time_sec, char ascdiff[])
                   2250: {
                   2251:   long sec_left, days, hours, minutes;
                   2252:   days = (time_sec) / (60*60*24);
                   2253:   sec_left = (time_sec) % (60*60*24);
                   2254:   hours = (sec_left) / (60*60) ;
                   2255:   sec_left = (sec_left) %(60*60);
                   2256:   minutes = (sec_left) /60;
                   2257:   sec_left = (sec_left) % (60);
                   2258:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2259:   return ascdiff;
                   2260: }
                   2261: 
1.126     brouard  2262: /***************** f1dim *************************/
                   2263: extern int ncom; 
                   2264: extern double *pcom,*xicom;
                   2265: extern double (*nrfunc)(double []); 
                   2266:  
                   2267: double f1dim(double x) 
                   2268: { 
                   2269:   int j; 
                   2270:   double f;
                   2271:   double *xt; 
                   2272:  
                   2273:   xt=vector(1,ncom); 
                   2274:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2275:   f=(*nrfunc)(xt); 
                   2276:   free_vector(xt,1,ncom); 
                   2277:   return f; 
                   2278: } 
                   2279: 
                   2280: /*****************brent *************************/
                   2281: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2282: {
                   2283:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2284:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2285:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2286:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2287:    * returned function value. 
                   2288:   */
1.126     brouard  2289:   int iter; 
                   2290:   double a,b,d,etemp;
1.159     brouard  2291:   double fu=0,fv,fw,fx;
1.164     brouard  2292:   double ftemp=0.;
1.126     brouard  2293:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2294:   double e=0.0; 
                   2295:  
                   2296:   a=(ax < cx ? ax : cx); 
                   2297:   b=(ax > cx ? ax : cx); 
                   2298:   x=w=v=bx; 
                   2299:   fw=fv=fx=(*f)(x); 
                   2300:   for (iter=1;iter<=ITMAX;iter++) { 
                   2301:     xm=0.5*(a+b); 
                   2302:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2303:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2304:     printf(".");fflush(stdout);
                   2305:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2306: #ifdef DEBUGBRENT
1.126     brouard  2307:     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);
                   2308:     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);
                   2309:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2310: #endif
                   2311:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2312:       *xmin=x; 
                   2313:       return fx; 
                   2314:     } 
                   2315:     ftemp=fu;
                   2316:     if (fabs(e) > tol1) { 
                   2317:       r=(x-w)*(fx-fv); 
                   2318:       q=(x-v)*(fx-fw); 
                   2319:       p=(x-v)*q-(x-w)*r; 
                   2320:       q=2.0*(q-r); 
                   2321:       if (q > 0.0) p = -p; 
                   2322:       q=fabs(q); 
                   2323:       etemp=e; 
                   2324:       e=d; 
                   2325:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2326:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2327:       else { 
1.224     brouard  2328:                                d=p/q; 
                   2329:                                u=x+d; 
                   2330:                                if (u-a < tol2 || b-u < tol2) 
                   2331:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2332:       } 
                   2333:     } else { 
                   2334:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2335:     } 
                   2336:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2337:     fu=(*f)(u); 
                   2338:     if (fu <= fx) { 
                   2339:       if (u >= x) a=x; else b=x; 
                   2340:       SHFT(v,w,x,u) 
1.183     brouard  2341:       SHFT(fv,fw,fx,fu) 
                   2342:     } else { 
                   2343:       if (u < x) a=u; else b=u; 
                   2344:       if (fu <= fw || w == x) { 
1.224     brouard  2345:                                v=w; 
                   2346:                                w=u; 
                   2347:                                fv=fw; 
                   2348:                                fw=fu; 
1.183     brouard  2349:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2350:                                v=u; 
                   2351:                                fv=fu; 
1.183     brouard  2352:       } 
                   2353:     } 
1.126     brouard  2354:   } 
                   2355:   nrerror("Too many iterations in brent"); 
                   2356:   *xmin=x; 
                   2357:   return fx; 
                   2358: } 
                   2359: 
                   2360: /****************** mnbrak ***********************/
                   2361: 
                   2362: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2363:            double (*func)(double)) 
1.183     brouard  2364: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2365: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2366: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2367: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2368:    */
1.126     brouard  2369:   double ulim,u,r,q, dum;
                   2370:   double fu; 
1.187     brouard  2371: 
                   2372:   double scale=10.;
                   2373:   int iterscale=0;
                   2374: 
                   2375:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2376:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2377: 
                   2378: 
                   2379:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2380:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2381:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2382:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2383:   /* } */
                   2384: 
1.126     brouard  2385:   if (*fb > *fa) { 
                   2386:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2387:     SHFT(dum,*fb,*fa,dum) 
                   2388:   } 
1.126     brouard  2389:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2390:   *fc=(*func)(*cx); 
1.183     brouard  2391: #ifdef DEBUG
1.224     brouard  2392:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2393:   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  2394: #endif
1.224     brouard  2395:   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  2396:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2397:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2398:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2399:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2400:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2401:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2402:       fu=(*func)(u); 
1.163     brouard  2403: #ifdef DEBUG
                   2404:       /* f(x)=A(x-u)**2+f(u) */
                   2405:       double A, fparabu; 
                   2406:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2407:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2408:       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);
                   2409:       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  2410:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2411:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2412:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2413:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2414: #endif 
1.184     brouard  2415: #ifdef MNBRAKORIGINAL
1.183     brouard  2416: #else
1.191     brouard  2417: /*       if (fu > *fc) { */
                   2418: /* #ifdef DEBUG */
                   2419: /*       printf("mnbrak4  fu > fc \n"); */
                   2420: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2421: /* #endif */
                   2422: /*     /\* 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 *\\/  *\/ */
                   2423: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2424: /*     dum=u; /\* Shifting c and u *\/ */
                   2425: /*     u = *cx; */
                   2426: /*     *cx = dum; */
                   2427: /*     dum = fu; */
                   2428: /*     fu = *fc; */
                   2429: /*     *fc =dum; */
                   2430: /*       } else { /\* end *\/ */
                   2431: /* #ifdef DEBUG */
                   2432: /*       printf("mnbrak3  fu < fc \n"); */
                   2433: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2434: /* #endif */
                   2435: /*     dum=u; /\* Shifting c and u *\/ */
                   2436: /*     u = *cx; */
                   2437: /*     *cx = dum; */
                   2438: /*     dum = fu; */
                   2439: /*     fu = *fc; */
                   2440: /*     *fc =dum; */
                   2441: /*       } */
1.224     brouard  2442: #ifdef DEBUGMNBRAK
                   2443:                 double A, fparabu; 
                   2444:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2445:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2446:      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);
                   2447:      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  2448: #endif
1.191     brouard  2449:       dum=u; /* Shifting c and u */
                   2450:       u = *cx;
                   2451:       *cx = dum;
                   2452:       dum = fu;
                   2453:       fu = *fc;
                   2454:       *fc =dum;
1.183     brouard  2455: #endif
1.162     brouard  2456:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2457: #ifdef DEBUG
1.224     brouard  2458:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2459:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2460: #endif
1.126     brouard  2461:       fu=(*func)(u); 
                   2462:       if (fu < *fc) { 
1.183     brouard  2463: #ifdef DEBUG
1.224     brouard  2464:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2465:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2466: #endif
                   2467:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2468:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2469: #ifdef DEBUG
                   2470:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2471: #endif
                   2472:       } 
1.162     brouard  2473:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2474: #ifdef DEBUG
1.224     brouard  2475:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2476:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2477: #endif
1.126     brouard  2478:       u=ulim; 
                   2479:       fu=(*func)(u); 
1.183     brouard  2480:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2481: #ifdef DEBUG
1.224     brouard  2482:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2483:       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  2484: #endif
1.126     brouard  2485:       u=(*cx)+GOLD*(*cx-*bx); 
                   2486:       fu=(*func)(u); 
1.224     brouard  2487: #ifdef DEBUG
                   2488:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2489:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2490: #endif
1.183     brouard  2491:     } /* end tests */
1.126     brouard  2492:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2493:     SHFT(*fa,*fb,*fc,fu) 
                   2494: #ifdef DEBUG
1.224     brouard  2495:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2496:       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  2497: #endif
                   2498:   } /* 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  2499: } 
                   2500: 
                   2501: /*************** linmin ************************/
1.162     brouard  2502: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2503: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2504: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2505: the value of func at the returned location p . This is actually all accomplished by calling the
                   2506: routines mnbrak and brent .*/
1.126     brouard  2507: int ncom; 
                   2508: double *pcom,*xicom;
                   2509: double (*nrfunc)(double []); 
                   2510:  
1.224     brouard  2511: #ifdef LINMINORIGINAL
1.126     brouard  2512: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2513: #else
                   2514: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2515: #endif
1.126     brouard  2516: { 
                   2517:   double brent(double ax, double bx, double cx, 
                   2518:               double (*f)(double), double tol, double *xmin); 
                   2519:   double f1dim(double x); 
                   2520:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2521:              double *fc, double (*func)(double)); 
                   2522:   int j; 
                   2523:   double xx,xmin,bx,ax; 
                   2524:   double fx,fb,fa;
1.187     brouard  2525: 
1.203     brouard  2526: #ifdef LINMINORIGINAL
                   2527: #else
                   2528:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2529: #endif
                   2530:   
1.126     brouard  2531:   ncom=n; 
                   2532:   pcom=vector(1,n); 
                   2533:   xicom=vector(1,n); 
                   2534:   nrfunc=func; 
                   2535:   for (j=1;j<=n;j++) { 
                   2536:     pcom[j]=p[j]; 
1.202     brouard  2537:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2538:   } 
1.187     brouard  2539: 
1.203     brouard  2540: #ifdef LINMINORIGINAL
                   2541:   xx=1.;
                   2542: #else
                   2543:   axs=0.0;
                   2544:   xxs=1.;
                   2545:   do{
                   2546:     xx= xxs;
                   2547: #endif
1.187     brouard  2548:     ax=0.;
                   2549:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2550:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2551:     /* 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))   */
                   2552:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2553:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2554:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2555:     /* 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  2556: #ifdef LINMINORIGINAL
                   2557: #else
                   2558:     if (fx != fx){
1.224     brouard  2559:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2560:                        printf("|");
                   2561:                        fprintf(ficlog,"|");
1.203     brouard  2562: #ifdef DEBUGLINMIN
1.224     brouard  2563:                        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  2564: #endif
                   2565:     }
1.224     brouard  2566:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2567: #endif
                   2568:   
1.191     brouard  2569: #ifdef DEBUGLINMIN
                   2570:   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  2571:   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  2572: #endif
1.224     brouard  2573: #ifdef LINMINORIGINAL
                   2574: #else
1.317     brouard  2575:   if(fb == fx){ /* Flat function in the direction */
                   2576:     xmin=xx;
1.224     brouard  2577:     *flat=1;
1.317     brouard  2578:   }else{
1.224     brouard  2579:     *flat=0;
                   2580: #endif
                   2581:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2582:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2583:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2584:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2585:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2586:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2587: #ifdef DEBUG
1.224     brouard  2588:   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);
                   2589:   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);
                   2590: #endif
                   2591: #ifdef LINMINORIGINAL
                   2592: #else
                   2593:                        }
1.126     brouard  2594: #endif
1.191     brouard  2595: #ifdef DEBUGLINMIN
                   2596:   printf("linmin end ");
1.202     brouard  2597:   fprintf(ficlog,"linmin end ");
1.191     brouard  2598: #endif
1.126     brouard  2599:   for (j=1;j<=n;j++) { 
1.203     brouard  2600: #ifdef LINMINORIGINAL
                   2601:     xi[j] *= xmin; 
                   2602: #else
                   2603: #ifdef DEBUGLINMIN
                   2604:     if(xxs <1.0)
                   2605:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2606: #endif
                   2607:     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) */
                   2608: #ifdef DEBUGLINMIN
                   2609:     if(xxs <1.0)
                   2610:       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 );
                   2611: #endif
                   2612: #endif
1.187     brouard  2613:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2614:   } 
1.191     brouard  2615: #ifdef DEBUGLINMIN
1.203     brouard  2616:   printf("\n");
1.191     brouard  2617:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2618:   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  2619:   for (j=1;j<=n;j++) { 
1.202     brouard  2620:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2621:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2622:     if(j % ncovmodel == 0){
1.191     brouard  2623:       printf("\n");
1.202     brouard  2624:       fprintf(ficlog,"\n");
                   2625:     }
1.191     brouard  2626:   }
1.203     brouard  2627: #else
1.191     brouard  2628: #endif
1.126     brouard  2629:   free_vector(xicom,1,n); 
                   2630:   free_vector(pcom,1,n); 
                   2631: } 
                   2632: 
1.359     brouard  2633: /**** praxis gegen ****/
                   2634: 
                   2635: /* This has been tested by Visual C from Microsoft and works */
                   2636: /* meaning tha valgrind could be wrong */
                   2637: /*********************************************************************/
                   2638: /*     f u n c t i o n     p r a x i s                              */
                   2639: /*                                                                   */
                   2640: /* praxis is a general purpose routine for the minimization of a     */
                   2641: /* function in several variables. the algorithm used is a modifi-    */
                   2642: /* cation of conjugate gradient search method by powell. the changes */
                   2643: /* are due to r.p. brent, who gives an algol-w program, which served */
                   2644: /* as a basis for this function.                                     */
                   2645: /*                                                                   */
                   2646: /* references:                                                       */
                   2647: /*     - powell, m.j.d., 1964. an efficient method for finding       */
                   2648: /*       the minimum of a function in several variables without      */
                   2649: /*       calculating derivatives, computer journal, 7, 155-162       */
                   2650: /*     - brent, r.p., 1973. algorithms for minimization without      */
                   2651: /*       derivatives, prentice hall, englewood cliffs.               */
                   2652: /*                                                                   */
                   2653: /*     problems, suggestions or improvements are always wellcome     */
                   2654: /*                       karl gegenfurtner   07/08/87                */
                   2655: /*                                           c - version             */
                   2656: /*********************************************************************/
                   2657: /*                                                                   */
                   2658: /* usage: min = praxis(tol, macheps, h, n, prin, x, func)      */
                   2659: /* macheps has been suppressed because it is replaced by DBL_EPSILON */
                   2660: /* and if it was an argument of praxis (as it is in original brent)  */
                   2661: /* it should be declared external */
                   2662: /* usage: min = praxis(tol, h, n, prin, x, func)      */
                   2663: /* was    min = praxis(fun, x, n);                                   */
                   2664: /*                                                                   */
                   2665: /*  fun        the function to be minimized. fun is called from      */
                   2666: /*             praxis with x and n as arguments                      */
                   2667: /*  x          a double array containing the initial guesses for     */
                   2668: /*             the minimum, which will contain the solution on       */
                   2669: /*             return                                                */
                   2670: /*  n          an integer specifying the number of unknown           */
                   2671: /*             parameters                                            */
                   2672: /*  min        praxis returns the least calculated value of fun      */
                   2673: /*                                                                   */
                   2674: /* some additional global variables control some more aspects of     */
                   2675: /* the inner workings of praxis. setting them is optional, they      */
                   2676: /* are all set to some reasonable default values given below.        */
                   2677: /*                                                                   */
                   2678: /*   prin      controls the printed output from the routine.         */
                   2679: /*             0 -> no output                                        */
                   2680: /*             1 -> print only starting and final values             */
                   2681: /*             2 -> detailed map of the minimization process         */
                   2682: /*             3 -> print also eigenvalues and vectors of the        */
                   2683: /*                  search directions                                */
                   2684: /*             the default value is 1                                */
                   2685: /*  tol        is the tolerance allowed for the precision of the     */
                   2686: /*             solution. praxis returns if the criterion             */
                   2687: /*             2 * ||x[k]-x[k-1]|| <= sqrt(macheps) * ||x[k]|| + tol */
                   2688: /*             is fulfilled more than ktm times.                     */
                   2689: /*             the default value depends on the machine precision    */
                   2690: /*  ktm        see just above. default is 1, and a value of 4 leads  */
                   2691: /*             to a very(!) cautious stopping criterion.             */
                   2692: /*  h0 or step       is a steplength parameter and should be set equal     */
                   2693: /*             to the expected distance from the solution.           */
                   2694: /*             exceptionally small or large values of step lead to   */
                   2695: /*             slower convergence on the first few iterations        */
                   2696: /*             the default value for step is 1.0                     */
                   2697: /*  scbd       is a scaling parameter. 1.0 is the default and        */
                   2698: /*             indicates no scaling. if the scales for the different */
                   2699: /*             parameters are very different, scbd should be set to  */
                   2700: /*             a value of about 10.0.                                */
                   2701: /*  illc       should be set to true (1) if the problem is known to  */
                   2702: /*             be ill-conditioned. the default is false (0). this    */
                   2703: /*             variable is automatically set, when praxis finds      */
                   2704: /*             the problem to be ill-conditioned during iterations.  */
                   2705: /*  maxfun     is the maximum number of calls to fun allowed. praxis */
                   2706: /*             will return after maxfun calls to fun even when the   */
                   2707: /*             minimum is not yet found. the default value of 0      */
                   2708: /*             indicates no limit on the number of calls.            */
                   2709: /*             this return condition is only checked every n         */
                   2710: /*             iterations.                                           */
                   2711: /*                                                                   */
                   2712: /*********************************************************************/
                   2713: 
                   2714: #include <math.h>
                   2715: #include <stdio.h>
                   2716: #include <stdlib.h>
                   2717: #include <float.h> /* for DBL_EPSILON */
                   2718: /* #include "machine.h" */
                   2719: 
                   2720: 
                   2721: /* extern void minfit(int n, double eps, double tol, double **ab, double q[]); */
                   2722: /* extern void minfit(int n, double eps, double tol, double ab[N][N], double q[]); */
                   2723: /* control parameters */
                   2724: /* control parameters */
                   2725: #define SQREPSILON 1.0e-19
                   2726: /* #define EPSILON 1.0e-8 */ /* in main */
                   2727: 
                   2728: double tol = SQREPSILON,
                   2729:        scbd = 1.0,
                   2730:        step = 1.0;
                   2731: int    ktm = 1,
                   2732:        /* prin = 2, */
                   2733:        maxfun = 0,
                   2734:        illc = 0;
                   2735:        
                   2736: /* some global variables */
                   2737: static int i, j, k, k2, nl, nf, kl, kt;
                   2738: /* static double s; */
                   2739: double sl, dn, dmin,
                   2740:        fx, f1, lds, ldt, sf, df,
                   2741:        qf1, qd0, qd1, qa, qb, qc,
                   2742:        m2, m4, small_windows, vsmall, large, 
                   2743:        vlarge, ldfac, t2;
                   2744: /* static double d[N], y[N], z[N], */
                   2745: /*        q0[N], q1[N], v[N][N]; */
                   2746: 
                   2747: static double *d, *y, *z;
                   2748: static double  *q0, *q1, **v;
                   2749: double *tflin; /* used in flin: return (*fun)(tflin, n); */
                   2750: double *e; /* used in minfit, don't konw how to free memory and thus made global */
                   2751: /* static double s, sl, dn, dmin, */
                   2752: /*        fx, f1, lds, ldt, sf, df, */
                   2753: /*        qf1, qd0, qd1, qa, qb, qc, */
                   2754: /*        m2, m4, small, vsmall, large,  */
                   2755: /*        vlarge, ldfac, t2; */
                   2756: /* static double d[N], y[N], z[N], */
                   2757: /*        q0[N], q1[N], v[N][N]; */
                   2758: 
                   2759: /* these will be set by praxis to point to it's arguments */
                   2760: static int prin; /* added */
                   2761: static int n;
                   2762: static double *x;
                   2763: static double (*fun)();
                   2764: /* static double (*fun)(double *x, int n); */
                   2765: 
                   2766: /* these will be set by praxis to the global control parameters */
                   2767: /* static double h, macheps, t; */
                   2768: extern double macheps;
                   2769: static double h;
                   2770: static double t;
                   2771: 
                   2772: static double 
                   2773: drandom()      /* return random no between 0 and 1 */
                   2774: {
                   2775:    return (double)(rand()%(8192*2))/(double)(8192*2);
                   2776: }
                   2777: 
                   2778: static void sort()             /* d and v in descending order */
                   2779: {
                   2780:    int k, i, j;
                   2781:    double s;
                   2782: 
                   2783:    for (i=1; i<=n-1; i++) {
                   2784:        k = i; s = d[i];
                   2785:        for (j=i+1; j<=n; j++) {
                   2786:            if (d[j] > s) {
                   2787:              k = j;
                   2788:              s = d[j];
                   2789:           }
                   2790:        }
                   2791:        if (k > i) {
                   2792:          d[k] = d[i];
                   2793:          d[i] = s;
                   2794:          for (j=1; j<=n; j++) {
                   2795:              s = v[j][i];
                   2796:              v[j][i] = v[j][k];
                   2797:              v[j][k] = s;
                   2798:          }
                   2799:        }
                   2800:    }
                   2801: }
                   2802: 
                   2803: double randbrent ( int *naught )
                   2804: {
                   2805:   double ran1, ran3[127], half;
                   2806:   int ran2, q, r, i, j;
                   2807:   int init=0; /* false */
                   2808:   double rr;
                   2809:   /* REAL*8 RAN1,RAN3(127),HALF */
                   2810: 
                   2811:   /*     INTEGER RAN2,Q,R */
                   2812:   /*     LOGICAL INIT */
                   2813:   /*     DATA INIT/.FALSE./ */
                   2814:   /*     IF (INIT) GO TO 3 */
                   2815:   if(!init){ 
                   2816: /*       R = MOD(NAUGHT,8190) + 1 *//* 1804289383 rand () */
                   2817:     r = *naught % 8190 + 1;/* printf(" naught r %d %d",*naught,r); */
                   2818:     ran2=127;
                   2819:     for(i=ran2; i>0; i--){
                   2820: /*       RAN2 = 128 */
                   2821: /*       DO 2 I=1,127 */
                   2822:       ran2 = ran2-1;
                   2823: /*          RAN2 = RAN2 - 1 */
                   2824:       ran1 = -pow(2.0,55);
                   2825: /*          RAN1 = -2.D0**55 */
                   2826: /*          DO 1 J=1,7 */
                   2827:       for(j=1; j<=7;j++){
                   2828: /*             R = MOD(1756*R,8191) */
                   2829:        r = (1756*r) % 8191;/* printf(" i=%d (1756*r)%8191=%d",j,r); */
                   2830:        q=r/32;
                   2831: /*             Q = R/32 */
                   2832: /* 1           RAN1 = (RAN1 + Q)*(1.0D0/256) */
                   2833:        ran1 =(ran1+q)*(1.0/256);
                   2834:       }
                   2835: /* 2        RAN3(RAN2) = RAN1 */
                   2836:       ran3[ran2] = ran1; /* printf(" ran2=%d ran1=%.7g \n",ran2,ran1); */ 
                   2837:     }
                   2838: /*       INIT = .TRUE. */
                   2839:     init=1;
                   2840: /* 3     IF (RAN2.EQ.1) RAN2 = 128 */
                   2841:   }
                   2842:   if(ran2 == 0) ran2 = 126;
                   2843:   else ran2 = ran2 -1;
                   2844:   /* RAN2 = RAN2 - 1 */
                   2845:   /* RAN1 = RAN1 + RAN3(RAN2) */
                   2846:   ran1 = ran1 + ran3[ran2];/* printf("BIS ran2=%d ran1=%.7g \n",ran2,ran1);  */
                   2847:   half= 0.5;
                   2848:   /* HALF = .5D0 */
                   2849:   /* IF (RAN1.GE.0.D0) HALF = -HALF */
                   2850:   if(ran1 >= 0.) half =-half;
                   2851:   ran1 = ran1 +half;
                   2852:   ran3[ran2] = ran1;
                   2853:   rr= ran1+0.5;
                   2854:   /* RAN1 = RAN1 + HALF */
                   2855:   /*   RAN3(RAN2) = RAN1 */
                   2856:   /*   RANDOM = RAN1 + .5D0 */
                   2857: /*   r = ( ( double ) ( *seed ) ) * 4.656612875E-10; */
                   2858:   return rr;
                   2859: }
                   2860: static void matprint(char *s, double **v, int m, int n)
                   2861: /* char *s; */
                   2862: /* double v[N][N]; */
                   2863: {
                   2864: #define INCX 8
                   2865:   int i;
                   2866:  
                   2867:   int i2hi;
                   2868:   int ihi;
                   2869:   int ilo;
                   2870:   int i2lo;
                   2871:   int jlo=1;
                   2872:   int j;
                   2873:   int j2hi;
                   2874:   int jhi;
                   2875:   int j2lo;
                   2876:   ilo=1;
                   2877:   ihi=n;
                   2878:   jlo=1;
                   2879:   jhi=n;
                   2880:   
                   2881:   printf ("\n" );
                   2882:   printf ("%s\n", s );
                   2883:   for ( j2lo = jlo; j2lo <= jhi; j2lo = j2lo + INCX )
                   2884:   {
                   2885:     j2hi = j2lo + INCX - 1;
                   2886:     if ( n < j2hi )
                   2887:     {
                   2888:       j2hi = n;
                   2889:     }
                   2890:     if ( jhi < j2hi )
                   2891:     {
                   2892:       j2hi = jhi;
                   2893:     }
                   2894: 
                   2895:     /* fprintf ( ficlog, "\n" ); */
                   2896:     printf ("\n" );
                   2897: /*
                   2898:   For each column J in the current range...
                   2899: 
                   2900:   Write the header.
                   2901: */
                   2902:     /* fprintf ( ficlog, "  Col:  "); */
                   2903:     printf ("Col:");
                   2904:     for ( j = j2lo; j <= j2hi; j++ )
                   2905:     {
                   2906:       /* fprintf ( ficlog, "  %7d     ", j - 1 ); */
                   2907:       /* printf (" %9d      ", j - 1 ); */
                   2908:       printf (" %9d      ", j );
                   2909:     }
                   2910:     /* fprintf ( ficlog, "\n" ); */
                   2911:     /* fprintf ( ficlog, "  Row\n" ); */
                   2912:     /* fprintf ( ficlog, "\n" ); */
                   2913:     printf ("\n" );
                   2914:     printf ("  Row\n" );
                   2915:     printf ("\n" );
                   2916: /*
                   2917:   Determine the range of the rows in this strip.
                   2918: */
                   2919:     if ( 1 < ilo ){
                   2920:       i2lo = ilo;
                   2921:     }else{
                   2922:       i2lo = 1;
                   2923:     }
                   2924:     if ( m < ihi ){
                   2925:       i2hi = m;
                   2926:     }else{
                   2927:       i2hi = ihi;
                   2928:     }
                   2929: 
                   2930:     for ( i = i2lo; i <= i2hi; i++ ){
                   2931: /*
                   2932:   Print out (up to) 5 entries in row I, that lie in the current strip.
                   2933: */
                   2934:       /* fprintf ( ficlog, "%5d:", i - 1 ); */
                   2935:       /* printf ("%5d:", i - 1 ); */
                   2936:       printf ("%5d:", i );
                   2937:       for ( j = j2lo; j <= j2hi; j++ )
                   2938:       {
                   2939:         /* fprintf ( ficlog, "  %14g", a[i-1+(j-1)*m] ); */
                   2940:         /* printf ("%14.7g  ", a[i-1+(j-1)*m] ); */
                   2941:            /* printf("%14.7f  ", v[i-1][j-1]); */
                   2942:            printf("%14.7f  ", v[i][j]);
                   2943:         /* fprintf ( stdout, "  %14g", a[i-1+(j-1)*m] ); */
                   2944:       }
                   2945:       /* fprintf ( ficlog, "\n" ); */
                   2946:       printf ("\n" );
                   2947:     }
                   2948:   }
                   2949:  
                   2950:    /* printf("%s\n", s); */
                   2951:    /* for (k=0; k<n; k++) { */
                   2952:    /*     for (i=0; i<n; i++) { */
                   2953:    /*         /\* printf("%20.10e ", v[k][i]); *\/ */
                   2954:    /*     } */
                   2955:    /*     printf("\n"); */
                   2956:    /* } */
                   2957: #undef INCX  
                   2958: }
                   2959: 
                   2960: void vecprint(char *s, double *x, int n)
                   2961: /* char *s; */
                   2962: /* double x[N]; */
                   2963: {
                   2964:    int i=0;
                   2965:    
                   2966:    printf(" %s", s);
                   2967:    /* for (i=0; i<n; i++) */
                   2968:    for (i=1; i<=n; i++)
                   2969:      printf ("  %14.7g",  x[i] );
                   2970:      /* printf("  %8d: %14g\n", i, x[i]); */
                   2971:    printf ("\n" ); 
                   2972: }
                   2973: 
                   2974: static void print()            /* print a line of traces */
                   2975: {
                   2976:  
                   2977: 
                   2978:    printf("\n");
                   2979:    /* printf("... chi square reduced to ... %20.10e\n", fx); */
                   2980:    /* printf("... after %u function calls ...\n", nf); */
                   2981:    /* printf("... including %u linear searches ...\n", nl); */
                   2982:    printf("%10d    %10d%14.7g",nl, nf, fx);
                   2983:    vecprint("... current values of x ...", x, n);
                   2984: }
                   2985: /* static void print2(int n, double *x, int prin, double fx, int nf, int nl) */ /* print a line of traces */
                   2986: static void print2() /* print a line of traces */
                   2987: {
                   2988:   int i; double fmin=0.;
                   2989: 
                   2990:    /* printf("\n"); */
                   2991:    /* printf("... chi square reduced to ... %20.10e\n", fx); */
                   2992:    /* printf("... after %u function calls ...\n", nf); */
                   2993:    /* printf("... including %u linear searches ...\n", nl); */
                   2994:    /* printf("%10d    %10d%14.7g",nl, nf, fx); */
                   2995:   printf ( "\n" );
                   2996:   printf ( "  Linear searches      %d", nl );
                   2997:   /* printf ( "  Linear searches      %d\n", nl ); */
                   2998:   /* printf ( "  Function evaluations %d\n", nf ); */
                   2999:   /* printf ( "  Function value FX = %g\n", fx ); */
                   3000:   printf ( "  Function evaluations %d", nf );
                   3001:   printf ( "  Function value FX = %.12lf\n", fx );
                   3002: #ifdef DEBUGPRAX
                   3003:    printf("n=%d prin=%d\n",n,prin);
                   3004: #endif
                   3005:    if(fx <= fmin) printf(" UNDEFINED "); else  printf("%14.7g",log(fx-fmin));
                   3006:    if ( n <= 4 || 2 < prin )
                   3007:    {
                   3008:      /* for(i=1;i<=n;i++)printf("%14.7g",x[i-1]); */
                   3009:      for(i=1;i<=n;i++)printf("%14.7g",x[i]);
                   3010:      /* r8vec_print ( n, x, "  X:" ); */
                   3011:    }
                   3012:    printf("\n");
                   3013:  }
                   3014: 
                   3015: 
                   3016: /* #ifdef MSDOS */
                   3017: /* static double tflin[N]; */
                   3018: /* #endif */
                   3019: 
                   3020: static double flin(double l, int j)
                   3021: /* double l; */
                   3022: {
                   3023:    int i;
                   3024:    /* #ifndef MSDOS */
                   3025:    /*    double tflin[N]; */
                   3026:    /* #endif    */
                   3027:    /* double *tflin; */ /* Be careful to put tflin on a vector n */
                   3028: 
                   3029:    /* j is used from 0 to n-1 and can be -1 for parabolic search */
                   3030: 
                   3031:    /* if (j != -1) {           /\* linear search *\/ */
                   3032:    if (j > 0) {                /* linear search */
                   3033:      /* for (i=0; i<n; i++){ */
                   3034:      for (i=1; i<=n; i++){
                   3035:           tflin[i] = x[i] + l *v[i][j];
                   3036: #ifdef DEBUGPRAX
                   3037:          /* 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); */
                   3038:          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);
                   3039: #endif
                   3040:      }
                   3041:    }
                   3042:    else {                      /* search along parabolic space curve */
                   3043:       qa = l*(l-qd1)/(qd0*(qd0+qd1));
                   3044:       qb = (l+qd0)*(qd1-l)/(qd0*qd1);
                   3045:       qc = l*(l+qd0)/(qd1*(qd0+qd1));
                   3046: #ifdef DEBUGPRAX      
                   3047:       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);
                   3048: #endif
                   3049:       /* for (i=0; i<n; i++){ */
                   3050:       for (i=1; i<=n; i++){
                   3051:           tflin[i] = qa*q0[i]+qb*x[i]+qc*q1[i];
                   3052: #ifdef DEBUGPRAX
                   3053:           /* 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]); */
                   3054:           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]);
                   3055: #endif
                   3056:       }
                   3057:    }
                   3058:    nf++;
                   3059: 
                   3060: #ifdef NR_SHIFT
                   3061:       return (*fun)((tflin-1), n);
                   3062: #else
                   3063:      /* return (*fun)(tflin, n);*/
                   3064:       return (*fun)(tflin);
                   3065: #endif
                   3066: }
                   3067: 
                   3068: void minny(int j, int nits, double *d2, double *x1, double f1, int fk)
                   3069: /* double *d2, *x1, f1; */
                   3070: {
                   3071: /* here j is from 0 to n-1 and can be -1 for parabolic search  */
                   3072:   /*      MINIMIZES F FROM X IN THE DIRECTION V(*,J) */
                   3073:           /*      UNLESS J<1, WHEN A QUADRATIC SEARCH IS DONE */
                   3074:           /*      IN THE PLANE DEFINED BY Q0, Q1 AND X. */
                   3075:           /*      D2 AN APPROXIMATION TO HALF F'' (OR ZERO), */
                   3076:           /*      X1 AN ESTIMATE OF DISTANCE TO MINIMUM, */
                   3077:           /*      RETURNED AS THE DISTANCE FOUND. */
                   3078:           /*       IF FK = TRUE THEN F1 IS FLIN(X1), OTHERWISE */
                   3079:           /*       X1 AND F1 ARE IGNORED ON ENTRY UNLESS FINAL */
                   3080:           /*       FX > F1. NITS CONTROLS THE NUMBER OF TIMES */
                   3081:           /*       AN ATTEMPT IS MADE TO HALVE THE INTERVAL. */
                   3082:           /* SIDE EFFECTS: USES AND ALTERS X, FX, NF, NL. */
                   3083:           /*       IF J < 1 USES VARIABLES Q... . */
                   3084:          /*       USES H, N, T, M2, M4, LDT, DMIN, MACHEPS; */
                   3085:    int k, i, dz;
                   3086:    double x2, xm, f0, f2, fm, d1, t2, sf1, sx1;
                   3087:    double s;
                   3088:    double macheps;
                   3089:    macheps=pow(16.0,-13.0);
                   3090:    sf1 = f1; sx1 = *x1;
                   3091:    k = 0; xm = 0.0; fm = f0 = fx; dz = *d2 < macheps;
                   3092:    /* h=1.0;*/ /* To be revised */
                   3093: #ifdef DEBUGPRAX
                   3094:    /* printf("min macheps=%14g h=%14g step=%14g t=%14g fx=%14g\n",macheps,h, step,t, fx);  */
                   3095:    /* Where is fx coming from */
                   3096:    printf("   min macheps=%14g h=%14g  t=%14g fx=%.9lf dirj=%d\n",macheps, h, t, fx, j);
                   3097:    matprint("  min vectors:",v,n,n);
                   3098: #endif
                   3099:    /* find step size */
                   3100:    s = 0.;
                   3101:    /* for (i=0; i<n; i++) s += x[i]*x[i]; */
                   3102:    for (i=1; i<=n; i++) s += x[i]*x[i];
                   3103:    s = sqrt(s);
                   3104:    if (dz)
                   3105:       t2 = m4*sqrt(fabs(fx)/dmin + s*ldt) + m2*ldt;
                   3106:    else
                   3107:       t2 = m4*sqrt(fabs(fx)/(*d2) + s*ldt) + m2*ldt;
                   3108:    s = s*m4 + t;
                   3109:    if (dz && t2 > s) t2 = s;
                   3110:    if (t2 < small_windows) t2 = small_windows;
                   3111:    if (t2 > 0.01*h) t2 = 0.01 * h;
                   3112:    if (fk && f1 <= fm) {
                   3113:       xm = *x1;
                   3114:       fm = f1;
                   3115:    }
                   3116: #ifdef DEBUGPRAX
                   3117:    printf("   additional flin X1=%14.7f t2=%14.7f *f1=%14.7f fm=%14.7f fk=%d\n",*x1,t2,f1,fm,fk);
                   3118: #endif   
                   3119:    if (!fk || fabs(*x1) < t2) {
                   3120:      *x1 = (*x1 >= 0 ? t2 : -t2); 
                   3121:       /* *x1 = (*x1 > 0 ? t2 : -t2); */ /* kind of error */
                   3122: #ifdef DEBUGPRAX
                   3123:      printf("    additional flin X1=%16.10e dirj=%d fk=%d\n",*x1, j, fk);
                   3124: #endif
                   3125:       f1 = flin(*x1, j);
                   3126: #ifdef DEBUGPRAX
                   3127:     printf("    after flin f1=%18.12e dirj=%d fk=%d\n",f1, j,fk);
                   3128: #endif
                   3129:    }
                   3130:    if (f1 <= fm) {
                   3131:       xm = *x1;
                   3132:       fm = f1;
                   3133:    }
                   3134: L0: /*L0 loop or next */
                   3135: /*
                   3136:   Evaluate FLIN at another point and estimate the second derivative.
                   3137: */
                   3138:    if (dz) {
                   3139:       x2 = (f0 < f1 ? -(*x1) : 2*(*x1));
                   3140: #ifdef DEBUGPRAX
                   3141:       printf("     additional second flin x2=%14.8e x1=%14.8e f0=%14.8e f1=%18.12e dirj=%d\n",x2,*x1,f0,f1,j);
                   3142: #endif
                   3143:       f2 = flin(x2, j);
                   3144: #ifdef DEBUGPRAX
                   3145:       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);
                   3146: #endif
                   3147:       if (f2 <= fm) {
                   3148:          xm = x2;
                   3149:         fm = f2;
                   3150:       }
                   3151:       /* d2 is the curvature or double difference f1 doesn't seem to be accurately computed */
                   3152:       *d2 = (x2*(f1-f0) - (*x1)*(f2-f0))/((*x1)*x2*((*x1)-x2));
                   3153: #ifdef DEBUGPRAX
                   3154:       double d11,d12;
                   3155:       d11=(f1-f0)/(*x1);d12=(f2-f0)/x2;
                   3156:       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)));
                   3157:       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);
                   3158:       double ff1=7.783920622852e+04;
                   3159:       double f1mf0=9.0344736236e-05;
                   3160:       *d2 = (f1mf0)/ (*x1)/((*x1)-x2) - (f2-f0)/x2/((*x1)-x2);
                   3161:       /* *d2 = (ff1-f0)/ (*x1)/((*x1)-x2) - (f2-f0)/x2/((*x1)-x2); */
                   3162:       printf(" simpliff computing *d2=%16.10e f1mf0=%18.12e,f1=f0+f1mf0=%18.12e\n",*d2,f1mf0,f0+f1mf0);
                   3163:       *d2 = ((f1-f0)/ (*x1) - (f2-f0)/x2)/((*x1)-x2);
                   3164:       printf(" overlifi computing *d2=%16.10e\n",*d2);
                   3165: #endif
                   3166:       *d2 = ((f1-f0)/ (*x1) - (f2-f0)/x2)/((*x1)-x2);      
                   3167:    }
                   3168: #ifdef DEBUGPRAX
                   3169:       printf("    additional second flin xm=%14.8e fm=%14.8e *d2=%14.8e\n",xm, fm,*d2);
                   3170: #endif
                   3171:    /*
                   3172:      Estimate the first derivative at 0.
                   3173:    */
                   3174:    d1 = (f1-f0)/(*x1) - *x1**d2; dz = 1;
                   3175:    /*
                   3176:       Predict the minimum.
                   3177:     */
                   3178:    if (*d2 <= small_windows) {
                   3179:      x2 = (d1 < 0 ? h : -h);
                   3180:    }
                   3181:    else {
                   3182:       x2 = - 0.5*d1/(*d2);
                   3183:    }
                   3184: #ifdef DEBUGPRAX
                   3185:     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);
                   3186: #endif
                   3187:     if (fabs(x2) > h)
                   3188:       x2 = (x2 > 0 ? h : -h);
                   3189: L1:  /* L1 or try loop */
                   3190: #ifdef DEBUGPRAX
                   3191:     printf("   AT predicted minimum flin x2=%14.8e x1=%14.8e K=%14d NITS=%14d dirj=%d\n",x2,*x1,k,nits,j);
                   3192: #endif
                   3193:    f2 = flin(x2, j); /* x[i]+x2*v[i][j] */
                   3194: #ifdef DEBUGPRAX
                   3195:    printf("   after flin f0=%14.8e f1=%14.8e f2=%14.8e fm=%14.8e\n",f0,f1,f2, fm);
                   3196: #endif
                   3197:    if ((k < nits) && (f2 > f0)) {
                   3198: #ifdef DEBUGPRAX
                   3199:      printf("  NO SUCCESS SO TRY AGAIN;\n");
                   3200: #endif
                   3201:      k++;
                   3202:      if ((f0 < f1) && (*x1*x2 > 0.0))
                   3203:        goto L0; /* or next */
                   3204:      x2 *= 0.5;
                   3205:      goto L1;
                   3206:    }
                   3207:    nl++;
                   3208: #ifdef DEBUGPRAX
                   3209:    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);
                   3210: #endif
                   3211:    if (f2 > fm) x2 = xm; else fm = f2;
                   3212:    if (fabs(x2*(x2-*x1)) > small_windows) {
                   3213:       *d2 = (x2*(f1-f0) - *x1*(fm-f0))/(*x1*x2*(*x1-x2));
                   3214:    }
                   3215:    else {
                   3216:       if (k > 0) *d2 = 0;
                   3217:    }
                   3218: #ifdef DEBUGPRAX
                   3219:    printf(" bebe end of min x1=%14.8e fx=%14.8e d2=%14.8e\n",*x1, fx, *d2);
                   3220: #endif
                   3221:    if (*d2 <= small_windows) *d2 = small_windows;
                   3222:    *x1 = x2; fx = fm;
                   3223:    if (sf1 < fx) {
                   3224:       fx = sf1;
                   3225:       *x1 = sx1;
                   3226:    }
                   3227:   /*
                   3228:     Update X for linear search.
                   3229:   */
                   3230: #ifdef DEBUGPRAX
                   3231:    printf("  end of min x1=%14.8e fx=%14.8e d2=%14.8e\n",*x1, fx, *d2);
                   3232: #endif
                   3233:    
                   3234:    /* if (j != -1) */
                   3235:    /*    for (i=0; i<n; i++) */
                   3236:    /*        x[i] += (*x1)*v[i][j]; */
                   3237:    if (j > 0)
                   3238:       for (i=1; i<=n; i++)
                   3239:           x[i] += (*x1)*v[i][j];
                   3240: }
                   3241: 
                   3242: void quad()    /* look for a minimum along the curve q0, q1, q2        */
                   3243: {
                   3244:    int i;
                   3245:    double l, s;
                   3246: 
                   3247:    s = fx; fx = qf1; qf1 = s; qd1 = 0.0;
                   3248:    /* for (i=0; i<n; i++) { */
                   3249:    for (i=1; i<=n; i++) {
                   3250:        s = x[i]; l = q1[i]; x[i] = l; q1[i] = s;
                   3251:        qd1 = qd1 + (s-l)*(s-l);
                   3252:    }
                   3253:    s = 0.0; qd1 = sqrt(qd1); l = qd1;
                   3254: #ifdef DEBUGPRAX
                   3255:   printf("  QUAD after sqrt qd1=%14.8e \n",qd1);
                   3256: #endif
                   3257:  
                   3258:    if (qd0>0.0 && qd1>0.0 &&nl>=3*n*n) {
                   3259: #ifdef DEBUGPRAX
                   3260:      printf(" QUAD before min value=%14.8e \n",qf1);
                   3261: #endif
                   3262:       /* min(-1, 2, &s, &l, qf1, 1); */
                   3263:       minny(0, 2, &s, &l, qf1, 1);
                   3264:       qa = l*(l-qd1)/(qd0*(qd0+qd1));
                   3265:       qb = (l+qd0)*(qd1-l)/(qd0*qd1);
                   3266:       qc = l*(l+qd0)/(qd1*(qd0+qd1));
                   3267:    }
                   3268:    else {
                   3269:       fx = qf1; qa = qb = 0.0; qc = 1.0;
                   3270:    }
                   3271: #ifdef DEBUGPRAX
                   3272:   printf("after eventual min qd0=%14.8e qd1=%14.8e nl=%d\n",qd0, qd1,nl);
                   3273: #endif
                   3274:    qd0 = qd1;
                   3275:    /* for (i=0; i<n; i++) { */
                   3276:    for (i=1; i<=n; i++) {
                   3277:        s = q0[i]; q0[i] = x[i];
                   3278:        x[i] = qa*s + qb*x[i] + qc*q1[i];
                   3279:    }
                   3280: #ifdef DEBUGQUAD
                   3281:    vecprint ( " X after QUAD:" , x, n );
                   3282: #endif
                   3283: }
                   3284: 
                   3285: /* void minfit(int n, double eps, double tol, double ab[N][N], double q[]) */
                   3286: void minfit(int n, double eps, double tol, double **ab, double q[])
                   3287: /* int n; */
                   3288: /* double eps, tol, ab[N][N], q[N]; */
                   3289: {
                   3290:    int l, kt, l2, i, j, k;
                   3291:    double c, f, g, h, s, x, y, z;
                   3292:    /* double eps; */
                   3293: /* #ifndef MSDOS */
                   3294: /*    double e[N];             /\* plenty of stack on a vax *\/ */
                   3295: /* #endif */
                   3296:    /* double *e; */
                   3297:    /* e=vector(0,n-1); /\* should be freed somewhere but gotos *\/ */
                   3298:    
                   3299:    /* householder's reduction to bidiagonal form */
                   3300: 
                   3301:    if(n==1){
                   3302:      /* q[1-1]=ab[1-1][1-1]; */
                   3303:      /* ab[1-1][1-1]=1.0; */
                   3304:      q[1]=ab[1][1];
                   3305:      ab[1][1]=1.0;
                   3306:      return; /* added from hardt */
                   3307:    }
                   3308:    /* eps=macheps; */ /* added */
                   3309:    x = g = 0.0;
                   3310: #ifdef DEBUGPRAX
                   3311:    matprint (" HOUSE holder:", ab, n, n);
                   3312: #endif
                   3313: 
                   3314:    /* for (i=0; i<n; i++) {  /\* FOR I := 1 UNTIL N DO *\/ */
                   3315:    for (i=1; i<=n; i++) {  /* FOR I := 1 UNTIL N DO */
                   3316:      e[i] = g; s = 0.0; l = i+1;
                   3317:      /* for (j=i; j<n; j++)  /\* FOR J := I UNTIL N DO S := S*AB(J,I)**2; *\/ /\* not correct *\/ */
                   3318:      for (j=i; j<=n; j++)  /* FOR J := I UNTIL N DO S := S*AB(J,I)**2; */ /* not correct */
                   3319:        s += ab[j][i] * ab[j][i];
                   3320: #ifdef DEBUGPRAXFIN
                   3321:      printf("i=%d s=%d %.7g tol=%.7g",i,s,tol);
                   3322: #endif
                   3323:      if (s < tol) {
                   3324:        g = 0.0;
                   3325:      }
                   3326:      else {
                   3327:        /* f = ab[i][i]; */
                   3328:        f = ab[i][i];
                   3329:        if (f < 0.0) 
                   3330:         g = sqrt(s);
                   3331:        else
                   3332:         g = -sqrt(s);
                   3333:        /* h = f*g - s; ab[i][i] = f - g; */
                   3334:        h = f*g - s; ab[i][i] = f - g;
                   3335:        /* for (j=l; j<n; j++) { */ /* FOR J := L UNTIL N DO */ /* wrong */
                   3336:        for (j=l; j<=n; j++) {
                   3337:         f = 0.0;
                   3338:         /* for (k=i; k<n; k++) /\* FOR K := I UNTIL N DO *\/ /\* wrong *\/ */
                   3339:         for (k=i; k<=n; k++) /* FOR K := I UNTIL N DO */
                   3340:           /* f += ab[k][i] * ab[k][j]; */
                   3341:           f += ab[k][i] * ab[k][j];
                   3342:         f /= h;
                   3343:         for (k=i; k<=n; k++) /* FOR K := I UNTIL N DO */
                   3344:           /* for (k=i; k<n; k++)/\* FOR K := I UNTIL N DO *\/ /\* wrong *\/ */
                   3345:           ab[k][j] += f * ab[k][i];
                   3346:         /* ab[k][j] += f * ab[k][i]; */
                   3347: #ifdef DEBUGPRAX
                   3348:         printf("Holder J=%d F=%.7g",j,f);
                   3349: #endif
                   3350:        }
                   3351:      } /* end s */
                   3352:      /* q[i] = g; s = 0.0; */
                   3353:      q[i] = g; s = 0.0;
                   3354: #ifdef DEBUGPRAX
                   3355:      printf(" I Q=%d %.7g",i,q[i]);
                   3356: #endif   
                   3357:        
                   3358:      /* if (i < n) */
                   3359:      /* if (i <= n)  /\* I is always lower or equal to n wasn't in golub reinsch*\/ */
                   3360:      /* for (j=l; j<n; j++) */
                   3361:      for (j=l; j<=n; j++)
                   3362:        s += ab[i][j] * ab[i][j];
                   3363:      /* s += ab[i][j] * ab[i][j]; */
                   3364:      if (s < tol) {
                   3365:        g = 0.0;
                   3366:      }
                   3367:      else {
                   3368:        if(i<n)
                   3369:         /* f = ab[i][i+1]; */ /* Brent golub overflow */
                   3370:         f = ab[i][i+1];
                   3371:        if (f < 0.0)
                   3372:         g = sqrt(s);
                   3373:        else 
                   3374:         g = - sqrt(s);
                   3375:        h = f*g - s;
                   3376:        /* h = f*g - s; ab[i][i+1] = f - g; */ /* Overflow for i=n Error in Golub too but not Burkardt*/
                   3377:        /* for (j=l; j<n; j++) */
                   3378:        /*     e[j] = ab[i][j]/h; */
                   3379:        if(i<n){
                   3380:         ab[i][i+1] = f - g;
                   3381:         for (j=l; j<=n; j++)
                   3382:           e[j] = ab[i][j]/h;
                   3383:         /* for (j=l; j<n; j++) { */
                   3384:         for (j=l; j<=n; j++) {
                   3385:           s = 0.0;
                   3386:           /* for (k=l; k<n; k++) s += ab[j][k]*ab[i][k]; */
                   3387:           for (k=l; k<=n; k++) s += ab[j][k]*ab[i][k];
                   3388:           /* for (k=l; k<n; k++) ab[j][k] += s * e[k]; */
                   3389:           for (k=l; k<=n; k++) ab[j][k] += s * e[k];
                   3390:         } /* END J */
                   3391:        } /* END i <n */
                   3392:      } /* end s */
                   3393:        /* y = fabs(q[i]) + fabs(e[i]); */
                   3394:      y = fabs(q[i]) + fabs(e[i]);
                   3395:      if (y > x) x = y;
                   3396: #ifdef DEBUGPRAX
                   3397:      printf(" I Y=%d %.7g",i,y);
                   3398: #endif
                   3399: #ifdef DEBUGPRAX
                   3400:      printf(" i=%d e(i) %.7g",i,e[i]);
                   3401: #endif
                   3402:    } /* end i */
                   3403:    /*
                   3404:      Accumulation of right hand transformations */
                   3405:    /* for (i=n-1; i >= 0; i--) { */ /* FOR I := N STEP -1 UNTIL 1 DO */
                   3406:    /* We should avoid the overflow in Golub */
                   3407:    /* ab[n-1][n-1] = 1.0; */
                   3408:    /* g = e[n-1]; */
                   3409:    ab[n][n] = 1.0;
                   3410:    g = e[n];
                   3411:    l = n;
                   3412: 
                   3413:    /* for (i=n; i >= 1; i--) { */
                   3414:    for (i=n-1; i >= 1; i--) { /* n-1 loops, different from brent and golub*/
                   3415:      if (g != 0.0) {
                   3416:        /* h = ab[i-1][i]*g; */
                   3417:        h = ab[i][i+1]*g;
                   3418:        for (j=l; j<=n; j++) ab[j][i] = ab[i][j] / h;
                   3419:        for (j=l; j<=n; j++) {
                   3420:         /* h = ab[i][i+1]*g; */
                   3421:         /* for (j=l; j<n; j++) ab[j][i] = ab[i][j] / h; */
                   3422:         /* for (j=l; j<n; j++) { */
                   3423:         s = 0.0;
                   3424:         /* for (k=l; k<n; k++) s += ab[i][k] * ab[k][j]; */
                   3425:         /* for (k=l; k<n; k++) ab[k][j] += s * ab[k][i]; */
                   3426:         for (k=l; k<=n; k++) s += ab[i][k] * ab[k][j];
                   3427:         for (k=l; k<=n; k++) ab[k][j] += s * ab[k][i];
                   3428:        }/* END J */
                   3429:      }/* END G */
                   3430:      /* for (j=l; j<n; j++) */
                   3431:      /*     ab[i][j] = ab[j][i] = 0.0; */
                   3432:      /* ab[i][i] = 1.0; g = e[i]; l = i; */
                   3433:      for (j=l; j<=n; j++)
                   3434:        ab[i][j] = ab[j][i] = 0.0;
                   3435:      ab[i][i] = 1.0; g = e[i]; l = i;
                   3436:    }/* END I */
                   3437: #ifdef DEBUGPRAX
                   3438:    matprint (" HOUSE accumulation:",ab,n, n );
                   3439: #endif
                   3440: 
                   3441:    /* diagonalization to bidiagonal form */
                   3442:    eps *= x;
                   3443:    /* for (k=n-1; k>= 0; k--) { */
                   3444:    for (k=n; k>= 1; k--) {
                   3445:      kt = 0;
                   3446: TestFsplitting:
                   3447: #ifdef DEBUGPRAX
                   3448:      printf(" TestFsplitting: k=%d kt=%d\n",k,kt);
                   3449:      /* for(i=1;i<=n;i++)printf(" e(%d)=%.14f",i,e[i]);printf("\n"); */
                   3450: #endif     
                   3451:      kt = kt+1; 
                   3452: /* TestFsplitting: */
                   3453:      /* if (++kt > 30) { */
                   3454:      if (kt > 30) { 
                   3455:        e[k] = 0.0;
                   3456:        fprintf(stderr, "\n+++ MINFIT - Fatal error\n");
                   3457:        fprintf ( stderr, "  The QR algorithm failed to converge.\n" );
                   3458:      }
                   3459:      /* for (l2=k; l2>=0; l2--) { */
                   3460:      for (l2=k; l2>=1; l2--) {
                   3461:        l = l2;
                   3462: #ifdef DEBUGPRAX
                   3463:        printf(" l e(l)< eps %d %.7g %.7g ",l,e[l], eps);
                   3464: #endif
                   3465:        /* if (fabs(e[l]) <= eps) */
                   3466:        if (fabs(e[l]) <= eps)
                   3467:         goto TestFconvergence;
                   3468:        /* if (fabs(q[l-1]) <= eps)*/ /* missing if ( 1 < l ){ *//* printf(" q(l-1)< eps %d %.7g %.7g ",l-1,q[l-2], eps); */
                   3469:        if (fabs(q[l-1]) <= eps)
                   3470:         break; /* goto Cancellation; */
                   3471:      }
                   3472:    Cancellation:
                   3473: #ifdef DEBUGPRAX
                   3474:      printf(" Cancellation:\n");
                   3475: #endif     
                   3476:      c = 0.0; s = 1.0;
                   3477:      for (i=l; i<=k; i++) {
                   3478:        f = s * e[i]; e[i] *= c;
                   3479:        /* f = s * e[i]; e[i] *= c; */
                   3480:        if (fabs(f) <= eps)
                   3481:         goto TestFconvergence;
                   3482:        /* g = q[i]; */
                   3483:        g = q[i];
                   3484:        if (fabs(f) < fabs(g)) {
                   3485:         double fg = f/g;
                   3486:         h = fabs(g)*sqrt(1.0+fg*fg);
                   3487:        }
                   3488:        else {
                   3489:         double gf = g/f;
                   3490:         h = (f!=0.0 ? fabs(f)*sqrt(1.0+gf*gf) : 0.0);
                   3491:        }
                   3492:        /*    COMMENT: THE ABOVE REPLACES Q(I):=H:=LONGSQRT(G*G+F*F) */
                   3493:        /* WHICH MAY GIVE INCORRECT RESULTS IF THE */
                   3494:        /* SQUARES UNDERFLOW OR IF F = G = 0; */
                   3495:        
                   3496:        /* q[i] = h; */
                   3497:        q[i] = h;
                   3498:        if (h == 0.0) { h = 1.0; g = 1.0; }
                   3499:        c = g/h; s = -f/h;
                   3500:      }
                   3501: TestFconvergence:
                   3502:  #ifdef DEBUGPRAX
                   3503:      printf(" TestFconvergence: l=%d k=%d\n",l,k);
                   3504: #endif     
                   3505:      /* z = q[k]; */
                   3506:      z = q[k];
                   3507:      if (l == k)
                   3508:        goto Convergence;
                   3509:      /* shift from bottom 2x2 minor */
                   3510:      /* x = q[l]; y = q[k-l]; g = e[k-1]; h = e[k]; */ /* Error */
                   3511:      x = q[l]; y = q[k-1]; g = e[k-1]; h = e[k];
                   3512:      f = ((y-z)*(y+z) + (g-h)*(g+h)) / (2.0*h*y);
                   3513:      g = sqrt(f*f+1.0);
                   3514:      if (f <= 0.0)
                   3515:        f = ((x-z)*(x+z) + h*(y/(f-g)-h))/x;
                   3516:      else
                   3517:        f = ((x-z)*(x+z) + h*(y/(f+g)-h))/x;
                   3518:      /* next qr transformation */
                   3519:      s = c = 1.0;
                   3520:      for (i=l+1; i<=k; i++) {
                   3521: #ifdef DEBUGPRAXQR
                   3522:        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]);
                   3523: #endif     
                   3524:        /* g = e[i]; y = q[i]; h = s*g; g *= c; */
                   3525:        g = e[i]; y = q[i]; h = s*g; g *= c;
                   3526:        if (fabs(f) < fabs(h)) {
                   3527:         double fh = f/h;
                   3528:         z = fabs(h) * sqrt(1.0 + fh*fh);
                   3529:        }
                   3530:        else {
                   3531:         double hf = h/f;
                   3532:         z = (f!=0.0 ? fabs(f)*sqrt(1.0+hf*hf) : 0.0);
                   3533:        }
                   3534:        /* e[i-1] = z; */
                   3535:        e[i-1] = z;
                   3536: #ifdef DEBUGPRAXQR
                   3537:        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]);
                   3538: #endif     
                   3539:        if (z == 0.0) 
                   3540:         f = z = 1.0;
                   3541:        c = f/z; s = h/z;
                   3542:        f = x*c + g*s; g = - x*s + g*c; h = y*s;
                   3543:        y *= c;
                   3544:        /* for (j=0; j<n; j++) { */
                   3545:        /*     x = ab[j][i-1]; z = ab[j][i]; */
                   3546:        /*     ab[j][i-1] = x*c + z*s; */
                   3547:        /*     ab[j][i] = - x*s + z*c; */
                   3548:        /* } */
                   3549:        for (j=1; j<=n; j++) {
                   3550:         x = ab[j][i-1]; z = ab[j][i];
                   3551:         ab[j][i-1] = x*c + z*s;
                   3552:         ab[j][i] = - x*s + z*c;
                   3553:        }
                   3554:        if (fabs(f) < fabs(h)) {
                   3555:         double fh = f/h;
                   3556:         z = fabs(h) * sqrt(1.0 + fh*fh);
                   3557:        }
                   3558:        else {
                   3559:         double hf = h/f;
                   3560:         z = (f!=0.0 ? fabs(f)*sqrt(1.0+hf*hf) : 0.0);
                   3561:        }
                   3562: #ifdef DEBUGPRAXQR
                   3563:        printf(" qr transformation z f h=%.7g %.7g %.7g i=%d k=%d\n",z,f,h, i, k);
                   3564: #endif
                   3565:        q[i-1] = z;
                   3566:        if (z == 0.0)
                   3567:         z = f = 1.0;
                   3568:        c = f/z; s = h/z;
                   3569:        f = c*g + s*y;  /* f can be very small */
                   3570:        x = - s*g + c*y;
                   3571:      }
                   3572:      /* e[l] = 0.0; e[k] = f; q[k] = x; */
                   3573:      e[l] = 0.0; e[k] = f; q[k] = x;
                   3574: #ifdef DEBUGPRAXQR
                   3575:      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);
                   3576: #endif
                   3577:      goto TestFsplitting;
                   3578:    Convergence:
                   3579: #ifdef DEBUGPRAX
                   3580:      printf(" Convergence:\n");
                   3581: #endif     
                   3582:      if (z < 0.0) {
                   3583:        /* q[k] = - z; */
                   3584:        /* for (j=0; j<n; j++) ab[j][k] = - ab[j][k]; */
                   3585:        q[k] = - z;
                   3586:        for (j=1; j<=n; j++) ab[j][k] = - ab[j][k];
                   3587:      }/* END Z */
                   3588:    }/* END K */
                   3589: } /* END MINFIT */
                   3590: 
                   3591: 
                   3592: double praxis(double tol, double macheps, double h0, int _n, int _prin, double *_x, double (*_fun)(double *_x))
                   3593: /* double praxis(double tol, double macheps, double h0, int _n, int _prin, double *_x, double (*_fun)(double *_x, int _n)) */
                   3594: /* double praxis(double (*_fun)(), double _x[], int _n) */
                   3595: /* double (*_fun)(); */
                   3596: /* double _x[N]; */
                   3597: /* double (*_fun)(); */
                   3598: /* double _x[N]; */
                   3599: {
                   3600:    /* init global extern variables and parameters */
                   3601:    /* double *d, *y, *z, */
                   3602:    /*   *q0, *q1, **v; */
                   3603:    /* double *tflin; /\* used in flin: return (*fun)(tflin, n); *\/ */
                   3604:    /* double *e; /\* used in minfit, don't konw how to free memory and thus made global *\/ */
                   3605: 
                   3606:   
                   3607:   int seed; /* added */
                   3608:   int biter=0;
                   3609:   double r;
                   3610:   double randbrent( int (*));
                   3611:   double s, sf;
                   3612:   
                   3613:    h = h0; /* step; */
                   3614:    t = tol;
                   3615:    scbd = 1.0;
                   3616:    illc = 0;
                   3617:    ktm = 1;
                   3618: 
                   3619:    macheps = DBL_EPSILON;
                   3620:    /* prin=4; */
                   3621: #ifdef DEBUGPRAX
                   3622:    printf("Praxis macheps=%14g h=%14g step=%14g tol=%14g\n",macheps,h, h0,tol); 
                   3623: #endif
                   3624:    n = _n;
                   3625:    x = _x;
                   3626:    prin = _prin;
                   3627:    fun = _fun;
                   3628:    d=vector(1, n);
                   3629:    y=vector(1, n);
                   3630:    z=vector(1, n);
                   3631:    q0=vector(1, n);
                   3632:    q1=vector(1, n);
                   3633:    e=vector(1, n);
                   3634:    tflin=vector(1, n);
                   3635:    v=matrix(1, n, 1, n);
                   3636:    for(i=1;i<=n;i++){d[i]=y[i]=z[i]=q0[0]=e[i]=tflin[i]=0.;}
                   3637:    small_windows = (macheps) * (macheps); vsmall = small_windows*small_windows;
                   3638:    large = 1.0/small_windows; vlarge = 1.0/vsmall;
                   3639:    m2 = sqrt(macheps); m4 = sqrt(m2);
                   3640:    seed = 123456789; /* added */
                   3641:    ldfac = (illc ? 0.1 : 0.01);
                   3642:    for(i=1;i<=n;i++) z[i]=0.; /* Was missing in Gegenfurtner as well as Brent's algol or fortran  */
                   3643:    nl = kt = 0; nf = 1;
                   3644: #ifdef NR_SHIFT
                   3645:    fx = (*fun)((x-1), n);
                   3646: #else
                   3647:    fx = (*fun)(x);
                   3648: #endif
                   3649:    qf1 = fx;
                   3650:    t2 = small_windows + fabs(t); t = t2; dmin = small_windows;
                   3651: #ifdef DEBUGPRAX
                   3652:    printf("praxis2 macheps=%14g h=%14g step=%14g small=%14g t=%14g\n",macheps,h, h0,small_windows, t); 
                   3653: #endif
                   3654:    if (h < 100.0*t) h = 100.0*t;
                   3655: #ifdef DEBUGPRAX
                   3656:    printf("praxis3 macheps=%14g h=%14g step=%14g small=%14g t=%14g\n",macheps,h, h0,small_windows, t); 
                   3657: #endif
                   3658:    ldt = h;
                   3659:    /* for (i=0; i<n; i++) for (j=0; j<n; j++) */
                   3660:    for (i=1; i<=n; i++) for (j=1; j<=n; j++)
                   3661:        v[i][j] = (i == j ? 1.0 : 0.0);
                   3662:    d[1] = 0.0; qd0 = 0.0;
                   3663:    /* for (i=0; i<n; i++) q1[i] = x[i]; */
                   3664:    for (i=1; i<=n; i++) q1[i] = x[i];
                   3665:    if (prin > 1) {
                   3666:       printf("\n------------- enter function praxis -----------\n");
                   3667:       printf("... current parameter settings ...\n");
                   3668:       printf("... scaling ... %20.10e\n", scbd);
                   3669:       printf("...   tol   ... %20.10e\n", t);
                   3670:       printf("... maxstep ... %20.10e\n", h);
                   3671:       printf("...   illc  ... %20u\n", illc);
                   3672:       printf("...   ktm   ... %20u\n", ktm);
                   3673:       printf("... maxfun  ... %20u\n", maxfun);
                   3674:    }
                   3675:    if (prin) print2();
                   3676: 
                   3677: mloop:
                   3678:     biter++;  /* Added to count the loops */
                   3679:    /* sf = d[0]; */
                   3680:    /* s = d[0] = 0.0; */
                   3681:     printf("\n Big iteration %d \n",biter);
                   3682:     fprintf(ficlog,"\n Big iteration %d \n",biter);
                   3683:     sf = d[1];
                   3684:    s = d[1] = 0.0;
                   3685: 
                   3686:    /* minimize along first direction V(*,1) */
                   3687: #ifdef DEBUGPRAX
                   3688:    printf("  Minimize along the first direction V(*,1). illc=%d\n",illc);
                   3689:    /* fprintf(ficlog,"  Minimize along the first direction V(*,1).\n"); */
                   3690: #endif
                   3691: #ifdef DEBUGPRAX2
                   3692:    printf("praxis4 macheps=%14g h=%14g step=%14g small=%14g t=%14g\n",macheps,h, h0,small_windows, t); 
                   3693: #endif
                   3694:    /* min(0, 2, &d[0], &s, fx, 0); /\* mac heps not global *\/ */
                   3695:    minny(1, 2, &d[1], &s, fx, 0); /* mac heps not global */
                   3696: #ifdef DEBUGPRAX
                   3697:    printf("praxis5 macheps=%14g h=%14g looks at sign of s=%14g fx=%14g\n",macheps,h, s,fx); 
                   3698: #endif
                   3699:    if (s <= 0.0)
                   3700:       /* for (i=0; i < n; i++) */
                   3701:       for (i=1; i <= n; i++)
                   3702:           v[i][1] = -v[i][1];
                   3703:    /* if ((sf <= (0.9 * d[0])) || ((0.9 * sf) >= d[0])) */
                   3704:    if ((sf <= (0.9 * d[1])) || ((0.9 * sf) >= d[1]))
                   3705:       /* for (i=1; i<n; i++) */
                   3706:       for (i=2; i<=n; i++)
                   3707:           d[i] = 0.0;
                   3708:    /* for (k=1; k<n; k++) { */
                   3709:    for (k=2; k<=n; k++) {
                   3710:     /*
                   3711:       The inner loop starts here.
                   3712:     */
                   3713: #ifdef DEBUGPRAX
                   3714:       printf("      The inner loop  here from k=%d to n=%d.\n",k,n);
                   3715:       /* fprintf(ficlog,"      The inner loop  here from k=%d to n=%d.\n",k,n); */
                   3716: #endif
                   3717:        /* for (i=0; i<n; i++) */
                   3718:        for (i=1; i<=n; i++)
                   3719:            y[i] = x[i];
                   3720:        sf = fx;
                   3721: #ifdef DEBUGPRAX
                   3722:        printf(" illc=%d and kt=%d and ktm=%d\n", illc, kt, ktm);
                   3723: #endif
                   3724:        illc = illc || (kt > 0);
                   3725: next:
                   3726:        kl = k;
                   3727:        df = 0.0;
                   3728:        if (illc) {        /* random step to get off resolution valley */
                   3729: #ifdef DEBUGPRAX
                   3730:          printf("  A random step follows, to avoid resolution valleys.\n");
                   3731:          matprint("  before rand, vectors:",v,n,n);
                   3732: #endif
                   3733:           for (i=1; i<=n; i++) {
                   3734: #ifdef NOBRENTRAND
                   3735:            r = drandom();
                   3736: #else
                   3737:            seed=i;
                   3738:            /* seed=i+1; */
                   3739: #ifdef DEBUGRAND
                   3740:            printf(" Random seed=%d, brent i=%d",seed,i); /* YYYY i=5 j=1 vji= -0.0001170073 */
                   3741: #endif
                   3742:            r = randbrent ( &seed );
                   3743: #endif
                   3744: #ifdef DEBUGRAND
                   3745:            printf(" Random r=%.7g \n",r);
                   3746: #endif     
                   3747:             z[i] = (0.1 * ldt + t2 * pow(10.0,(double)kt)) * (r - 0.5);
                   3748:            /* z[i] = (0.1 * ldt + t2 * pow(10.0,(double)kt)) * (drandom() - 0.5); */
                   3749: 
                   3750:            s = z[i];
                   3751:               for (j=1; j <= n; j++)
                   3752:                   x[j] += s * v[j][i];
                   3753:          }
                   3754: #ifdef DEBUGRAND
                   3755:          matprint("  after rand, vectors:",v,n,n);
                   3756: #endif
                   3757: #ifdef NR_SHIFT
                   3758:           fx = (*fun)((x-1), n);
                   3759: #else
                   3760:           fx = (*fun)(x, n);
                   3761: #endif
                   3762:           /* fx = (*func) ( (x-1) ); *//* This for func which is computed from x[1] and not from x[0] xm1=(x-1)*/
                   3763:           nf++;
                   3764:        }
                   3765:        /* minimize along non-conjugate directions */
                   3766: #ifdef DEBUGPRAX
                   3767:        printf(" Minimize along the 'non-conjugate' directions (dots printed) V(*,%d),...,V(*,%d).\n",k,n);
                   3768:        /* fprintf(ficlog," Minimize along the 'non-conjugate' directions  (dots printed) V(*,%d),...,V(*,%d).\n",k,n); */
                   3769: #endif
                   3770:        /* for (k2=k; k2<n; k2++) {  /\* Be careful here k2 <=n ? *\/ */
                   3771:        for (k2=k; k2<=n; k2++) {  /* Be careful here k2 <=n ? */
                   3772:            sl = fx;
                   3773:            s = 0.0;
                   3774: #ifdef DEBUGPRAX
                   3775:           printf(" Minimize along the 'NON-CONJUGATE' true direction k2=%14d fx=%14.7f\n",k2, fx);
                   3776:    matprint("  before min vectors:",v,n,n);
                   3777: #endif
                   3778:            /* min(k2, 2, &d[k2], &s, fx, 0); */
                   3779:    /*    jsearch=k2-1; */
                   3780:    /* min(jsearch, 2, &d[jsearch], &s, fx, 0); */
                   3781:    minny(k2, 2, &d[k2], &s, fx, 0);
                   3782: #ifdef DEBUGPRAX
                   3783:           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);
                   3784: #endif
                   3785:           if (illc) {
                   3786:              /* double szk = s + z[k2]; */
                   3787:               /* s = d[k2] * szk*szk; */
                   3788:              double szk = s + z[k2];
                   3789:               s = d[k2] * szk*szk;
                   3790:           }
                   3791:            else 
                   3792:              s = sl - fx;
                   3793:            /* if (df < s) { */
                   3794:            if (df <= s) {
                   3795:               df = s;
                   3796:               kl = k2;
                   3797: #ifdef DEBUGPRAX
                   3798:            printf(" df=%.7g and choose kl=%d \n",df,kl); /* UUUU */
                   3799: #endif
                   3800:            }
                   3801:        } /* end loop k2 */
                   3802:         /*
                   3803:          If there was not much improvement on the first try, set
                   3804:          ILLC = true and start the inner loop again.
                   3805:        */
                   3806: #ifdef DEBUGPRAX
                   3807:        printf(" If there was not much improvement on the first try, set ILLC = true and start the inner loop again. illc=%d\n",illc);
                   3808:        /* fprintf(ficlog,"  If there was not much improvement on the first try, set ILLC = true and start the inner loop again.\n"); */
                   3809: #endif
                   3810:         if (!illc && (df < fabs(100.0 * (macheps) * fx))) {
                   3811: #ifdef DEBUGPRAX
                   3812:          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);         
                   3813: #endif
                   3814:           illc = 1;
                   3815:           goto next;
                   3816:        }
                   3817: #ifdef DEBUGPRAX
                   3818:        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);
                   3819: #endif
                   3820:        
                   3821:        /* if ((k == 1) && (prin > 1)){ /\* be careful k=2 *\/ */
                   3822:        if ((k == 2) && (prin > 1)){ /* be careful k=2 */
                   3823: #ifdef DEBUGPRAX
                   3824:         printf("  NEW D The second difference array d:\n" );
                   3825:         /* fprintf(ficlog, " NEW D The second difference array d:\n" ); */
                   3826: #endif
                   3827:         vecprint(" NEW D The second difference array d:",d,n);
                   3828:        }
                   3829:        /* minimize along conjugate directions */ 
                   3830:        /*
                   3831:         Minimize along the "conjugate" directions V(*,1),...,V(*,K-1).
                   3832:        */
                   3833: #ifdef DEBUGPRAX
                   3834:       printf("Minimize along the 'conjugate' directions V(*,1),...,V(*,K-1=%d).\n",k-1);
                   3835:       /* fprintf(ficlog,"Minimize along the 'conjugate' directions V(*,1),...,V(*,K-1=%d).\n",k-1); */
                   3836: #endif
                   3837:       /* for (k2=0; k2<=k-1; k2++) { */
                   3838:       for (k2=1; k2<=k-1; k2++) {
                   3839:            s = 0.0;
                   3840:            /* min(k2-1, 2, &d[k2-1], &s, fx, 0); */
                   3841:            minny(k2, 2, &d[k2], &s, fx, 0);
                   3842:        }
                   3843:        f1 = fx;
                   3844:        fx = sf;
                   3845:        lds = 0.0;
                   3846:        /* for (i=0; i<n; i++) { */
                   3847:        for (i=1; i<=n; i++) {
                   3848:            sl = x[i];
                   3849:            x[i] = y[i];
                   3850:            y[i] = sl - y[i];
                   3851:            sl = y[i];
                   3852:            lds = lds + sl*sl;
                   3853:        }
                   3854:        lds = sqrt(lds);
                   3855: #ifdef DEBUGPRAX
                   3856:        printf("Minimization done 'conjugate', shifted all points, computed lds=%.8f\n",lds);
                   3857: #endif      
                   3858:       /*
                   3859:        Discard direction V(*,kl).
                   3860:        
                   3861:        If no random step was taken, V(*,KL) is the "non-conjugate"
                   3862:        direction along which the greatest improvement was made.
                   3863:       */
                   3864:        if (lds > small_windows) {
                   3865: #ifdef DEBUGPRAX
                   3866:        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);
                   3867:         matprint("  before shift new conjugate vectors:",v,n,n);
                   3868: #endif
                   3869:         for (i=kl-1; i>=k; i--) {
                   3870:           /* for (j=0; j < n; j++) */
                   3871:           for (j=1; j <= n; j++)
                   3872:             /* v[j][i+1] = v[j][i]; */ /* This is v[j][i+1]=v[j][i] i=kl-1 to k */
                   3873:             v[j][i+1] = v[j][i]; /* This is v[j][i+1]=v[j][i] i=kl-1 to k */
                   3874:           /* v[j][i+1] = v[j][i]; */
                   3875:           /* d[i+1] = d[i];*/  /* last  is d[k+1]= d[k] */
                   3876:           d[i+1] = d[i];  /* last  is d[k]= d[k-1] */
                   3877:         }
                   3878: #ifdef DEBUGPRAX
                   3879:         matprint("  after shift new conjugate vectors:",v,n,n);         
                   3880: #endif  /* d[k] = 0.0; */
                   3881:         d[k] = 0.0;
                   3882:         for (i=1; i <= n; i++)
                   3883:           v[i][k] = y[i] / lds;
                   3884:         /* v[i][k] = y[i] / lds; */
                   3885: #ifdef DEBUGPRAX
                   3886:         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);
                   3887:         /* fprintf(ficlog,"Minimize along the new 'conjugate' direction V(*,k=%d), which is the normalized vector:  (new x) - (old x).\n",k); */
                   3888:     matprint("  before min new conjugate vectors:",v,n,n);      
                   3889: #endif
                   3890:         /* min(k-1, 4, &d[k-1], &lds, f1, 1); */
                   3891:         minny(k, 4, &d[k], &lds, f1, 1);
                   3892: #ifdef DEBUGPRAX
                   3893:         printf(" after min d(k)=%d %.7g lds=%14f\n",k,d[k],lds);
                   3894:    matprint("  after min vectors:",v,n,n);
                   3895: #endif
                   3896:         if (lds <= 0.0) {
                   3897:           lds = -lds;
                   3898: #ifdef DEBUGPRAX
                   3899:          printf(" lds changed sign lds=%.14f k=%d\n",lds,k);
                   3900: #endif    
                   3901:           /* for (i=0; i<n; i++) */
                   3902:           /*   v[i][k] = -v[i][k]; */
                   3903:           for (i=1; i<=n; i++)
                   3904:             v[i][k] = -v[i][k];
                   3905:         }
                   3906:        }
                   3907:        ldt = ldfac * ldt;
                   3908:        if (ldt < lds)
                   3909:           ldt = lds;
                   3910:        if (prin > 0){
                   3911: #ifdef DEBUGPRAX
                   3912:        printf(" k=%d",k);
                   3913:        /* fprintf(ficlog," k=%d",k); */
                   3914: #endif
                   3915:        print2();/* n, x, prin, fx, nf, nl ); */
                   3916:        }
                   3917:        t2 = 0.0;
                   3918:        /* for (i=0; i<n; i++) */
                   3919:        for (i=1; i<=n; i++)
                   3920:            t2 += x[i]*x[i];
                   3921:        t2 = m2 * sqrt(t2) + t;
                   3922:        /*
                   3923:        See whether the length of the step taken since starting the
                   3924:        inner loop exceeds half the tolerance.
                   3925:       */
                   3926: #ifdef DEBUGPRAX
                   3927:        printf("See if step length exceeds half the tolerance.\n"); /* ZZZZZ */
                   3928:       /* fprintf(ficlog,"See if step length exceeds half the tolerance.\n"); */
                   3929: #endif
                   3930:        if (ldt > (0.5 * t2))
                   3931:           kt = 0;
                   3932:        else 
                   3933:          kt++;
                   3934: #ifdef DEBUGPRAX
                   3935:        printf("if kt=%d >? ktm=%d gotoL2 loop\n",kt,ktm);
                   3936: #endif
                   3937:        if (kt > ktm){
                   3938:          if ( 0 < prin ){
                   3939:           /* printf("\nr8vec_print\n X:\n"); */
                   3940:           /* fprintf(ficlog,"\nr8vec_print\n X:\n"); */
                   3941:           vecprint ("END  X:", x, n );
                   3942:         }
                   3943:            goto fret;
                   3944:        }
                   3945: #ifdef DEBUGPRAX
                   3946:    matprint("  end of L2 loop vectors:",v,n,n);
                   3947: #endif
                   3948:        
                   3949:    }
                   3950:    /* printf("The inner loop ends here.\n"); */
                   3951:    /* fprintf(ficlog,"The inner loop ends here.\n"); */
                   3952:    /*
                   3953:      The inner loop ends here.
                   3954:      
                   3955:      Try quadratic extrapolation in case we are in a curved valley.
                   3956:    */
                   3957: #ifdef DEBUGPRAX
                   3958:    printf("Try QUAD ratic extrapolation in case we are in a curved valley.\n");
                   3959: #endif
                   3960:    /*  try quadratic extrapolation in case    */
                   3961:    /*  we are stuck in a curved valley        */
                   3962:    quad();
                   3963:    dn = 0.0;
                   3964:    /* for (i=0; i<n; i++) { */
                   3965:    for (i=1; i<=n; i++) {
                   3966:        d[i] = 1.0 / sqrt(d[i]);
                   3967:        if (dn < d[i])
                   3968:           dn = d[i];
                   3969:    }
                   3970:    if (prin > 2)
                   3971:      matprint("  NEW DIRECTIONS vectors:",v,n,n);
                   3972:    /* for (j=0; j<n; j++) { */
                   3973:    for (j=1; j<=n; j++) {
                   3974:        s = d[j] / dn;
                   3975:        /* for (i=0; i < n; i++) */
                   3976:        for (i=1; i <= n; i++)
                   3977:            v[i][j] *= s;
                   3978:    }
                   3979:    
                   3980:    if (scbd > 1.0) {       /* scale axis to reduce condition number */
                   3981: #ifdef DEBUGPRAX
                   3982:      printf("Scale the axes to try to reduce the condition number.\n");
                   3983: #endif
                   3984:      /* fprintf(ficlog,"Scale the axes to try to reduce the condition number.\n"); */
                   3985:       s = vlarge;
                   3986:       /* for (i=0; i<n; i++) { */
                   3987:       for (i=1; i<=n; i++) {
                   3988:           sl = 0.0;
                   3989:           /* for (j=0; j < n; j++) */
                   3990:           for (j=1; j <= n; j++)
                   3991:               sl += v[i][j]*v[i][j];
                   3992:           z[i] = sqrt(sl);
                   3993:           if (z[i] < m4)
                   3994:              z[i] = m4;
                   3995:           if (s > z[i])
                   3996:              s = z[i];
                   3997:       }
                   3998:       /* for (i=0; i<n; i++) { */
                   3999:       for (i=1; i<=n; i++) {
                   4000:           sl = s / z[i];
                   4001:           z[i] = 1.0 / sl;
                   4002:           if (z[i] > scbd) {
                   4003:              sl = 1.0 / scbd;
                   4004:              z[i] = scbd;
                   4005:           }
                   4006:       }
                   4007:    }
                   4008:    for (i=1; i<=n; i++)
                   4009:        /* for (j=0; j<=i-1; j++) { */
                   4010:        /* for (j=1; j<=i; j++) { */
                   4011:        for (j=1; j<=i-1; j++) {
                   4012:            s = v[i][j];
                   4013:            v[i][j] = v[j][i];
                   4014:            v[j][i] = s;
                   4015:        }
                   4016: #ifdef DEBUGPRAX
                   4017:     printf(" Calculate a new set of orthogonal directions before repeating  the main loop.\n  Transpose V for MINFIT:...\n");
                   4018: #endif
                   4019:       /*
                   4020:       MINFIT finds the singular value decomposition of V.
                   4021: 
                   4022:       This gives the principal values and principal directions of the
                   4023:       approximating quadratic form without squaring the condition number.
                   4024:     */
                   4025:  #ifdef DEBUGPRAX
                   4026:     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");
                   4027: #endif
                   4028: 
                   4029:    minfit(n, macheps, vsmall, v, d);
                   4030:     /* for(i=0; i<n;i++)printf(" %14.7g",d[i]); */
                   4031:     /* v is overwritten with R. */
                   4032:     /*
                   4033:       Unscale the axes.
                   4034:     */
                   4035:    if (scbd > 1.0) {
                   4036: #ifdef DEBUGPRAX
                   4037:       printf(" Unscale the axes.\n");
                   4038: #endif
                   4039:       /* for (i=0; i<n; i++) { */
                   4040:       for (i=1; i<=n; i++) {
                   4041:           s = z[i];
                   4042:           /* for (j=0; j<n; j++) */
                   4043:           for (j=1; j<=n; j++)
                   4044:               v[i][j] *= s;
                   4045:       }
                   4046:       /* for (i=0; i<n; i++) { */
                   4047:       for (i=1; i<=n; i++) {
                   4048:           s = 0.0;
                   4049:           /* for (j=0; j<n; j++) */
                   4050:           for (j=1; j<=n; j++)
                   4051:               s += v[j][i]*v[j][i];
                   4052:           s = sqrt(s);
                   4053:           d[i] *= s;
                   4054:           s = 1.0 / s;
                   4055:           /* for (j=0; j<n; j++) */
                   4056:           for (j=1; j<=n; j++)
                   4057:               v[j][i] *= s;
                   4058:       }
                   4059:    }
                   4060:    /* for (i=0; i<n; i++) { */
                   4061:    double dni; /* added for compatibility with buckhardt but not brent */
                   4062:    for (i=1; i<=n; i++) {
                   4063:      dni=dn*d[i]; /* added for compatibility with buckhardt but not brent */
                   4064:        if ((dn * d[i]) > large)
                   4065:           d[i] = vsmall;
                   4066:        else if ((dn * d[i]) < small_windows)
                   4067:           d[i] = vlarge;
                   4068:        else 
                   4069:         d[i] = 1.0 / dni / dni; /* added for compatibility with buckhardt but not brent */
                   4070:           /* d[i] = pow(dn * d[i],-2.0); */
                   4071:    }
                   4072: #ifdef DEBUGPRAX
                   4073:    vecprint ("\n Before sort Eigenvalues of a:",d,n );
                   4074: #endif
                   4075:    
                   4076:    sort();               /* the new eigenvalues and eigenvectors */
                   4077: #ifdef DEBUGPRAX
                   4078:    vecprint( " After sort the eigenvalues ....\n", d, n);
                   4079:    matprint( " After sort the eigenvectors....\n", v, n,n);
                   4080: #endif
                   4081: #ifdef DEBUGPRAX
                   4082:     printf("  Determine the smallest eigenvalue.\n");
                   4083: #endif
                   4084:    /* dmin = d[n-1]; */
                   4085:    dmin = d[n];
                   4086:    if (dmin < small_windows)
                   4087:       dmin = small_windows;
                   4088:     /*
                   4089:      The ratio of the smallest to largest eigenvalue determines whether
                   4090:      the system is ill conditioned.
                   4091:    */
                   4092:   
                   4093:    /* illc = (m2 * d[0]) > dmin; */
                   4094:    illc = (m2 * d[1]) > dmin;
                   4095: #ifdef DEBUGPRAX
                   4096:     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]);
                   4097: #endif
                   4098:    
                   4099:    if ((prin > 2) && (scbd > 1.0))
                   4100:       vecprint("\n The scale factors:",z,n);
                   4101:    if (prin > 2)
                   4102:       vecprint("  Principal values (EIGEN VALUES OF A) of the quadratic form:",d,n);
                   4103:    if (prin > 2)
                   4104:      matprint("  The principal axes (EIGEN VECTORS OF A:",v,n, n);
                   4105: 
                   4106:    if ((maxfun > 0) && (nf > maxfun)) {
                   4107:       if (prin)
                   4108:         printf("\n... maximum number of function calls reached ...\n");
                   4109:       goto fret;
                   4110:    }
                   4111: #ifdef DEBUGPRAX
                   4112:    printf("Goto main loop\n");
                   4113: #endif
                   4114:    goto mloop;          /* back to main loop */
                   4115: 
                   4116: fret:
                   4117:    if (prin > 0) {
                   4118:          vecprint("\n  X:", x, n);
                   4119:          /* printf("\n... ChiSq reduced to %20.10e ...\n", fx); */
                   4120:         /* printf("... after %20u function calls.\n", nf); */
                   4121:    }
                   4122:    free_vector(d, 1, n);
                   4123:    free_vector(y, 1, n);
                   4124:    free_vector(z, 1, n);
                   4125:    free_vector(q0, 1, n);
                   4126:    free_vector(q1, 1, n);
                   4127:    free_matrix(v, 1, n, 1, n);
                   4128:    /*   double *d, *y, *z, */
                   4129:    /* *q0, *q1, **v; */
                   4130:    free_vector(tflin, 1, n);
                   4131:    /* double *tflin; /\* used in flin: return (*fun)(tflin, n); *\/ */
                   4132:    free_vector(e, 1, n);
                   4133:    /* double *e; /\* used in minfit, don't konw how to free memory and thus made global *\/ */
                   4134:    
                   4135:    return(fx);
                   4136: }
                   4137: 
                   4138: /* end praxis gegen */
1.126     brouard  4139: 
                   4140: /*************** powell ************************/
1.162     brouard  4141: /*
1.317     brouard  4142: Minimization of a function func of n variables. Input consists in an initial starting point
                   4143: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   4144: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   4145: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  4146: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   4147: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   4148:  */
1.224     brouard  4149: #ifdef LINMINORIGINAL
                   4150: #else
                   4151:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  4152:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  4153: #endif
1.126     brouard  4154: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   4155:            double (*func)(double [])) 
                   4156: { 
1.224     brouard  4157: #ifdef LINMINORIGINAL
                   4158:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  4159:              double (*func)(double [])); 
1.224     brouard  4160: #else 
1.241     brouard  4161:  void linmin(double p[], double xi[], int n, double *fret,
                   4162:             double (*func)(double []),int *flat); 
1.224     brouard  4163: #endif
1.239     brouard  4164:  int i,ibig,j,jk,k; 
1.126     brouard  4165:   double del,t,*pt,*ptt,*xit;
1.181     brouard  4166:   double directest;
1.126     brouard  4167:   double fp,fptt;
                   4168:   double *xits;
                   4169:   int niterf, itmp;
1.349     brouard  4170:   int Bigter=0, nBigterf=1;
                   4171:   
1.126     brouard  4172:   pt=vector(1,n); 
                   4173:   ptt=vector(1,n); 
                   4174:   xit=vector(1,n); 
                   4175:   xits=vector(1,n); 
                   4176:   *fret=(*func)(p); 
                   4177:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.338     brouard  4178:   rcurr_time = time(NULL);
                   4179:   fp=(*fret); /* Initialisation */
1.126     brouard  4180:   for (*iter=1;;++(*iter)) { 
                   4181:     ibig=0; 
                   4182:     del=0.0; 
1.157     brouard  4183:     rlast_time=rcurr_time;
1.349     brouard  4184:     rlast_btime=rcurr_time;
1.157     brouard  4185:     /* (void) gettimeofday(&curr_time,&tzp); */
                   4186:     rcurr_time = time(NULL);  
                   4187:     curr_time = *localtime(&rcurr_time);
1.337     brouard  4188:     /* 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); */
                   4189:     /* 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  4190:     /* Bigter=(*iter - *iter % ncovmodel)/ncovmodel +1; /\* Big iteration, i.e on ncovmodel cycle *\/ */
                   4191:     Bigter=(*iter - (*iter-1) % n)/n +1; /* Big iteration, i.e on ncovmodel cycle */
1.349     brouard  4192:     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);
                   4193:     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);
                   4194:     fprintf(ficrespow,"%d %d %.12f %d",*iter,Bigter, *fret,curr_time.tm_sec-start_time.tm_sec);
1.324     brouard  4195:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  4196:     for (i=1;i<=n;i++) {
1.126     brouard  4197:       fprintf(ficrespow," %.12lf", p[i]);
                   4198:     }
1.239     brouard  4199:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   4200:     printf("\n#model=  1      +     age ");
                   4201:     fprintf(ficlog,"\n#model=  1      +     age ");
                   4202:     if(nagesqr==1){
1.241     brouard  4203:        printf("  + age*age  ");
                   4204:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  4205:     }
                   4206:     for(j=1;j <=ncovmodel-2;j++){
                   4207:       if(Typevar[j]==0) {
                   4208:        printf("  +      V%d  ",Tvar[j]);
                   4209:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   4210:       }else if(Typevar[j]==1) {
                   4211:        printf("  +    V%d*age ",Tvar[j]);
                   4212:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   4213:       }else if(Typevar[j]==2) {
                   4214:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   4215:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  4216:       }else if(Typevar[j]==3) {
                   4217:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   4218:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.239     brouard  4219:       }
                   4220:     }
1.126     brouard  4221:     printf("\n");
1.239     brouard  4222: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   4223: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  4224:     fprintf(ficlog,"\n");
1.239     brouard  4225:     for(i=1,jk=1; i <=nlstate; i++){
                   4226:       for(k=1; k <=(nlstate+ndeath); k++){
                   4227:        if (k != i) {
                   4228:          printf("%d%d ",i,k);
                   4229:          fprintf(ficlog,"%d%d ",i,k);
                   4230:          for(j=1; j <=ncovmodel; j++){
                   4231:            printf("%12.7f ",p[jk]);
                   4232:            fprintf(ficlog,"%12.7f ",p[jk]);
                   4233:            jk++; 
                   4234:          }
                   4235:          printf("\n");
                   4236:          fprintf(ficlog,"\n");
                   4237:        }
                   4238:       }
                   4239:     }
1.241     brouard  4240:     if(*iter <=3 && *iter >1){
1.157     brouard  4241:       tml = *localtime(&rcurr_time);
                   4242:       strcpy(strcurr,asctime(&tml));
                   4243:       rforecast_time=rcurr_time; 
1.126     brouard  4244:       itmp = strlen(strcurr);
                   4245:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  4246:        strcurr[itmp-1]='\0';
1.162     brouard  4247:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  4248:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.349     brouard  4249:       for(nBigterf=1;nBigterf<=31;nBigterf+=10){
                   4250:        niterf=nBigterf*ncovmodel;
                   4251:        /* rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time); */
1.241     brouard  4252:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   4253:        forecast_time = *localtime(&rforecast_time);
                   4254:        strcpy(strfor,asctime(&forecast_time));
                   4255:        itmp = strlen(strfor);
                   4256:        if(strfor[itmp-1]=='\n')
                   4257:          strfor[itmp-1]='\0';
1.349     brouard  4258:        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);
                   4259:        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  4260:       }
                   4261:     }
1.359     brouard  4262:     for (i=1;i<=n;i++) { /* For each direction i, maximisation after loading directions */
                   4263:       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  */
                   4264: 
                   4265:       fptt=(*fret); /* Computes likelihood for parameters xit */
1.126     brouard  4266: #ifdef DEBUG
1.203     brouard  4267:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   4268:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  4269: #endif
1.203     brouard  4270:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  4271:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  4272: #ifdef LINMINORIGINAL
1.359     brouard  4273:       linmin(p,xit,n,fret,func); /* New point i minimizing in direction xit, i has coordinates p[j].*/
1.357     brouard  4274:       /* xit[j] gives the n coordinates of direction i as input.*/
                   4275:       /* *fret gives the maximum value on direction xit */
1.224     brouard  4276: #else
                   4277:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.359     brouard  4278:       flatdir[i]=flat; /* Function is vanishing in that direction i */
1.224     brouard  4279: #endif
1.359     brouard  4280:       /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  4281:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.359     brouard  4282:        /* because that direction will be replaced unless the gain del is small */
                   4283:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   4284:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   4285:        /* with the new direction. */
                   4286:        del=fabs(fptt-(*fret)); 
                   4287:        ibig=i; 
1.126     brouard  4288:       } 
                   4289: #ifdef DEBUG
                   4290:       printf("%d %.12e",i,(*fret));
                   4291:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   4292:       for (j=1;j<=n;j++) {
1.359     brouard  4293:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   4294:        printf(" x(%d)=%.12e",j,xit[j]);
                   4295:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  4296:       }
                   4297:       for(j=1;j<=n;j++) {
1.359     brouard  4298:        printf(" p(%d)=%.12e",j,p[j]);
                   4299:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  4300:       }
                   4301:       printf("\n");
                   4302:       fprintf(ficlog,"\n");
                   4303: #endif
1.187     brouard  4304:     } /* end loop on each direction i */
1.357     brouard  4305:     /* Convergence test will use last linmin estimation (fret) and compare to former iteration (fp) */ 
1.188     brouard  4306:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.359     brouard  4307:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  4308:     for(j=1;j<=n;j++) {
                   4309:       if(flatdir[j] >0){
                   4310:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   4311:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  4312:       }
1.319     brouard  4313:       /* printf("\n"); */
                   4314:       /* fprintf(ficlog,"\n"); */
                   4315:     }
1.243     brouard  4316:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   4317:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  4318:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   4319:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   4320:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   4321:       /* decreased of more than 3.84  */
                   4322:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   4323:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   4324:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  4325:                        
1.188     brouard  4326:       /* Starting the program with initial values given by a former maximization will simply change */
                   4327:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   4328:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   4329:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  4330: #ifdef DEBUG
                   4331:       int k[2],l;
                   4332:       k[0]=1;
                   4333:       k[1]=-1;
                   4334:       printf("Max: %.12e",(*func)(p));
                   4335:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   4336:       for (j=1;j<=n;j++) {
                   4337:        printf(" %.12e",p[j]);
                   4338:        fprintf(ficlog," %.12e",p[j]);
                   4339:       }
                   4340:       printf("\n");
                   4341:       fprintf(ficlog,"\n");
                   4342:       for(l=0;l<=1;l++) {
                   4343:        for (j=1;j<=n;j++) {
                   4344:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   4345:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   4346:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   4347:        }
                   4348:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   4349:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   4350:       }
                   4351: #endif
                   4352: 
                   4353:       free_vector(xit,1,n); 
                   4354:       free_vector(xits,1,n); 
                   4355:       free_vector(ptt,1,n); 
                   4356:       free_vector(pt,1,n); 
                   4357:       return; 
1.192     brouard  4358:     } /* enough precision */ 
1.240     brouard  4359:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.359     brouard  4360:     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  4361:       ptt[j]=2.0*p[j]-pt[j]; 
1.359     brouard  4362:       xit[j]=p[j]-pt[j]; /* Coordinate j of last direction xi_n=P_n-P_0 */
                   4363: #ifdef DEBUG
                   4364:       printf("\n %d xit=%12.7g p=%12.7g pt=%12.7g ",j,xit[j],p[j],pt[j]);
                   4365: #endif
                   4366:       pt[j]=p[j]; /* New P0 is Pn */
                   4367:     }
                   4368: #ifdef DEBUG
                   4369:     printf("\n");
                   4370: #endif
1.181     brouard  4371:     fptt=(*func)(ptt); /* f_3 */
1.359     brouard  4372: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in directions until some iterations are done */
1.224     brouard  4373:                if (*iter <=4) {
1.225     brouard  4374: #else
                   4375: #endif
1.224     brouard  4376: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  4377: #else
1.161     brouard  4378:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  4379: #endif
1.162     brouard  4380:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  4381:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  4382:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   4383:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   4384:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  4385:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   4386:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   4387:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  4388:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  4389:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   4390:       /* mu² and del² are equal when f3=f1 */
1.359     brouard  4391:       /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   4392:       /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   4393:       /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   4394:       /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  4395: #ifdef NRCORIGINAL
                   4396:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   4397: #else
                   4398:       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  4399:       t= t- del*SQR(fp-fptt);
1.183     brouard  4400: #endif
1.202     brouard  4401:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  4402: #ifdef DEBUG
1.181     brouard  4403:       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);
                   4404:       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  4405:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   4406:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   4407:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   4408:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   4409:       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);
                   4410:       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);
                   4411: #endif
1.183     brouard  4412: #ifdef POWELLORIGINAL
                   4413:       if (t < 0.0) { /* Then we use it for new direction */
                   4414: #else
1.182     brouard  4415:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.359     brouard  4416:        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  4417:         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  4418:         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  4419:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   4420:       } 
1.181     brouard  4421:       if (directest < 0.0) { /* Then we use it for new direction */
                   4422: #endif
1.191     brouard  4423: #ifdef DEBUGLINMIN
1.234     brouard  4424:        printf("Before linmin in direction P%d-P0\n",n);
                   4425:        for (j=1;j<=n;j++) {
                   4426:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   4427:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   4428:          if(j % ncovmodel == 0){
                   4429:            printf("\n");
                   4430:            fprintf(ficlog,"\n");
                   4431:          }
                   4432:        }
1.224     brouard  4433: #endif
                   4434: #ifdef LINMINORIGINAL
1.234     brouard  4435:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  4436: #else
1.234     brouard  4437:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   4438:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  4439: #endif
1.234     brouard  4440:        
1.191     brouard  4441: #ifdef DEBUGLINMIN
1.234     brouard  4442:        for (j=1;j<=n;j++) { 
                   4443:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   4444:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   4445:          if(j % ncovmodel == 0){
                   4446:            printf("\n");
                   4447:            fprintf(ficlog,"\n");
                   4448:          }
                   4449:        }
1.224     brouard  4450: #endif
1.234     brouard  4451:        for (j=1;j<=n;j++) { 
                   4452:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   4453:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   4454:        }
1.224     brouard  4455: #ifdef LINMINORIGINAL
                   4456: #else
1.234     brouard  4457:        for (j=1, flatd=0;j<=n;j++) {
                   4458:          if(flatdir[j]>0)
                   4459:            flatd++;
                   4460:        }
                   4461:        if(flatd >0){
1.255     brouard  4462:          printf("%d flat directions: ",flatd);
                   4463:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  4464:          for (j=1;j<=n;j++) { 
                   4465:            if(flatdir[j]>0){
                   4466:              printf("%d ",j);
                   4467:              fprintf(ficlog,"%d ",j);
                   4468:            }
                   4469:          }
                   4470:          printf("\n");
                   4471:          fprintf(ficlog,"\n");
1.319     brouard  4472: #ifdef FLATSUP
                   4473:           free_vector(xit,1,n); 
                   4474:           free_vector(xits,1,n); 
                   4475:           free_vector(ptt,1,n); 
                   4476:           free_vector(pt,1,n); 
                   4477:           return;
                   4478: #endif
1.234     brouard  4479:        }
1.191     brouard  4480: #endif
1.234     brouard  4481:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   4482:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   4483:        
1.126     brouard  4484: #ifdef DEBUG
1.234     brouard  4485:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   4486:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   4487:        for(j=1;j<=n;j++){
                   4488:          printf(" %lf",xit[j]);
                   4489:          fprintf(ficlog," %lf",xit[j]);
                   4490:        }
                   4491:        printf("\n");
                   4492:        fprintf(ficlog,"\n");
1.126     brouard  4493: #endif
1.192     brouard  4494:       } /* end of t or directest negative */
1.359     brouard  4495:       printf(" Directest is positive, P_n-P_0 does not increase the conjugacy. n=%d\n",n);
                   4496:       fprintf(ficlog," Directest is positive, P_n-P_0 does not increase the conjugacy. n=%d\n",n);
1.224     brouard  4497: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  4498: #else
1.234     brouard  4499:       } /* end if (fptt < fp)  */
1.192     brouard  4500: #endif
1.225     brouard  4501: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  4502:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  4503: #else
1.224     brouard  4504: #endif
1.234     brouard  4505:                } /* loop iteration */ 
1.126     brouard  4506: } 
1.234     brouard  4507:   
1.126     brouard  4508: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  4509:   
1.235     brouard  4510:   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  4511:   {
1.338     brouard  4512:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
1.279     brouard  4513:      *   (and selected quantitative values in nres)
                   4514:      *  by left multiplying the unit
                   4515:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   4516:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   4517:      * Wx is row vector: population in state 1, population in state 2, population dead
                   4518:      * or prevalence in state 1, prevalence in state 2, 0
                   4519:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   4520:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   4521:      * Output is prlim.
                   4522:      * Initial matrix pimij 
                   4523:      */
1.206     brouard  4524:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   4525:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   4526:   /*  0,                   0                  , 1} */
                   4527:   /*
                   4528:    * and after some iteration: */
                   4529:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   4530:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   4531:   /*  0,                   0                  , 1} */
                   4532:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   4533:   /* {0.51571254859325999, 0.4842874514067399, */
                   4534:   /*  0.51326036147820708, 0.48673963852179264} */
                   4535:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  4536:     
1.332     brouard  4537:     int i, ii,j,k, k1;
1.209     brouard  4538:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  4539:   /* double **matprod2(); */ /* test */
1.218     brouard  4540:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  4541:   double **newm;
1.209     brouard  4542:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  4543:   int ncvloop=0;
1.288     brouard  4544:   int first=0;
1.169     brouard  4545:   
1.209     brouard  4546:   min=vector(1,nlstate);
                   4547:   max=vector(1,nlstate);
                   4548:   meandiff=vector(1,nlstate);
                   4549: 
1.218     brouard  4550:        /* Starting with matrix unity */
1.126     brouard  4551:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   4552:     for (j=1;j<=nlstate+ndeath;j++){
                   4553:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4554:     }
1.169     brouard  4555:   
                   4556:   cov[1]=1.;
                   4557:   
                   4558:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  4559:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  4560:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  4561:     ncvloop++;
1.126     brouard  4562:     newm=savm;
                   4563:     /* Covariates have to be included here again */
1.138     brouard  4564:     cov[2]=agefin;
1.319     brouard  4565:      if(nagesqr==1){
                   4566:       cov[3]= agefin*agefin;
                   4567:      }
1.332     brouard  4568:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   4569:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   4570:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  4571:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  4572:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   4573:        }else{
                   4574:         cov[2+nagesqr+k1]=precov[nres][k1];
                   4575:        }
                   4576:      }/* End of loop on model equation */
                   4577:      
                   4578: /* Start of old code (replaced by a loop on position in the model equation */
                   4579:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   4580:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   4581:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   4582:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   4583:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   4584:     /*    * k                  1        2      3    4      5      6     7        8 */
                   4585:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   4586:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   4587:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   4588:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   4589:     /*    *nsd=3                              (1)  (2)           (3) */
                   4590:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   4591:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   4592:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   4593:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   4594:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   4595:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   4596:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   4597:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   4598:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   4599:     /*    *TvarsDpType */
                   4600:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   4601:     /*    * nsd=1              (1)           (2) */
                   4602:     /*    *TvarsD[nsd]          3             2 */
                   4603:     /*    *TnsdVar           (3)=1          (2)=2 */
                   4604:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   4605:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   4606:     /*    *\/ */
                   4607:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   4608:     /*   /\* 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)); *\/ */
                   4609:     /* } */
                   4610:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   4611:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   4612:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   4613:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   4614:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   4615:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   4616:     /*   /\* 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]); *\/ */
                   4617:     /* } */
                   4618:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   4619:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   4620:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   4621:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   4622:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   4623:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   4624:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   4625:     /*   } */
                   4626:     /*   /\* 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]); *\/ */
                   4627:     /* } */
                   4628:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   4629:     /*   /\* 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]); *\/ */
                   4630:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   4631:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   4632:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   4633:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   4634:     /*         }else{ */
                   4635:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   4636:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   4637:     /*         } */
                   4638:     /*   }else{ */
                   4639:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   4640:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   4641:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   4642:     /*         }else{ */
                   4643:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   4644:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   4645:     /*         } */
                   4646:     /*   } */
                   4647:     /* } /\* End product without age *\/ */
                   4648: /* ENd of old code */
1.138     brouard  4649:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   4650:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   4651:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  4652:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4653:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  4654:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  4655:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  4656:     
1.126     brouard  4657:     savm=oldm;
                   4658:     oldm=newm;
1.209     brouard  4659: 
                   4660:     for(j=1; j<=nlstate; j++){
                   4661:       max[j]=0.;
                   4662:       min[j]=1.;
                   4663:     }
                   4664:     for(i=1;i<=nlstate;i++){
                   4665:       sumnew=0;
                   4666:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   4667:       for(j=1; j<=nlstate; j++){ 
                   4668:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   4669:        max[j]=FMAX(max[j],prlim[i][j]);
                   4670:        min[j]=FMIN(min[j],prlim[i][j]);
                   4671:       }
                   4672:     }
                   4673: 
1.126     brouard  4674:     maxmax=0.;
1.209     brouard  4675:     for(j=1; j<=nlstate; j++){
                   4676:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   4677:       maxmax=FMAX(maxmax,meandiff[j]);
                   4678:       /* 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  4679:     } /* j loop */
1.203     brouard  4680:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  4681:     /* 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  4682:     if(maxmax < ftolpl){
1.209     brouard  4683:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   4684:       free_vector(min,1,nlstate);
                   4685:       free_vector(max,1,nlstate);
                   4686:       free_vector(meandiff,1,nlstate);
1.126     brouard  4687:       return prlim;
                   4688:     }
1.288     brouard  4689:   } /* agefin loop */
1.208     brouard  4690:     /* After some age loop it doesn't converge */
1.288     brouard  4691:   if(!first){
                   4692:     first=1;
                   4693:     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  4694:     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);
                   4695:   }else if (first >=1 && first <10){
                   4696:     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);
                   4697:     first++;
                   4698:   }else if (first ==10){
                   4699:     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);
                   4700:     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");
                   4701:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   4702:     first++;
1.288     brouard  4703:   }
                   4704: 
1.359     brouard  4705:   /* Try to lower 'ftol', for example from 1.e-8 to 6.e-9.\n", ftolpl,
                   4706:    * (int)age, (int)delaymax, (int)agefin, ncvloop,
                   4707:    * (int)age-(int)agefin); */
1.209     brouard  4708:   free_vector(min,1,nlstate);
                   4709:   free_vector(max,1,nlstate);
                   4710:   free_vector(meandiff,1,nlstate);
1.208     brouard  4711:   
1.169     brouard  4712:   return prlim; /* should not reach here */
1.126     brouard  4713: }
                   4714: 
1.217     brouard  4715: 
                   4716:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   4717: 
1.218     brouard  4718:  /* 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) */
                   4719:  /* 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  4720:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  4721: {
1.264     brouard  4722:   /* 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  4723:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   4724:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   4725:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   4726:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   4727:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   4728:   /* Initial matrix pimij */
                   4729:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   4730:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   4731:   /*  0,                   0                  , 1} */
                   4732:   /*
                   4733:    * and after some iteration: */
                   4734:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   4735:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   4736:   /*  0,                   0                  , 1} */
                   4737:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   4738:   /* {0.51571254859325999, 0.4842874514067399, */
                   4739:   /*  0.51326036147820708, 0.48673963852179264} */
                   4740:   /* If we start from prlim again, prlim tends to a constant matrix */
                   4741: 
1.359     brouard  4742:   int i, ii,j, k1;
1.247     brouard  4743:   int first=0;
1.217     brouard  4744:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   4745:   /* double **matprod2(); */ /* test */
                   4746:   double **out, cov[NCOVMAX+1], **bmij();
                   4747:   double **newm;
1.218     brouard  4748:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   4749:   double        **oldm, **savm;  /* for use */
                   4750: 
1.217     brouard  4751:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   4752:   int ncvloop=0;
                   4753:   
                   4754:   min=vector(1,nlstate);
                   4755:   max=vector(1,nlstate);
                   4756:   meandiff=vector(1,nlstate);
                   4757: 
1.266     brouard  4758:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   4759:   oldm=oldms; savm=savms;
                   4760:   
                   4761:   /* Starting with matrix unity */
                   4762:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   4763:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  4764:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4765:     }
                   4766:   
                   4767:   cov[1]=1.;
                   4768:   
                   4769:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   4770:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  4771:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  4772:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   4773:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  4774:     ncvloop++;
1.218     brouard  4775:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   4776:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  4777:     /* Covariates have to be included here again */
                   4778:     cov[2]=agefin;
1.319     brouard  4779:     if(nagesqr==1){
1.217     brouard  4780:       cov[3]= agefin*agefin;;
1.319     brouard  4781:     }
1.332     brouard  4782:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  4783:       if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  4784:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  4785:       }else{
1.332     brouard  4786:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  4787:       }
1.332     brouard  4788:     }/* End of loop on model equation */
                   4789: 
                   4790: /* Old code */ 
                   4791: 
                   4792:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   4793:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   4794:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   4795:     /*   /\* 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)); *\/ */
                   4796:     /* } */
                   4797:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   4798:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   4799:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   4800:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   4801:     /* /\* } *\/ */
                   4802:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   4803:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   4804:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   4805:     /*   /\* 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]); *\/ */
                   4806:     /* } */
                   4807:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   4808:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   4809:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   4810:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   4811:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   4812:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   4813:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   4814:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   4815:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   4816:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   4817:     /*   } */
                   4818:     /*   /\* 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]); *\/ */
                   4819:     /* } */
                   4820:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   4821:     /*   /\* 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]); *\/ */
                   4822:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   4823:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   4824:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   4825:     /*         }else{ */
                   4826:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   4827:     /*         } */
                   4828:     /*   }else{ */
                   4829:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   4830:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   4831:     /*         }else{ */
                   4832:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   4833:     /*         } */
                   4834:     /*   } */
                   4835:     /* } */
1.217     brouard  4836:     
                   4837:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   4838:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   4839:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   4840:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4841:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  4842:                /* ij should be linked to the correct index of cov */
                   4843:                /* age and covariate values ij are in 'cov', but we need to pass
                   4844:                 * ij for the observed prevalence at age and status and covariate
                   4845:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   4846:                 */
                   4847:     /* 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 *\/ */
                   4848:     /* 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 *\/ */
                   4849:     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  4850:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  4851:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   4852:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   4853:     /*         printf("%d newm= ",i); */
                   4854:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   4855:     /*           printf("%f ",newm[i][j]); */
                   4856:     /*         } */
                   4857:     /*         printf("oldm * "); */
                   4858:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   4859:     /*           printf("%f ",oldm[i][j]); */
                   4860:     /*         } */
1.268     brouard  4861:     /*         printf(" bmmij "); */
1.266     brouard  4862:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   4863:     /*           printf("%f ",pmmij[i][j]); */
                   4864:     /*         } */
                   4865:     /*         printf("\n"); */
                   4866:     /*   } */
                   4867:     /* } */
1.217     brouard  4868:     savm=oldm;
                   4869:     oldm=newm;
1.266     brouard  4870: 
1.217     brouard  4871:     for(j=1; j<=nlstate; j++){
                   4872:       max[j]=0.;
                   4873:       min[j]=1.;
                   4874:     }
                   4875:     for(j=1; j<=nlstate; j++){ 
                   4876:       for(i=1;i<=nlstate;i++){
1.234     brouard  4877:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   4878:        bprlim[i][j]= newm[i][j];
                   4879:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   4880:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  4881:       }
                   4882:     }
1.218     brouard  4883:                
1.217     brouard  4884:     maxmax=0.;
                   4885:     for(i=1; i<=nlstate; i++){
1.318     brouard  4886:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  4887:       maxmax=FMAX(maxmax,meandiff[i]);
                   4888:       /* 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  4889:     } /* i loop */
1.217     brouard  4890:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  4891:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  4892:     if(maxmax < ftolpl){
1.220     brouard  4893:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  4894:       free_vector(min,1,nlstate);
                   4895:       free_vector(max,1,nlstate);
                   4896:       free_vector(meandiff,1,nlstate);
                   4897:       return bprlim;
                   4898:     }
1.288     brouard  4899:   } /* agefin loop */
1.217     brouard  4900:     /* After some age loop it doesn't converge */
1.288     brouard  4901:   if(!first){
1.247     brouard  4902:     first=1;
                   4903:     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\
                   4904: 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);
                   4905:   }
                   4906:   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  4907: 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);
                   4908:   /* 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); */
                   4909:   free_vector(min,1,nlstate);
                   4910:   free_vector(max,1,nlstate);
                   4911:   free_vector(meandiff,1,nlstate);
                   4912:   
                   4913:   return bprlim; /* should not reach here */
                   4914: }
                   4915: 
1.126     brouard  4916: /*************** transition probabilities ***************/ 
                   4917: 
                   4918: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   4919: {
1.138     brouard  4920:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  4921:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  4922:      model to the ncovmodel covariates (including constant and age).
                   4923:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   4924:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   4925:      ncth covariate in the global vector x is given by the formula:
                   4926:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   4927:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   4928:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   4929:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  4930:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  4931:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  4932:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  4933:   */
                   4934:   double s1, lnpijopii;
1.126     brouard  4935:   /*double t34;*/
1.164     brouard  4936:   int i,j, nc, ii, jj;
1.126     brouard  4937: 
1.223     brouard  4938:   for(i=1; i<= nlstate; i++){
                   4939:     for(j=1; j<i;j++){
                   4940:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   4941:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   4942:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   4943:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   4944:       }
                   4945:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  4946:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  4947:     }
                   4948:     for(j=i+1; j<=nlstate+ndeath;j++){
                   4949:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   4950:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   4951:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   4952:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   4953:       }
                   4954:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  4955:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  4956:     }
                   4957:   }
1.218     brouard  4958:   
1.223     brouard  4959:   for(i=1; i<= nlstate; i++){
                   4960:     s1=0;
                   4961:     for(j=1; j<i; j++){
1.339     brouard  4962:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  4963:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   4964:     }
                   4965:     for(j=i+1; j<=nlstate+ndeath; j++){
1.339     brouard  4966:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  4967:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   4968:     }
                   4969:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   4970:     ps[i][i]=1./(s1+1.);
                   4971:     /* Computing other pijs */
                   4972:     for(j=1; j<i; j++)
1.325     brouard  4973:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  4974:     for(j=i+1; j<=nlstate+ndeath; j++)
                   4975:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   4976:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   4977:   } /* end i */
1.218     brouard  4978:   
1.223     brouard  4979:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   4980:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   4981:       ps[ii][jj]=0;
                   4982:       ps[ii][ii]=1;
                   4983:     }
                   4984:   }
1.294     brouard  4985: 
                   4986: 
1.223     brouard  4987:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   4988:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   4989:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   4990:   /*   } */
                   4991:   /*   printf("\n "); */
                   4992:   /* } */
                   4993:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   4994:   /*
                   4995:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  4996:                goto end;*/
1.266     brouard  4997:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  4998: }
                   4999: 
1.218     brouard  5000: /*************** backward transition probabilities ***************/ 
                   5001: 
                   5002:  /* 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 ) */
                   5003: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   5004:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   5005: {
1.302     brouard  5006:   /* 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  5007:    * 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  5008:    */
1.359     brouard  5009:   int ii, j;
1.222     brouard  5010:   
1.359     brouard  5011:   double  **pmij();
1.222     brouard  5012:   double sumnew=0.;
1.218     brouard  5013:   double agefin;
1.292     brouard  5014:   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  5015:   double **dnewm, **dsavm, **doldm;
                   5016:   double **bbmij;
                   5017:   
1.218     brouard  5018:   doldm=ddoldms; /* global pointers */
1.222     brouard  5019:   dnewm=ddnewms;
                   5020:   dsavm=ddsavms;
1.318     brouard  5021: 
                   5022:   /* Debug */
                   5023:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  5024:   agefin=cov[2];
1.268     brouard  5025:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  5026:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  5027:      the observed prevalence (with this covariate ij) at beginning of transition */
                   5028:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  5029: 
                   5030:   /* P_x */
1.325     brouard  5031:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  5032:   /* outputs pmmij which is a stochastic matrix in row */
                   5033: 
                   5034:   /* Diag(w_x) */
1.292     brouard  5035:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  5036:   sumnew=0.;
1.269     brouard  5037:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  5038:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  5039:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  5040:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   5041:   }
                   5042:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   5043:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   5044:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  5045:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  5046:     }
                   5047:   }else{
                   5048:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   5049:       for (j=1;j<=nlstate+ndeath;j++)
                   5050:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   5051:     }
                   5052:     /* if(sumnew <0.9){ */
                   5053:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   5054:     /* } */
                   5055:   }
                   5056:   k3=0.0;  /* We put the last diagonal to 0 */
                   5057:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   5058:       doldm[ii][ii]= k3;
                   5059:   }
                   5060:   /* End doldm, At the end doldm is diag[(w_i)] */
                   5061:   
1.292     brouard  5062:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   5063:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  5064: 
1.292     brouard  5065:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  5066:   /* 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  5067:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  5068:     sumnew=0.;
1.222     brouard  5069:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  5070:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  5071:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  5072:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  5073:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  5074:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  5075:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  5076:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  5077:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  5078:        /* }else */
1.268     brouard  5079:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   5080:     } /*End ii */
                   5081:   } /* 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 */
                   5082: 
1.292     brouard  5083:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  5084:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  5085:   /* end bmij */
1.266     brouard  5086:   return ps; /*pointer is unchanged */
1.218     brouard  5087: }
1.217     brouard  5088: /*************** transition probabilities ***************/ 
                   5089: 
1.218     brouard  5090: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  5091: {
                   5092:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   5093:      computes the probability to be observed in state j being in state i by appying the
                   5094:      model to the ncovmodel covariates (including constant and age).
                   5095:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   5096:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   5097:      ncth covariate in the global vector x is given by the formula:
                   5098:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   5099:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   5100:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   5101:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   5102:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   5103:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   5104:   */
                   5105:   double s1, lnpijopii;
                   5106:   /*double t34;*/
                   5107:   int i,j, nc, ii, jj;
                   5108: 
1.234     brouard  5109:   for(i=1; i<= nlstate; i++){
                   5110:     for(j=1; j<i;j++){
                   5111:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   5112:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   5113:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   5114:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   5115:       }
                   5116:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   5117:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   5118:     }
                   5119:     for(j=i+1; j<=nlstate+ndeath;j++){
                   5120:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   5121:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   5122:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   5123:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   5124:       }
                   5125:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   5126:     }
                   5127:   }
                   5128:   
                   5129:   for(i=1; i<= nlstate; i++){
                   5130:     s1=0;
                   5131:     for(j=1; j<i; j++){
                   5132:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   5133:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   5134:     }
                   5135:     for(j=i+1; j<=nlstate+ndeath; j++){
                   5136:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   5137:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   5138:     }
                   5139:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   5140:     ps[i][i]=1./(s1+1.);
                   5141:     /* Computing other pijs */
                   5142:     for(j=1; j<i; j++)
                   5143:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   5144:     for(j=i+1; j<=nlstate+ndeath; j++)
                   5145:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   5146:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   5147:   } /* end i */
                   5148:   
                   5149:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   5150:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   5151:       ps[ii][jj]=0;
                   5152:       ps[ii][ii]=1;
                   5153:     }
                   5154:   }
1.296     brouard  5155:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  5156:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   5157:     s1=0.;
                   5158:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   5159:       s1+=ps[ii][jj];
                   5160:     }
                   5161:     for(ii=1; ii<= nlstate; ii++){
                   5162:       ps[ii][jj]=ps[ii][jj]/s1;
                   5163:     }
                   5164:   }
                   5165:   /* Transposition */
                   5166:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   5167:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   5168:       s1=ps[ii][jj];
                   5169:       ps[ii][jj]=ps[jj][ii];
                   5170:       ps[jj][ii]=s1;
                   5171:     }
                   5172:   }
                   5173:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   5174:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   5175:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   5176:   /*   } */
                   5177:   /*   printf("\n "); */
                   5178:   /* } */
                   5179:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   5180:   /*
                   5181:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   5182:     goto end;*/
                   5183:   return ps;
1.217     brouard  5184: }
                   5185: 
                   5186: 
1.126     brouard  5187: /**************** Product of 2 matrices ******************/
                   5188: 
1.145     brouard  5189: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  5190: {
                   5191:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   5192:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   5193:   /* in, b, out are matrice of pointers which should have been initialized 
                   5194:      before: only the contents of out is modified. The function returns
                   5195:      a pointer to pointers identical to out */
1.145     brouard  5196:   int i, j, k;
1.126     brouard  5197:   for(i=nrl; i<= nrh; i++)
1.145     brouard  5198:     for(k=ncolol; k<=ncoloh; k++){
                   5199:       out[i][k]=0.;
                   5200:       for(j=ncl; j<=nch; j++)
                   5201:        out[i][k] +=in[i][j]*b[j][k];
                   5202:     }
1.126     brouard  5203:   return out;
                   5204: }
                   5205: 
                   5206: 
                   5207: /************* Higher Matrix Product ***************/
                   5208: 
1.235     brouard  5209: 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  5210: {
1.336     brouard  5211:   /* Already optimized with precov.
                   5212:      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  5213:      'nhstepm*hstepm*stepm' months (i.e. until
                   5214:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   5215:      nhstepm*hstepm matrices. 
                   5216:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   5217:      (typically every 2 years instead of every month which is too big 
                   5218:      for the memory).
                   5219:      Model is determined by parameters x and covariates have to be 
                   5220:      included manually here. 
                   5221: 
                   5222:      */
                   5223: 
1.359     brouard  5224:   int i, j, d, h, k1;
1.131     brouard  5225:   double **out, cov[NCOVMAX+1];
1.126     brouard  5226:   double **newm;
1.187     brouard  5227:   double agexact;
1.359     brouard  5228:   /*double agebegin, ageend;*/
1.126     brouard  5229: 
                   5230:   /* Hstepm could be zero and should return the unit matrix */
                   5231:   for (i=1;i<=nlstate+ndeath;i++)
                   5232:     for (j=1;j<=nlstate+ndeath;j++){
                   5233:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   5234:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   5235:     }
                   5236:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   5237:   for(h=1; h <=nhstepm; h++){
                   5238:     for(d=1; d <=hstepm; d++){
                   5239:       newm=savm;
                   5240:       /* Covariates have to be included here again */
                   5241:       cov[1]=1.;
1.214     brouard  5242:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  5243:       cov[2]=agexact;
1.319     brouard  5244:       if(nagesqr==1){
1.227     brouard  5245:        cov[3]= agexact*agexact;
1.319     brouard  5246:       }
1.330     brouard  5247:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   5248:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   5249:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  5250:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  5251:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   5252:        }else{
                   5253:          cov[2+nagesqr+k1]=precov[nres][k1];
                   5254:        }
                   5255:       }/* End of loop on model equation */
                   5256:        /* Old code */ 
                   5257: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   5258: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   5259: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   5260: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   5261: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   5262: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   5263: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   5264: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   5265: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   5266: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   5267: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   5268: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   5269: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   5270: /*       /\* 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]])); *\/ */
                   5271: /*       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); */
                   5272: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   5273: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   5274: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   5275: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   5276: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   5277: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   5278: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   5279: /*       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]]); */
                   5280: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   5281: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   5282: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   5283: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   5284: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   5285: /*       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]); */
                   5286: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   5287: 
                   5288: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   5289: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   5290: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   5291: /*       /\* *\/ */
1.330     brouard  5292: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   5293: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   5294: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  5295: /* /\*cptcovage=2                   1               2      *\/ */
                   5296: /* /\*Tage[k]=                      5               8      *\/  */
                   5297: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   5298: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   5299: /*       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]]); */
                   5300: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   5301: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   5302: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   5303: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   5304: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   5305: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   5306: /*       /\*   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); *\/ */
                   5307: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   5308: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   5309: /*       /\* } *\/ */
                   5310: /*       /\* 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]); *\/ */
                   5311: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   5312: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   5313: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   5314: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   5315: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   5316: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   5317: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   5318: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   5319: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  5320:          
1.332     brouard  5321: /*       /\* 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])]); *\/ */
                   5322: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   5323: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   5324: /*       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]]); */
                   5325: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   5326: 
                   5327: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   5328: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   5329: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   5330: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   5331: /*           /\* 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]])]; *\/ */
                   5332: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   5333: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   5334: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   5335: /*       /\*   } *\/ */
                   5336: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   5337: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   5338: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   5339: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   5340: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   5341: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   5342: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   5343: /*       /\*   } *\/ */
                   5344: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   5345: /*     }/\*end of products *\/ */
                   5346:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  5347:       /* for (k=1; k<=cptcovn;k++)  */
                   5348:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   5349:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   5350:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   5351:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   5352:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  5353:       
                   5354:       
1.126     brouard  5355:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   5356:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  5357:       /* right multiplication of oldm by the current matrix */
1.126     brouard  5358:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   5359:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  5360:       /* if((int)age == 70){ */
                   5361:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   5362:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   5363:       /*         printf("%d pmmij ",i); */
                   5364:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   5365:       /*           printf("%f ",pmmij[i][j]); */
                   5366:       /*         } */
                   5367:       /*         printf(" oldm "); */
                   5368:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   5369:       /*           printf("%f ",oldm[i][j]); */
                   5370:       /*         } */
                   5371:       /*         printf("\n"); */
                   5372:       /*       } */
                   5373:       /* } */
1.126     brouard  5374:       savm=oldm;
                   5375:       oldm=newm;
                   5376:     }
                   5377:     for(i=1; i<=nlstate+ndeath; i++)
                   5378:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  5379:        po[i][j][h]=newm[i][j];
                   5380:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  5381:       }
1.128     brouard  5382:     /*printf("h=%d ",h);*/
1.126     brouard  5383:   } /* end h */
1.267     brouard  5384:   /*     printf("\n H=%d \n",h); */
1.126     brouard  5385:   return po;
                   5386: }
                   5387: 
1.217     brouard  5388: /************* Higher Back Matrix Product ***************/
1.218     brouard  5389: /* 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  5390: 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  5391: {
1.332     brouard  5392:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   5393:      computes the transition matrix starting at age 'age' over
1.217     brouard  5394:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  5395:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   5396:      nhstepm*hstepm matrices.
                   5397:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   5398:      (typically every 2 years instead of every month which is too big
1.217     brouard  5399:      for the memory).
1.218     brouard  5400:      Model is determined by parameters x and covariates have to be
1.266     brouard  5401:      included manually here. Then we use a call to bmij(x and cov)
                   5402:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  5403:   */
1.217     brouard  5404: 
1.359     brouard  5405:   int i, j, d, h, k1;
1.266     brouard  5406:   double **out, cov[NCOVMAX+1], **bmij();
                   5407:   double **newm, ***newmm;
1.217     brouard  5408:   double agexact;
1.359     brouard  5409:   /*double agebegin, ageend;*/
1.222     brouard  5410:   double **oldm, **savm;
1.217     brouard  5411: 
1.266     brouard  5412:   newmm=po; /* To be saved */
                   5413:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  5414:   /* Hstepm could be zero and should return the unit matrix */
                   5415:   for (i=1;i<=nlstate+ndeath;i++)
                   5416:     for (j=1;j<=nlstate+ndeath;j++){
                   5417:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   5418:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   5419:     }
                   5420:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   5421:   for(h=1; h <=nhstepm; h++){
                   5422:     for(d=1; d <=hstepm; d++){
                   5423:       newm=savm;
                   5424:       /* Covariates have to be included here again */
                   5425:       cov[1]=1.;
1.271     brouard  5426:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  5427:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  5428:         /* Debug */
                   5429:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  5430:       cov[2]=agexact;
1.332     brouard  5431:       if(nagesqr==1){
1.222     brouard  5432:        cov[3]= agexact*agexact;
1.332     brouard  5433:       }
                   5434:       /** New code */
                   5435:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  5436:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  5437:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  5438:        }else{
1.332     brouard  5439:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  5440:        }
1.332     brouard  5441:       }/* End of loop on model equation */
                   5442:       /** End of new code */
                   5443:   /** This was old code */
                   5444:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   5445:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   5446:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   5447:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   5448:       /*   /\* 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)); *\/ */
                   5449:       /* } */
                   5450:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   5451:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   5452:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   5453:       /*       /\* 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]); *\/ */
                   5454:       /* } */
                   5455:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   5456:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   5457:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   5458:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   5459:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   5460:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   5461:       /*       } */
                   5462:       /*       /\* 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]); *\/ */
                   5463:       /* } */
                   5464:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   5465:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   5466:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   5467:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   5468:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   5469:       /*         }else{ */
                   5470:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   5471:       /*         } */
                   5472:       /*       }else{ */
                   5473:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   5474:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   5475:       /*         }else{ */
                   5476:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   5477:       /*         } */
                   5478:       /*       } */
                   5479:       /* }                      */
                   5480:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   5481:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   5482: /** End of old code */
                   5483:       
1.218     brouard  5484:       /* Careful transposed matrix */
1.266     brouard  5485:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  5486:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  5487:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  5488:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  5489:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  5490:       /* if((int)age == 70){ */
                   5491:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   5492:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   5493:       /*         printf("%d pmmij ",i); */
                   5494:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   5495:       /*           printf("%f ",pmmij[i][j]); */
                   5496:       /*         } */
                   5497:       /*         printf(" oldm "); */
                   5498:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   5499:       /*           printf("%f ",oldm[i][j]); */
                   5500:       /*         } */
                   5501:       /*         printf("\n"); */
                   5502:       /*       } */
                   5503:       /* } */
                   5504:       savm=oldm;
                   5505:       oldm=newm;
                   5506:     }
                   5507:     for(i=1; i<=nlstate+ndeath; i++)
                   5508:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  5509:        po[i][j][h]=newm[i][j];
1.268     brouard  5510:        /* if(h==nhstepm) */
                   5511:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  5512:       }
1.268     brouard  5513:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  5514:   } /* end h */
1.268     brouard  5515:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  5516:   return po;
                   5517: }
                   5518: 
                   5519: 
1.162     brouard  5520: #ifdef NLOPT
                   5521:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   5522:   double fret;
                   5523:   double *xt;
                   5524:   int j;
                   5525:   myfunc_data *d2 = (myfunc_data *) pd;
                   5526: /* xt = (p1-1); */
                   5527:   xt=vector(1,n); 
                   5528:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   5529: 
                   5530:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   5531:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   5532:   printf("Function = %.12lf ",fret);
                   5533:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   5534:   printf("\n");
                   5535:  free_vector(xt,1,n);
                   5536:   return fret;
                   5537: }
                   5538: #endif
1.126     brouard  5539: 
                   5540: /*************** log-likelihood *************/
                   5541: double func( double *x)
                   5542: {
1.336     brouard  5543:   int i, ii, j, k, mi, d, kk, kf=0;
1.226     brouard  5544:   int ioffset=0;
1.339     brouard  5545:   int ipos=0,iposold=0,ncovv=0;
                   5546: 
1.340     brouard  5547:   double cotvarv, cotvarvold;
1.226     brouard  5548:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   5549:   double **out;
                   5550:   double lli; /* Individual log likelihood */
                   5551:   int s1, s2;
1.228     brouard  5552:   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  5553: 
1.226     brouard  5554:   double bbh, survp;
                   5555:   double agexact;
1.336     brouard  5556:   double agebegin, ageend;
1.226     brouard  5557:   /*extern weight */
                   5558:   /* We are differentiating ll according to initial status */
                   5559:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   5560:   /*for(i=1;i<imx;i++) 
                   5561:     printf(" %d\n",s[4][i]);
                   5562:   */
1.162     brouard  5563: 
1.226     brouard  5564:   ++countcallfunc;
1.162     brouard  5565: 
1.226     brouard  5566:   cov[1]=1.;
1.126     brouard  5567: 
1.226     brouard  5568:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  5569:   ioffset=0;
1.226     brouard  5570:   if(mle==1){
                   5571:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   5572:       /* Computes the values of the ncovmodel covariates of the model
                   5573:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   5574:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   5575:         to be observed in j being in i according to the model.
                   5576:       */
1.243     brouard  5577:       ioffset=2+nagesqr ;
1.233     brouard  5578:    /* Fixed */
1.345     brouard  5579:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummy or quant or prod */
1.319     brouard  5580:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   5581:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   5582:        /*  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  5583:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.336     brouard  5584:        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  5585:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  5586:       }
1.226     brouard  5587:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  5588:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  5589:         has been calculated etc */
                   5590:       /* For an individual i, wav[i] gives the number of effective waves */
                   5591:       /* We compute the contribution to Likelihood of each effective transition
                   5592:         mw[mi][i] is real wave of the mi th effectve wave */
                   5593:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   5594:         s2=s[mw[mi+1][i]][i];
1.341     brouard  5595:         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  5596:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   5597:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   5598:       */
1.336     brouard  5599:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   5600:       /* Wave varying (but not age varying) */
1.339     brouard  5601:        /* 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*\/ */
                   5602:        /*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
                   5603:        /*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   5604:        /* } */
1.340     brouard  5605:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
                   5606:          itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   5607:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  5608:          if(FixedV[itv]!=0){ /* Not a fixed covariate */
1.341     brouard  5609:            cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* cotvar[wav][ncovcol+nqv+iv][i] */
1.340     brouard  5610:          }else{ /* fixed covariate */
1.345     brouard  5611:            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  5612:          }
1.339     brouard  5613:          if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  5614:            cotvarvold=cotvarv;
                   5615:          }else{ /* A second product */
                   5616:            cotvarv=cotvarv*cotvarvold;
1.339     brouard  5617:          }
                   5618:          iposold=ipos;
1.340     brouard  5619:          cov[ioffset+ipos]=cotvarv;
1.234     brouard  5620:        }
1.339     brouard  5621:        /* for products of time varying to be done */
1.234     brouard  5622:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5623:          for (j=1;j<=nlstate+ndeath;j++){
                   5624:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5625:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5626:          }
1.336     brouard  5627: 
                   5628:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   5629:        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  5630:        for(d=0; d<dh[mi][i]; d++){
                   5631:          newm=savm;
                   5632:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5633:          cov[2]=agexact;
                   5634:          if(nagesqr==1)
                   5635:            cov[3]= agexact*agexact;  /* Should be changed here */
1.349     brouard  5636:          /* for (kk=1; kk<=cptcovage;kk++) { */
                   5637:          /*   if(!FixedV[Tvar[Tage[kk]]]) */
                   5638:          /*     cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /\* Tage[kk] gives the data-covariate associated with age *\/ */
                   5639:          /*   else */
                   5640:          /*     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) *\/  */
                   5641:          /* } */
                   5642:          for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   5643:            itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   5644:            ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   5645:            if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   5646:              cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   5647:            }else{ /* fixed covariate */
                   5648:              cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   5649:            }
                   5650:            if(ipos!=iposold){ /* Not a product or first of a product */
                   5651:              cotvarvold=cotvarv;
                   5652:            }else{ /* A second product */
                   5653:              cotvarv=cotvarv*cotvarvold;
                   5654:            }
                   5655:            iposold=ipos;
                   5656:            cov[ioffset+ipos]=cotvarv*agexact;
                   5657:            /* For products */
1.234     brouard  5658:          }
1.349     brouard  5659:          
1.234     brouard  5660:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5661:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5662:          savm=oldm;
                   5663:          oldm=newm;
                   5664:        } /* end mult */
                   5665:        
                   5666:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   5667:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   5668:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   5669:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   5670:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   5671:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   5672:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   5673:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  5674:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   5675:                                 * -stepm/2 to stepm/2 .
                   5676:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   5677:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   5678:                                 */
1.234     brouard  5679:        s1=s[mw[mi][i]][i];
                   5680:        s2=s[mw[mi+1][i]][i];
                   5681:        bbh=(double)bh[mi][i]/(double)stepm; 
                   5682:        /* bias bh is positive if real duration
                   5683:         * is higher than the multiple of stepm and negative otherwise.
                   5684:         */
                   5685:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   5686:        if( s2 > nlstate){ 
                   5687:          /* i.e. if s2 is a death state and if the date of death is known 
                   5688:             then the contribution to the likelihood is the probability to 
                   5689:             die between last step unit time and current  step unit time, 
                   5690:             which is also equal to probability to die before dh 
                   5691:             minus probability to die before dh-stepm . 
                   5692:             In version up to 0.92 likelihood was computed
                   5693:             as if date of death was unknown. Death was treated as any other
                   5694:             health state: the date of the interview describes the actual state
                   5695:             and not the date of a change in health state. The former idea was
                   5696:             to consider that at each interview the state was recorded
                   5697:             (healthy, disable or death) and IMaCh was corrected; but when we
                   5698:             introduced the exact date of death then we should have modified
                   5699:             the contribution of an exact death to the likelihood. This new
                   5700:             contribution is smaller and very dependent of the step unit
                   5701:             stepm. It is no more the probability to die between last interview
                   5702:             and month of death but the probability to survive from last
                   5703:             interview up to one month before death multiplied by the
                   5704:             probability to die within a month. Thanks to Chris
                   5705:             Jackson for correcting this bug.  Former versions increased
                   5706:             mortality artificially. The bad side is that we add another loop
                   5707:             which slows down the processing. The difference can be up to 10%
                   5708:             lower mortality.
                   5709:          */
                   5710:          /* If, at the beginning of the maximization mostly, the
                   5711:             cumulative probability or probability to be dead is
                   5712:             constant (ie = 1) over time d, the difference is equal to
                   5713:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   5714:             s1 at precedent wave, to be dead a month before current
                   5715:             wave is equal to probability, being at state s1 at
                   5716:             precedent wave, to be dead at mont of the current
                   5717:             wave. Then the observed probability (that this person died)
                   5718:             is null according to current estimated parameter. In fact,
                   5719:             it should be very low but not zero otherwise the log go to
                   5720:             infinity.
                   5721:          */
1.183     brouard  5722: /* #ifdef INFINITYORIGINAL */
                   5723: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   5724: /* #else */
                   5725: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   5726: /*         lli=log(mytinydouble); */
                   5727: /*       else */
                   5728: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   5729: /* #endif */
1.226     brouard  5730:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  5731:          
1.226     brouard  5732:        } else if  ( s2==-1 ) { /* alive */
                   5733:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   5734:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   5735:          /*survp += out[s1][j]; */
                   5736:          lli= log(survp);
                   5737:        }
1.336     brouard  5738:        /* else if  (s2==-4) {  */
                   5739:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
                   5740:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   5741:        /*   lli= log(survp);  */
                   5742:        /* }  */
                   5743:        /* else if  (s2==-5) {  */
                   5744:        /*   for (j=1,survp=0. ; j<=2; j++)   */
                   5745:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   5746:        /*   lli= log(survp);  */
                   5747:        /* }  */
1.226     brouard  5748:        else{
                   5749:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   5750:          /*  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 */
                   5751:        } 
                   5752:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   5753:        /*if(lli ==000.0)*/
1.340     brouard  5754:        /* 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  5755:        ipmx +=1;
                   5756:        sw += weight[i];
                   5757:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   5758:        /* if (lli < log(mytinydouble)){ */
                   5759:        /*   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); */
                   5760:        /*   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]); */
                   5761:        /* } */
                   5762:       } /* end of wave */
                   5763:     } /* end of individual */
                   5764:   }  else if(mle==2){
                   5765:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  5766:       ioffset=2+nagesqr ;
                   5767:       for (k=1; k<=ncovf;k++)
                   5768:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  5769:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  5770:        for(k=1; k <= ncovv ; k++){
1.341     brouard  5771:          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  5772:        }
1.226     brouard  5773:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5774:          for (j=1;j<=nlstate+ndeath;j++){
                   5775:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5776:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5777:          }
                   5778:        for(d=0; d<=dh[mi][i]; d++){
                   5779:          newm=savm;
                   5780:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5781:          cov[2]=agexact;
                   5782:          if(nagesqr==1)
                   5783:            cov[3]= agexact*agexact;
                   5784:          for (kk=1; kk<=cptcovage;kk++) {
                   5785:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   5786:          }
                   5787:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5788:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5789:          savm=oldm;
                   5790:          oldm=newm;
                   5791:        } /* end mult */
                   5792:       
                   5793:        s1=s[mw[mi][i]][i];
                   5794:        s2=s[mw[mi+1][i]][i];
                   5795:        bbh=(double)bh[mi][i]/(double)stepm; 
                   5796:        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 */
                   5797:        ipmx +=1;
                   5798:        sw += weight[i];
                   5799:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   5800:       } /* end of wave */
                   5801:     } /* end of individual */
                   5802:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   5803:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   5804:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   5805:       for(mi=1; mi<= wav[i]-1; mi++){
                   5806:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5807:          for (j=1;j<=nlstate+ndeath;j++){
                   5808:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5809:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5810:          }
                   5811:        for(d=0; d<dh[mi][i]; d++){
                   5812:          newm=savm;
                   5813:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5814:          cov[2]=agexact;
                   5815:          if(nagesqr==1)
                   5816:            cov[3]= agexact*agexact;
                   5817:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  5818:            if(!FixedV[Tvar[Tage[kk]]])
                   5819:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   5820:            else
1.341     brouard  5821:              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  5822:          }
                   5823:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5824:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5825:          savm=oldm;
                   5826:          oldm=newm;
                   5827:        } /* end mult */
                   5828:       
                   5829:        s1=s[mw[mi][i]][i];
                   5830:        s2=s[mw[mi+1][i]][i];
                   5831:        bbh=(double)bh[mi][i]/(double)stepm; 
                   5832:        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 */
                   5833:        ipmx +=1;
                   5834:        sw += weight[i];
                   5835:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   5836:       } /* end of wave */
                   5837:     } /* end of individual */
                   5838:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   5839:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   5840:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   5841:       for(mi=1; mi<= wav[i]-1; mi++){
                   5842:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5843:          for (j=1;j<=nlstate+ndeath;j++){
                   5844:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5845:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5846:          }
                   5847:        for(d=0; d<dh[mi][i]; d++){
                   5848:          newm=savm;
                   5849:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5850:          cov[2]=agexact;
                   5851:          if(nagesqr==1)
                   5852:            cov[3]= agexact*agexact;
                   5853:          for (kk=1; kk<=cptcovage;kk++) {
                   5854:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   5855:          }
1.126     brouard  5856:        
1.226     brouard  5857:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5858:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5859:          savm=oldm;
                   5860:          oldm=newm;
                   5861:        } /* end mult */
                   5862:       
                   5863:        s1=s[mw[mi][i]][i];
                   5864:        s2=s[mw[mi+1][i]][i];
                   5865:        if( s2 > nlstate){ 
                   5866:          lli=log(out[s1][s2] - savm[s1][s2]);
                   5867:        } else if  ( s2==-1 ) { /* alive */
                   5868:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   5869:            survp += out[s1][j];
                   5870:          lli= log(survp);
                   5871:        }else{
                   5872:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   5873:        }
                   5874:        ipmx +=1;
                   5875:        sw += weight[i];
                   5876:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.343     brouard  5877:        /* 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  5878:       } /* end of wave */
                   5879:     } /* end of individual */
                   5880:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   5881:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   5882:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   5883:       for(mi=1; mi<= wav[i]-1; mi++){
                   5884:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5885:          for (j=1;j<=nlstate+ndeath;j++){
                   5886:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5887:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5888:          }
                   5889:        for(d=0; d<dh[mi][i]; d++){
                   5890:          newm=savm;
                   5891:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5892:          cov[2]=agexact;
                   5893:          if(nagesqr==1)
                   5894:            cov[3]= agexact*agexact;
                   5895:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  5896:            if(!FixedV[Tvar[Tage[kk]]])
                   5897:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   5898:            else
1.341     brouard  5899:              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  5900:          }
1.126     brouard  5901:        
1.226     brouard  5902:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5903:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5904:          savm=oldm;
                   5905:          oldm=newm;
                   5906:        } /* end mult */
                   5907:       
                   5908:        s1=s[mw[mi][i]][i];
                   5909:        s2=s[mw[mi+1][i]][i];
                   5910:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   5911:        ipmx +=1;
                   5912:        sw += weight[i];
                   5913:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   5914:        /*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]);*/
                   5915:       } /* end of wave */
                   5916:     } /* end of individual */
                   5917:   } /* End of if */
                   5918:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   5919:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   5920:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   5921:   return -l;
1.126     brouard  5922: }
                   5923: 
                   5924: /*************** log-likelihood *************/
                   5925: double funcone( double *x)
                   5926: {
1.228     brouard  5927:   /* Same as func but slower because of a lot of printf and if */
1.359     brouard  5928:   int i, ii, j, k, mi, d, kv=0, kf=0;
1.228     brouard  5929:   int ioffset=0;
1.339     brouard  5930:   int ipos=0,iposold=0,ncovv=0;
                   5931: 
1.340     brouard  5932:   double cotvarv, cotvarvold;
1.131     brouard  5933:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  5934:   double **out;
                   5935:   double lli; /* Individual log likelihood */
                   5936:   double llt;
                   5937:   int s1, s2;
1.228     brouard  5938:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   5939: 
1.126     brouard  5940:   double bbh, survp;
1.187     brouard  5941:   double agexact;
1.214     brouard  5942:   double agebegin, ageend;
1.126     brouard  5943:   /*extern weight */
                   5944:   /* We are differentiating ll according to initial status */
                   5945:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   5946:   /*for(i=1;i<imx;i++) 
                   5947:     printf(" %d\n",s[4][i]);
                   5948:   */
                   5949:   cov[1]=1.;
                   5950: 
                   5951:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  5952:   ioffset=0;
                   5953:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.336     brouard  5954:     /* Computes the values of the ncovmodel covariates of the model
                   5955:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   5956:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   5957:        to be observed in j being in i according to the model.
                   5958:     */
1.243     brouard  5959:     /* ioffset=2+nagesqr+cptcovage; */
                   5960:     ioffset=2+nagesqr;
1.232     brouard  5961:     /* Fixed */
1.224     brouard  5962:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  5963:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.349     brouard  5964:     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  5965:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
                   5966:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
                   5967:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
1.335     brouard  5968:       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  5969: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   5970: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   5971: /*    cov[2+6]=covar[2][i]; V2  */
                   5972: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   5973: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   5974: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   5975: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   5976: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   5977: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  5978:     }
1.336     brouard  5979:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   5980:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   5981:         has been calculated etc */
                   5982:       /* For an individual i, wav[i] gives the number of effective waves */
                   5983:       /* We compute the contribution to Likelihood of each effective transition
                   5984:         mw[mi][i] is real wave of the mi th effectve wave */
                   5985:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   5986:         s2=s[mw[mi+1][i]][i];
1.341     brouard  5987:         And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][ncovcol+nqv+iv][i]
1.336     brouard  5988:       */
                   5989:     /* This part may be useless now because everythin should be in covar */
1.232     brouard  5990:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   5991:     /*   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?)*\/ */
                   5992:     /* } */
1.231     brouard  5993:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   5994:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   5995:     /* } */
1.225     brouard  5996:     
1.233     brouard  5997: 
                   5998:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.339     brouard  5999:       /* 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 */
                   6000:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
                   6001:       /*       /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
                   6002:       /*       cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   6003:       /* } */
                   6004:       
                   6005:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   6006:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   6007:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   6008:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
                   6009:       /* We need the position of the time varying or product in the model */
                   6010:       /* 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 */            
                   6011:       /* TvarVV gives the variable name */
1.340     brouard  6012:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   6013:       *      k=         1   2     3     4         5        6        7       8        9
                   6014:       *  varying            1     2                                 3       4        5
                   6015:       *  ncovv              1     2                                3 4     5 6      7 8
1.343     brouard  6016:       * TvarVV[ncovv]      V3     5                                1 3     3 5      1 5
1.340     brouard  6017:       * TvarVVind           2     3                                7 7     8 8      9 9
                   6018:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
                   6019:       */
1.345     brouard  6020:       /* Other model ncovcol=5 nqv=0 ntv=3 nqtv=0 nlstate=3
1.349     brouard  6021:        * 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  6022:        * FixedV[ncovcol+qv+ntv+nqtv]       V5
1.349     brouard  6023:        * 3           V1  V2     V3    V4   V5 V6     V7  V8 V3*V2 V7*V2  V6*V3 V7*V3 V6*V4 V7*V4
                   6024:        *             0   0      0      0    0  1      1   1  0, 0, 1,1,   1, 0, 1, 0, 1, 0, 1, 0}
                   6025:        * 3           0   0      0      0    0  1      1   1  0,     1      1    1      1    1}
                   6026:        * model=          V2  +  V3  +  V4  +  V6  +  V7  +  V6*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   6027:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   6028:         *                +age*V6*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   6029:        * model2=          V2  +  V3  +  V4  +  V6  +  V7  +  V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   6030:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   6031:         *                +age*V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   6032:        * model3=          V2  +  V3  +  V4  +  V6  +  V7  + age*V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   6033:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   6034:         *                +V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   6035:        * kmodel           1     2      3      4      5        6         7         8         9        10        11    
                   6036:        *                  12       13      14      15       16
                   6037:        *                    17        18         19        20         21
                   6038:        * Tvar[kmodel]     2     3      4      6      7        9        10        11        12        13        14
                   6039:        *                   2       3        4       6        7
                   6040:        *                     9         11          12        13         14            
                   6041:        * cptcovage=5+5 total of covariates with age 
                   6042:        * Tage[cptcovage] age*V2=12      13      14      15       16
                   6043:        *1                   17            18         19        20         21 gives the position in model of covariates associated with age
                   6044:        *3 Tage[cptcovage] age*V3*V2=6  
                   6045:        *3                age*V2=12         13      14      15       16
                   6046:        *3                age*V6*V3=18      19    20   21
                   6047:        * Tvar[Tage[cptcovage]]    Tvar[12]=2      3      4       6         Tvar[16]=7(age*V7)
                   6048:        *     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
                   6049:        * 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
                   6050:        * 3 Tvar[Tage[cptcovage]]    Tvar[6]=9      Tvar[12]=2      3     4       6         Tvar[16]=7(age*V7)
                   6051:        * 3     Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
                   6052:        * 3 Tage[cptcovage] age*V3*V2=6   age*V2=12 age*V3 13    14      15       16
                   6053:        *                    age*V6*V3=18         19        20         21 gives the position in model of covariates associated with age
                   6054:        * 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
                   6055:        * Tvar=                {2, 3, 4, 6, 7,
                   6056:        *                       9, 10, 11, 12, 13, 14,
                   6057:        *              Tvar[12]=2, 3, 4, 6, 7,
                   6058:        *              Tvar[17]=9, 11, 12, 13, 14}
                   6059:        * Typevar[1]@21 = {0, 0, 0, 0, 0,
                   6060:        *                  2, 2, 2, 2, 2, 2,
                   6061:        * 3                3, 2, 2, 2, 2, 2,
                   6062:        *                  1, 1, 1, 1, 1, 
                   6063:        *                  3, 3, 3, 3, 3}
                   6064:        * 3                 2, 3, 3, 3, 3}
                   6065:        * 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
                   6066:        * p Tprod[1]@21 {6, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   6067:        * 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}
                   6068:        * 3 Tprod[1]@21 {17, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   6069:        * cptcovprod=11 (6+5)
                   6070:        * FixedV[Tvar[Tage[cptcovage]]]]  FixedV[2]=0      FixedV[3]=0      0      1          (age*V7)Tvar[16]=1 FixedV[absolute] not [kmodel]
                   6071:        *   FixedV[Tvar[17]=FixedV[age*V6*V2]=FixedV[9]=1        1         1          1         1  
                   6072:        * 3 FixedV[Tvar[17]=FixedV[age*V3*V2]=FixedV[9]=0        [11]=1         1          1         1  
                   6073:        * FixedV[]          V1=0     V2=0   V3=0  v4=0    V5=0  V6=1    V7=1 v8=1  OK then model dependent
                   6074:        *                   9=1  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   6075:        * 3                 9=0  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   6076:        * cptcovdageprod=5  for gnuplot printing
                   6077:        * cptcovprodvage=6 
                   6078:        * ncova=15           1        2       3       4       5
                   6079:        *                      6 7        8 9      10 11        12 13     14 15
                   6080:        * TvarA              2        3       4       6       7
                   6081:        *                      6 2        6 7       7 3          6 4       7 4
                   6082:        * TvaAind             12 12      13 13     14 14      15 15       16 16        
1.345     brouard  6083:        * ncovf            1     2      3
1.349     brouard  6084:        *                                    V6       V7      V6*V2     V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   6085:        * ncovvt=14                            1      2        3 4       5 6       7 8       9 10     11 12     13 14     
                   6086:        * TvarVV[1]@14 = itv               {V6=6,     7, V6*V2=6, 2,     7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   6087:        * TvarVVind[1]@14=                    {4,     5,       6, 6,     7, 7,     8, 8,      9, 9,   10, 10,   11, 11}
                   6088:        * 3 ncovvt=12                        V6       V7      V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   6089:        * 3 TvarVV[1]@12 = itv                {6,     7, V7*V2=7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   6090:        * 3                                    1      2        3  4      5  6      7  8      9 10     11 12
                   6091:        * TvarVVind[1]@12=         {V6 is in k=4,     5,  7,(4isV2)=7,   8, 8,      9, 9,   10,10,    11,11}TvarVVind[12]=k=11
                   6092:        * TvarV              6, 7, 9, 10, 11, 12, 13, 14
                   6093:        * 3 cptcovprodvage=6
                   6094:        * 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
                   6095:        * 3 TvarAVVA[1]@15= itva 3 2    2      3    4        6       7        6 3         7 3         6 4         7 4 
                   6096:        * 3 ncovta             1 2      3      4    5        6       7        8 9       10 11       12 13        14 15
1.354     brouard  6097:        *?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  6098:        * TvarAVVAind[1]@15= V3 is in k=6 6 12  13   14      15      16       18 18       19,19,     20,20        21,21}TvarVVAind[]
                   6099:        * 3 ncovvta=10     +age*V6 + age*V7 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   6100:        * 3 we want to compute =cotvar[mw[mi][i]][TvarVVA[ncovva]][i] at position TvarVVAind[ncovva]
                   6101:        * 3 TvarVVA[1]@10= itva   6       7        6 3         7 3         6 4         7 4 
                   6102:        * 3 ncovva                1       2        3 4         5 6         7 8         9 10
                   6103:        * TvarVVAind[1]@10= V6 is in k=4  5        8,8         9, 9,      10,10        11 11}TvarVVAind[]
                   6104:        * TvarVVAind[1]@10=       15       16     18,18        19,19,      20,20        21 21}TvarVVAind[]
                   6105:        * TvarVA              V3*V2=6 6 , 1, 2, 11, 12, 13, 14
1.345     brouard  6106:        * TvarFind[1]@14= {1,    2,     3,     0 <repeats 12 times>}
1.349     brouard  6107:        * Tvar[1]@21=     {2,    3,     4,    6,      7,      9,      10,        11,       12,      13,       14,
                   6108:        *                   2, 3, 4, 6, 7,
                   6109:        *                     6, 8, 9, 10, 11}
1.345     brouard  6110:        * TvarFind[itv]                        0      0       0
                   6111:        * FixedV[itv]                          1      1       1  0      1 0       1 0       1 0       0
1.354     brouard  6112:        *? FixedV[itv]                          1      1       1  0      1 0       1 0       1 0      1 0     1 0
1.345     brouard  6113:        * Tvar[TvarFind[ncovf]]=[1]=2 [2]=3 [4]=4
                   6114:        * Tvar[TvarFind[itv]]                [0]=?      ?ncovv 1 à ncovvt]
                   6115:        *   Not a fixed cotvar[mw][itv][i]     6       7      6  2      7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
1.349     brouard  6116:        *   fixed covar[itv]                  [6]     [7]    [6][2] 
1.345     brouard  6117:        */
                   6118: 
1.349     brouard  6119:       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 */
                   6120:        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  6121:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  6122:        /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   6123:        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  6124:          /* printf("DEBUG ncovv=%d, Varying TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
1.345     brouard  6125:          cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
1.354     brouard  6126:          /* printf("DEBUG Varying cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
1.340     brouard  6127:        }else{ /* fixed covariate */
1.345     brouard  6128:          /* 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  6129:          /* printf("DEBUG ncovv=%d, Fixed TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
1.349     brouard  6130:          cotvarv=covar[itv][i];  /* Good: In V6*V3, 3 is fixed at position of the data */
1.354     brouard  6131:          /* printf("DEBUG Fixed cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
1.340     brouard  6132:        }
1.339     brouard  6133:        if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  6134:          cotvarvold=cotvarv;
                   6135:        }else{ /* A second product */
                   6136:          cotvarv=cotvarv*cotvarvold;
1.339     brouard  6137:        }
                   6138:        iposold=ipos;
1.340     brouard  6139:        cov[ioffset+ipos]=cotvarv;
1.354     brouard  6140:        /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
1.339     brouard  6141:        /* For products */
                   6142:       }
                   6143:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
                   6144:       /*       iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
                   6145:       /*       /\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
                   6146:       /*       /\*           1  2   3      4      5                         *\/ */
                   6147:       /*       /\*itv           1                                           *\/ */
                   6148:       /*       /\* TvarVInd[1]= 2                                           *\/ */
                   6149:       /*       /\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
                   6150:       /*       /\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
                   6151:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
                   6152:       /*       /\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
                   6153:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
                   6154:       /*       cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
                   6155:       /*       /\* 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]); *\/ */
                   6156:       /* } */
1.232     brouard  6157:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  6158:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   6159:       /*       /\* 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]); *\/ */
                   6160:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  6161:       /* } */
1.126     brouard  6162:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  6163:        for (j=1;j<=nlstate+ndeath;j++){
                   6164:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   6165:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   6166:        }
1.214     brouard  6167:       
                   6168:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   6169:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   6170:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  6171:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  6172:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   6173:          and mw[mi+1][i]. dh depends on stepm.*/
                   6174:        newm=savm;
1.247     brouard  6175:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  6176:        cov[2]=agexact;
                   6177:        if(nagesqr==1)
                   6178:          cov[3]= agexact*agexact;
1.349     brouard  6179:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   6180:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   6181:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   6182:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   6183:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   6184:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   6185:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   6186:          }else{ /* fixed covariate */
                   6187:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   6188:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   6189:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   6190:          }
                   6191:          if(ipos!=iposold){ /* Not a product or first of a product */
                   6192:            cotvarvold=cotvarv;
                   6193:          }else{ /* A second product */
                   6194:            /* printf("DEBUG * \n"); */
                   6195:            cotvarv=cotvarv*cotvarvold;
                   6196:          }
                   6197:          iposold=ipos;
                   6198:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   6199:          cov[ioffset+ipos]=cotvarv*agexact;
                   6200:          /* For products */
1.242     brouard  6201:        }
1.349     brouard  6202: 
1.242     brouard  6203:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   6204:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   6205:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   6206:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   6207:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   6208:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   6209:        savm=oldm;
                   6210:        oldm=newm;
1.126     brouard  6211:       } /* end mult */
1.336     brouard  6212:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   6213:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   6214:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   6215:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   6216:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   6217:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   6218:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   6219:         * probability in order to take into account the bias as a fraction of the way
                   6220:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   6221:                                 * -stepm/2 to stepm/2 .
                   6222:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   6223:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   6224:                                 */
1.126     brouard  6225:       s1=s[mw[mi][i]][i];
                   6226:       s2=s[mw[mi+1][i]][i];
1.217     brouard  6227:       /* if(s2==-1){ */
1.268     brouard  6228:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  6229:       /*       /\* exit(1); *\/ */
                   6230:       /* } */
1.126     brouard  6231:       bbh=(double)bh[mi][i]/(double)stepm; 
                   6232:       /* bias is positive if real duration
                   6233:        * is higher than the multiple of stepm and negative otherwise.
                   6234:        */
                   6235:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  6236:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  6237:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  6238:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   6239:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   6240:        lli= log(survp);
1.126     brouard  6241:       }else if (mle==1){
1.242     brouard  6242:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  6243:       } else if(mle==2){
1.242     brouard  6244:        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  6245:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  6246:        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  6247:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  6248:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  6249:       } else{  /* mle=0 back to 1 */
1.242     brouard  6250:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   6251:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  6252:       } /* End of if */
                   6253:       ipmx +=1;
                   6254:       sw += weight[i];
                   6255:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.342     brouard  6256:       /* Printing covariates values for each contribution for checking */
1.343     brouard  6257:       /* 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  6258:       if(globpr){
1.246     brouard  6259:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  6260:  %11.6f %11.6f %11.6f ", \
1.242     brouard  6261:                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  6262:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.343     brouard  6263:        /*      printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
                   6264:        /* %11.6f %11.6f %11.6f ", \ */
                   6265:        /*              num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   6266:        /*              2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  6267:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   6268:          llt +=ll[k]*gipmx/gsw;
                   6269:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335     brouard  6270:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  6271:        }
1.343     brouard  6272:        fprintf(ficresilk," %10.6f ", -llt);
1.335     brouard  6273:        /* printf(" %10.6f\n", -llt); */
1.342     brouard  6274:        /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
1.343     brouard  6275:        /* fprintf(ficresilk,"%09ld ", num[i]); */ /* not necessary */
                   6276:        for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
                   6277:          fprintf(ficresilk," %g",covar[Tvar[TvarFind[kf]]][i]);
                   6278:        }
                   6279:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
                   6280:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   6281:          if(ipos!=iposold){ /* Not a product or first of a product */
                   6282:            fprintf(ficresilk," %g",cov[ioffset+ipos]);
                   6283:            /* printf(" %g",cov[ioffset+ipos]); */
                   6284:          }else{
                   6285:            fprintf(ficresilk,"*");
                   6286:            /* printf("*"); */
1.342     brouard  6287:          }
1.343     brouard  6288:          iposold=ipos;
                   6289:        }
1.349     brouard  6290:        /* for (kk=1; kk<=cptcovage;kk++) { */
                   6291:        /*   if(!FixedV[Tvar[Tage[kk]]]){ */
                   6292:        /*     fprintf(ficresilk," %g*age",covar[Tvar[Tage[kk]]][i]); */
                   6293:        /*     /\* printf(" %g*age",covar[Tvar[Tage[kk]]][i]); *\/ */
                   6294:        /*   }else{ */
                   6295:        /*     fprintf(ficresilk," %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   6296:        /*     /\* printf(" %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\\/  *\/ */
                   6297:        /*   } */
                   6298:        /* } */
                   6299:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   6300:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   6301:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   6302:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   6303:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   6304:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   6305:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   6306:          }else{ /* fixed covariate */
                   6307:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   6308:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   6309:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   6310:          }
                   6311:          if(ipos!=iposold){ /* Not a product or first of a product */
                   6312:            cotvarvold=cotvarv;
                   6313:          }else{ /* A second product */
                   6314:            /* printf("DEBUG * \n"); */
                   6315:            cotvarv=cotvarv*cotvarvold;
1.342     brouard  6316:          }
1.349     brouard  6317:          cotvarv=cotvarv*agexact;
                   6318:          fprintf(ficresilk," %g*age",cotvarv);
                   6319:          iposold=ipos;
                   6320:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   6321:          cov[ioffset+ipos]=cotvarv;
                   6322:          /* For products */
1.343     brouard  6323:        }
                   6324:        /* printf("\n"); */
1.342     brouard  6325:        /* } /\*  End debugILK *\/ */
                   6326:        fprintf(ficresilk,"\n");
                   6327:       } /* End if globpr */
1.335     brouard  6328:     } /* end of wave */
                   6329:   } /* end of individual */
                   6330:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  6331: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335     brouard  6332:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   6333:   if(globpr==0){ /* First time we count the contributions and weights */
                   6334:     gipmx=ipmx;
                   6335:     gsw=sw;
                   6336:   }
1.343     brouard  6337:   return -l;
1.126     brouard  6338: }
                   6339: 
                   6340: 
                   6341: /*************** function likelione ***********/
1.292     brouard  6342: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  6343: {
                   6344:   /* This routine should help understanding what is done with 
                   6345:      the selection of individuals/waves and
                   6346:      to check the exact contribution to the likelihood.
                   6347:      Plotting could be done.
1.342     brouard  6348:   */
                   6349:   void pstamp(FILE *ficres);
1.343     brouard  6350:   int k, kf, kk, kvar, ncovv, iposold, ipos;
1.126     brouard  6351: 
                   6352:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  6353:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  6354:     strcat(fileresilk,fileresu);
1.126     brouard  6355:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   6356:       printf("Problem with resultfile: %s\n", fileresilk);
                   6357:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   6358:     }
1.342     brouard  6359:     pstamp(ficresilk);fprintf(ficresilk,"# model=1+age+%s\n",model);
1.214     brouard  6360:     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");
                   6361:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  6362:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   6363:     for(k=1; k<=nlstate; k++) 
                   6364:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
1.342     brouard  6365:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total) ");
                   6366: 
                   6367:     /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
                   6368:       for(kf=1;kf <= ncovf; kf++){
                   6369:        fprintf(ficresilk,"V%d",Tvar[TvarFind[kf]]);
                   6370:        /* printf("V%d",Tvar[TvarFind[kf]]); */
                   6371:       }
                   6372:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){
1.343     brouard  6373:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
1.342     brouard  6374:        if(ipos!=iposold){ /* Not a product or first of a product */
                   6375:          /* printf(" %d",ipos); */
                   6376:          fprintf(ficresilk," V%d",TvarVV[ncovv]);
                   6377:        }else{
                   6378:          /* printf("*"); */
                   6379:          fprintf(ficresilk,"*");
1.343     brouard  6380:        }
1.342     brouard  6381:        iposold=ipos;
                   6382:       }
                   6383:       for (kk=1; kk<=cptcovage;kk++) {
                   6384:        if(!FixedV[Tvar[Tage[kk]]]){
                   6385:          /* printf(" %d*age(Fixed)",Tvar[Tage[kk]]); */
                   6386:          fprintf(ficresilk," %d*age(Fixed)",Tvar[Tage[kk]]);
                   6387:        }else{
                   6388:          fprintf(ficresilk," %d*age(Varying)",Tvar[Tage[kk]]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   6389:          /* printf(" %d*age(Varying)",Tvar[Tage[kk]]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   6390:        }
                   6391:       }
                   6392:     /* } /\* End if debugILK *\/ */
                   6393:     /* printf("\n"); */
                   6394:     fprintf(ficresilk,"\n");
                   6395:   } /* End glogpri */
1.126     brouard  6396: 
1.292     brouard  6397:   *fretone=(*func)(p);
1.126     brouard  6398:   if(*globpri !=0){
                   6399:     fclose(ficresilk);
1.205     brouard  6400:     if (mle ==0)
                   6401:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   6402:     else if(mle >=1)
                   6403:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   6404:     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  6405:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  6406:       
1.207     brouard  6407:     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  6408: <img src=\"%s-ori.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  6409:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.343     brouard  6410: <img src=\"%s-dest.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
                   6411:     
                   6412:     for (k=1; k<= nlstate ; k++) {
                   6413:       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 \
                   6414: <img src=\"%s-p%dj.png\">\n",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   6415:       for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.350     brouard  6416:         kvar=Tvar[TvarFind[kf]];  /* variable */
                   6417:         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]]);
                   6418:         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);
                   6419:         fprintf(fichtm,"<img src=\"%s-p%dj-%d.png\">",subdirf2(optionfilefiname,"ILK_"),k,Tvar[TvarFind[kf]]);
1.343     brouard  6420:       }
                   6421:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Loop on the time varying extended covariates (with extension of Vn*Vm */
                   6422:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   6423:        kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   6424:        /* 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]); */
                   6425:        if(ipos!=iposold){ /* Not a product or first of a product */
                   6426:          /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   6427:          /* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); */
                   6428:          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)  */
                   6429:            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> \
                   6430: <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);
                   6431:          } /* End only for dummies time varying (single?) */
                   6432:        }else{ /* Useless product */
                   6433:          /* printf("*"); */
                   6434:          /* fprintf(ficresilk,"*"); */ 
                   6435:        }
                   6436:        iposold=ipos;
                   6437:       } /* For each time varying covariate */
                   6438:     } /* End loop on states */
                   6439: 
                   6440: /*     if(debugILK){ */
                   6441: /*       for(kf=1; kf <= ncovf; kf++){ /\* For each simple dummy covariate of the model *\/ */
                   6442: /*     /\* kvar=Tvar[TvarFind[kf]]; *\/ /\* variable *\/ */
                   6443: /*     for (k=1; k<= nlstate ; k++) { */
                   6444: /*       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> \ */
                   6445: /* <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]]); */
                   6446: /*     } */
                   6447: /*       } */
                   6448: /*       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /\* Loop on the time varying extended covariates (with extension of Vn*Vm *\/ */
                   6449: /*     ipos=TvarVVind[ncovv]; /\* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate *\/ */
                   6450: /*     kvar=TvarVV[ncovv]; /\*  TvarVV={3, 1, 3} gives the name of each varying covariate *\/ */
                   6451: /*     /\* 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]); *\/ */
                   6452: /*     if(ipos!=iposold){ /\* Not a product or first of a product *\/ */
                   6453: /*       /\* fprintf(ficresilk," V%d",TvarVV[ncovv]); *\/ */
                   6454: /*       /\* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); *\/ */
                   6455: /*       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)  *\/ */
                   6456: /*         for (k=1; k<= nlstate ; k++) { */
                   6457: /*           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> \ */
                   6458: /* <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar); */
                   6459: /*         } /\* End state *\/ */
                   6460: /*       } /\* End only for dummies time varying (single?) *\/ */
                   6461: /*     }else{ /\* Useless product *\/ */
                   6462: /*       /\* printf("*"); *\/ */
                   6463: /*       /\* fprintf(ficresilk,"*"); *\/  */
                   6464: /*     } */
                   6465: /*     iposold=ipos; */
                   6466: /*       } /\* For each time varying covariate *\/ */
                   6467: /*     }/\* End debugILK *\/ */
1.207     brouard  6468:     fflush(fichtm);
1.343     brouard  6469:   }/* End globpri */
1.126     brouard  6470:   return;
                   6471: }
                   6472: 
                   6473: 
                   6474: /*********** Maximum Likelihood Estimation ***************/
                   6475: 
                   6476: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   6477: {
1.359     brouard  6478:   int i,j,  jkk=0, iter=0;
1.126     brouard  6479:   double **xi;
1.359     brouard  6480:   /*double fret;*/
                   6481:   /*double fretone;*/ /* Only one call to likelihood */
1.126     brouard  6482:   /*  char filerespow[FILENAMELENGTH];*/
1.354     brouard  6483:   
1.359     brouard  6484:   /*double * p1;*/ /* Shifted parameters from 0 instead of 1 */
1.162     brouard  6485: #ifdef NLOPT
                   6486:   int creturn;
                   6487:   nlopt_opt opt;
                   6488:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   6489:   double *lb;
                   6490:   double minf; /* the minimum objective value, upon return */
1.354     brouard  6491: 
1.162     brouard  6492:   myfunc_data dinst, *d = &dinst;
                   6493: #endif
                   6494: 
                   6495: 
1.126     brouard  6496:   xi=matrix(1,npar,1,npar);
1.357     brouard  6497:   for (i=1;i<=npar;i++)  /* Starting with canonical directions j=1,n xi[i=1,n][j] */
1.126     brouard  6498:     for (j=1;j<=npar;j++)
                   6499:       xi[i][j]=(i==j ? 1.0 : 0.0);
1.359     brouard  6500:   printf("Powell-prax\n");  fprintf(ficlog,"Powell-prax\n");
1.201     brouard  6501:   strcpy(filerespow,"POW_"); 
1.126     brouard  6502:   strcat(filerespow,fileres);
                   6503:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   6504:     printf("Problem with resultfile: %s\n", filerespow);
                   6505:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   6506:   }
                   6507:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   6508:   for (i=1;i<=nlstate;i++)
                   6509:     for(j=1;j<=nlstate+ndeath;j++)
                   6510:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   6511:   fprintf(ficrespow,"\n");
1.162     brouard  6512: #ifdef POWELL
1.319     brouard  6513: #ifdef LINMINORIGINAL
                   6514: #else /* LINMINORIGINAL */
                   6515:   
                   6516:   flatdir=ivector(1,npar); 
                   6517:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   6518: #endif /*LINMINORIGINAL */
                   6519: 
                   6520: #ifdef FLATSUP
                   6521:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   6522:   /* reorganizing p by suppressing flat directions */
                   6523:   for(i=1, jk=1; i <=nlstate; i++){
                   6524:     for(k=1; k <=(nlstate+ndeath); k++){
                   6525:       if (k != i) {
                   6526:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   6527:         if(flatdir[jk]==1){
                   6528:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   6529:         }
                   6530:         for(j=1; j <=ncovmodel; j++){
                   6531:           printf("%12.7f ",p[jk]);
                   6532:           jk++; 
                   6533:         }
                   6534:         printf("\n");
                   6535:       }
                   6536:     }
                   6537:   }
                   6538: /* skipping */
                   6539:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   6540:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   6541:     for(k=1; k <=(nlstate+ndeath); k++){
                   6542:       if (k != i) {
                   6543:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   6544:         if(flatdir[jk]==1){
                   6545:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   6546:           for(j=1; j <=ncovmodel;  jk++,j++){
                   6547:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   6548:             /*q[jjk]=p[jk];*/
                   6549:           }
                   6550:         }else{
                   6551:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   6552:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   6553:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   6554:             /*q[jjk]=p[jk];*/
                   6555:           }
                   6556:         }
                   6557:         printf("\n");
                   6558:       }
                   6559:       fflush(stdout);
                   6560:     }
                   6561:   }
                   6562:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   6563: #else  /* FLATSUP */
1.359     brouard  6564: /*  powell(p,xi,npar,ftol,&iter,&fret,func);*/
                   6565: /*   praxis ( t0, h0, n, prin, x, beale_f ); */
                   6566:   int prin=1;
                   6567:   double h0=0.25;
                   6568:   double macheps;
                   6569:   double fmin;
                   6570:   macheps=pow(16.0,-13.0);
                   6571: /* #include "praxis.h" */
                   6572:   /* Be careful that praxis start at x[0] and powell start at p[1] */
                   6573:    /* praxis ( ftol, h0, npar, prin, p, func ); */
                   6574: /* p1= (p+1); */ /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   6575: printf("Praxis Gegenfurtner \n");
                   6576: fprintf(ficlog, "Praxis  Gegenfurtner\n");fflush(ficlog);
                   6577: /* praxis ( ftol, h0, npar, prin, p1, func ); */
                   6578:   /* fmin = praxis(1.e-5,macheps, h, n, prin, x, func); */
                   6579:   fmin = praxis(ftol,macheps, h0, npar, prin, p, func);
                   6580: printf("End Praxis\n");
1.319     brouard  6581: #endif  /* FLATSUP */
                   6582: 
                   6583: #ifdef LINMINORIGINAL
                   6584: #else
                   6585:       free_ivector(flatdir,1,npar); 
                   6586: #endif  /* LINMINORIGINAL*/
                   6587: #endif /* POWELL */
1.126     brouard  6588: 
1.162     brouard  6589: #ifdef NLOPT
                   6590: #ifdef NEWUOA
                   6591:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   6592: #else
                   6593:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   6594: #endif
                   6595:   lb=vector(0,npar-1);
                   6596:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   6597:   nlopt_set_lower_bounds(opt, lb);
                   6598:   nlopt_set_initial_step1(opt, 0.1);
                   6599:   
                   6600:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   6601:   d->function = func;
                   6602:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   6603:   nlopt_set_min_objective(opt, myfunc, d);
                   6604:   nlopt_set_xtol_rel(opt, ftol);
                   6605:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   6606:     printf("nlopt failed! %d\n",creturn); 
                   6607:   }
                   6608:   else {
                   6609:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   6610:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   6611:     iter=1; /* not equal */
                   6612:   }
                   6613:   nlopt_destroy(opt);
                   6614: #endif
1.319     brouard  6615: #ifdef FLATSUP
                   6616:   /* npared = npar -flatd/ncovmodel; */
                   6617:   /* xired= matrix(1,npared,1,npared); */
                   6618:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   6619:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   6620:   /* free_matrix(xire,1,npared,1,npared); */
                   6621: #else  /* FLATSUP */
                   6622: #endif /* FLATSUP */
1.126     brouard  6623:   free_matrix(xi,1,npar,1,npar);
                   6624:   fclose(ficrespow);
1.203     brouard  6625:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   6626:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  6627:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  6628: 
                   6629: }
                   6630: 
                   6631: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  6632: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  6633: {
                   6634:   double  **a,**y,*x,pd;
1.203     brouard  6635:   /* double **hess; */
1.164     brouard  6636:   int i, j;
1.126     brouard  6637:   int *indx;
                   6638: 
                   6639:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  6640:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  6641:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   6642:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   6643:   double gompertz(double p[]);
1.203     brouard  6644:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  6645: 
                   6646:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   6647:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   6648:   for (i=1;i<=npar;i++){
1.203     brouard  6649:     printf("%d-",i);fflush(stdout);
                   6650:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  6651:    
                   6652:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   6653:     
                   6654:     /*  printf(" %f ",p[i]);
                   6655:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   6656:   }
                   6657:   
                   6658:   for (i=1;i<=npar;i++) {
                   6659:     for (j=1;j<=npar;j++)  {
                   6660:       if (j>i) { 
1.203     brouard  6661:        printf(".%d-%d",i,j);fflush(stdout);
                   6662:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   6663:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  6664:        
                   6665:        hess[j][i]=hess[i][j];    
                   6666:        /*printf(" %lf ",hess[i][j]);*/
                   6667:       }
                   6668:     }
                   6669:   }
                   6670:   printf("\n");
                   6671:   fprintf(ficlog,"\n");
                   6672: 
                   6673:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   6674:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   6675:   
                   6676:   a=matrix(1,npar,1,npar);
                   6677:   y=matrix(1,npar,1,npar);
                   6678:   x=vector(1,npar);
                   6679:   indx=ivector(1,npar);
                   6680:   for (i=1;i<=npar;i++)
                   6681:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   6682:   ludcmp(a,npar,indx,&pd);
                   6683: 
                   6684:   for (j=1;j<=npar;j++) {
                   6685:     for (i=1;i<=npar;i++) x[i]=0;
                   6686:     x[j]=1;
                   6687:     lubksb(a,npar,indx,x);
                   6688:     for (i=1;i<=npar;i++){ 
                   6689:       matcov[i][j]=x[i];
                   6690:     }
                   6691:   }
                   6692: 
                   6693:   printf("\n#Hessian matrix#\n");
                   6694:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   6695:   for (i=1;i<=npar;i++) { 
                   6696:     for (j=1;j<=npar;j++) { 
1.203     brouard  6697:       printf("%.6e ",hess[i][j]);
                   6698:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  6699:     }
                   6700:     printf("\n");
                   6701:     fprintf(ficlog,"\n");
                   6702:   }
                   6703: 
1.203     brouard  6704:   /* printf("\n#Covariance matrix#\n"); */
                   6705:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   6706:   /* for (i=1;i<=npar;i++) {  */
                   6707:   /*   for (j=1;j<=npar;j++) {  */
                   6708:   /*     printf("%.6e ",matcov[i][j]); */
                   6709:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   6710:   /*   } */
                   6711:   /*   printf("\n"); */
                   6712:   /*   fprintf(ficlog,"\n"); */
                   6713:   /* } */
                   6714: 
1.126     brouard  6715:   /* Recompute Inverse */
1.203     brouard  6716:   /* for (i=1;i<=npar;i++) */
                   6717:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   6718:   /* ludcmp(a,npar,indx,&pd); */
                   6719: 
                   6720:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   6721: 
                   6722:   /* for (j=1;j<=npar;j++) { */
                   6723:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   6724:   /*   x[j]=1; */
                   6725:   /*   lubksb(a,npar,indx,x); */
                   6726:   /*   for (i=1;i<=npar;i++){  */
                   6727:   /*     y[i][j]=x[i]; */
                   6728:   /*     printf("%.3e ",y[i][j]); */
                   6729:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   6730:   /*   } */
                   6731:   /*   printf("\n"); */
                   6732:   /*   fprintf(ficlog,"\n"); */
                   6733:   /* } */
                   6734: 
                   6735:   /* Verifying the inverse matrix */
                   6736: #ifdef DEBUGHESS
                   6737:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  6738: 
1.203     brouard  6739:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   6740:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  6741: 
                   6742:   for (j=1;j<=npar;j++) {
                   6743:     for (i=1;i<=npar;i++){ 
1.203     brouard  6744:       printf("%.2f ",y[i][j]);
                   6745:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  6746:     }
                   6747:     printf("\n");
                   6748:     fprintf(ficlog,"\n");
                   6749:   }
1.203     brouard  6750: #endif
1.126     brouard  6751: 
                   6752:   free_matrix(a,1,npar,1,npar);
                   6753:   free_matrix(y,1,npar,1,npar);
                   6754:   free_vector(x,1,npar);
                   6755:   free_ivector(indx,1,npar);
1.203     brouard  6756:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  6757: 
                   6758: 
                   6759: }
                   6760: 
                   6761: /*************** hessian matrix ****************/
                   6762: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  6763: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  6764:   int i;
                   6765:   int l=1, lmax=20;
1.203     brouard  6766:   double k1,k2, res, fx;
1.132     brouard  6767:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  6768:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   6769:   int k=0,kmax=10;
                   6770:   double l1;
                   6771: 
                   6772:   fx=func(x);
                   6773:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  6774:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  6775:     l1=pow(10,l);
                   6776:     delts=delt;
                   6777:     for(k=1 ; k <kmax; k=k+1){
                   6778:       delt = delta*(l1*k);
                   6779:       p2[theta]=x[theta] +delt;
1.145     brouard  6780:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  6781:       p2[theta]=x[theta]-delt;
                   6782:       k2=func(p2)-fx;
                   6783:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  6784:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  6785:       
1.203     brouard  6786: #ifdef DEBUGHESSII
1.126     brouard  6787:       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);
                   6788:       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);
                   6789: #endif
                   6790:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   6791:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   6792:        k=kmax;
                   6793:       }
                   6794:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  6795:        k=kmax; l=lmax*10;
1.126     brouard  6796:       }
                   6797:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   6798:        delts=delt;
                   6799:       }
1.203     brouard  6800:     } /* End loop k */
1.126     brouard  6801:   }
                   6802:   delti[theta]=delts;
                   6803:   return res; 
                   6804:   
                   6805: }
                   6806: 
1.203     brouard  6807: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  6808: {
                   6809:   int i;
1.164     brouard  6810:   int l=1, lmax=20;
1.126     brouard  6811:   double k1,k2,k3,k4,res,fx;
1.132     brouard  6812:   double p2[MAXPARM+1];
1.203     brouard  6813:   int k, kmax=1;
                   6814:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  6815: 
                   6816:   int firstime=0;
1.203     brouard  6817:   
1.126     brouard  6818:   fx=func(x);
1.203     brouard  6819:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  6820:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  6821:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   6822:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  6823:     k1=func(p2)-fx;
                   6824:   
1.203     brouard  6825:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   6826:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  6827:     k2=func(p2)-fx;
                   6828:   
1.203     brouard  6829:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   6830:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  6831:     k3=func(p2)-fx;
                   6832:   
1.203     brouard  6833:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   6834:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  6835:     k4=func(p2)-fx;
1.203     brouard  6836:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   6837:     if(k1*k2*k3*k4 <0.){
1.208     brouard  6838:       firstime=1;
1.203     brouard  6839:       kmax=kmax+10;
1.208     brouard  6840:     }
                   6841:     if(kmax >=10 || firstime ==1){
1.354     brouard  6842:       /* What are the thetai and thetaj? thetai/ncovmodel thetai=(thetai-thetai%ncovmodel)/ncovmodel +thetai%ncovmodel=(line,pos)  */
1.246     brouard  6843:       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);
                   6844:       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  6845:       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);
                   6846:       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);
                   6847:     }
                   6848: #ifdef DEBUGHESSIJ
                   6849:     v1=hess[thetai][thetai];
                   6850:     v2=hess[thetaj][thetaj];
                   6851:     cv12=res;
                   6852:     /* Computing eigen value of Hessian matrix */
                   6853:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6854:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6855:     if ((lc2 <0) || (lc1 <0) ){
                   6856:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   6857:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   6858:       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);
                   6859:       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);
                   6860:     }
1.126     brouard  6861: #endif
                   6862:   }
                   6863:   return res;
                   6864: }
                   6865: 
1.203     brouard  6866:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   6867: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   6868: /* { */
                   6869: /*   int i; */
                   6870: /*   int l=1, lmax=20; */
                   6871: /*   double k1,k2,k3,k4,res,fx; */
                   6872: /*   double p2[MAXPARM+1]; */
                   6873: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   6874: /*   int k=0,kmax=10; */
                   6875: /*   double l1; */
                   6876:   
                   6877: /*   fx=func(x); */
                   6878: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   6879: /*     l1=pow(10,l); */
                   6880: /*     delts=delt; */
                   6881: /*     for(k=1 ; k <kmax; k=k+1){ */
                   6882: /*       delt = delti*(l1*k); */
                   6883: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   6884: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   6885: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   6886: /*       k1=func(p2)-fx; */
                   6887:       
                   6888: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   6889: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   6890: /*       k2=func(p2)-fx; */
                   6891:       
                   6892: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   6893: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   6894: /*       k3=func(p2)-fx; */
                   6895:       
                   6896: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   6897: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   6898: /*       k4=func(p2)-fx; */
                   6899: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   6900: /* #ifdef DEBUGHESSIJ */
                   6901: /*       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); */
                   6902: /*       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); */
                   6903: /* #endif */
                   6904: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   6905: /*     k=kmax; */
                   6906: /*       } */
                   6907: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   6908: /*     k=kmax; l=lmax*10; */
                   6909: /*       } */
                   6910: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   6911: /*     delts=delt; */
                   6912: /*       } */
                   6913: /*     } /\* End loop k *\/ */
                   6914: /*   } */
                   6915: /*   delti[theta]=delts; */
                   6916: /*   return res;  */
                   6917: /* } */
                   6918: 
                   6919: 
1.126     brouard  6920: /************** Inverse of matrix **************/
                   6921: void ludcmp(double **a, int n, int *indx, double *d) 
                   6922: { 
                   6923:   int i,imax,j,k; 
                   6924:   double big,dum,sum,temp; 
                   6925:   double *vv; 
                   6926:  
                   6927:   vv=vector(1,n); 
                   6928:   *d=1.0; 
                   6929:   for (i=1;i<=n;i++) { 
                   6930:     big=0.0; 
                   6931:     for (j=1;j<=n;j++) 
                   6932:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  6933:     if (big == 0.0){
                   6934:       printf(" Singular Hessian matrix at row %d:\n",i);
                   6935:       for (j=1;j<=n;j++) {
                   6936:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   6937:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   6938:       }
                   6939:       fflush(ficlog);
                   6940:       fclose(ficlog);
                   6941:       nrerror("Singular matrix in routine ludcmp"); 
                   6942:     }
1.126     brouard  6943:     vv[i]=1.0/big; 
                   6944:   } 
                   6945:   for (j=1;j<=n;j++) { 
                   6946:     for (i=1;i<j;i++) { 
                   6947:       sum=a[i][j]; 
                   6948:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   6949:       a[i][j]=sum; 
                   6950:     } 
                   6951:     big=0.0; 
                   6952:     for (i=j;i<=n;i++) { 
                   6953:       sum=a[i][j]; 
                   6954:       for (k=1;k<j;k++) 
                   6955:        sum -= a[i][k]*a[k][j]; 
                   6956:       a[i][j]=sum; 
                   6957:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   6958:        big=dum; 
                   6959:        imax=i; 
                   6960:       } 
                   6961:     } 
                   6962:     if (j != imax) { 
                   6963:       for (k=1;k<=n;k++) { 
                   6964:        dum=a[imax][k]; 
                   6965:        a[imax][k]=a[j][k]; 
                   6966:        a[j][k]=dum; 
                   6967:       } 
                   6968:       *d = -(*d); 
                   6969:       vv[imax]=vv[j]; 
                   6970:     } 
                   6971:     indx[j]=imax; 
                   6972:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   6973:     if (j != n) { 
                   6974:       dum=1.0/(a[j][j]); 
                   6975:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   6976:     } 
                   6977:   } 
                   6978:   free_vector(vv,1,n);  /* Doesn't work */
                   6979: ;
                   6980: } 
                   6981: 
                   6982: void lubksb(double **a, int n, int *indx, double b[]) 
                   6983: { 
                   6984:   int i,ii=0,ip,j; 
                   6985:   double sum; 
                   6986:  
                   6987:   for (i=1;i<=n;i++) { 
                   6988:     ip=indx[i]; 
                   6989:     sum=b[ip]; 
                   6990:     b[ip]=b[i]; 
                   6991:     if (ii) 
                   6992:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   6993:     else if (sum) ii=i; 
                   6994:     b[i]=sum; 
                   6995:   } 
                   6996:   for (i=n;i>=1;i--) { 
                   6997:     sum=b[i]; 
                   6998:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   6999:     b[i]=sum/a[i][i]; 
                   7000:   } 
                   7001: } 
                   7002: 
                   7003: void pstamp(FILE *fichier)
                   7004: {
1.196     brouard  7005:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  7006: }
                   7007: 
1.297     brouard  7008: void date2dmy(double date,double *day, double *month, double *year){
                   7009:   double yp=0., yp1=0., yp2=0.;
                   7010:   
                   7011:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   7012:                        fractional in yp1 */
                   7013:   *year=yp;
                   7014:   yp2=modf((yp1*12),&yp);
                   7015:   *month=yp;
                   7016:   yp1=modf((yp2*30.5),&yp);
                   7017:   *day=yp;
                   7018:   if(*day==0) *day=1;
                   7019:   if(*month==0) *month=1;
                   7020: }
                   7021: 
1.253     brouard  7022: 
                   7023: 
1.126     brouard  7024: /************ Frequencies ********************/
1.251     brouard  7025: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  7026:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   7027:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  7028: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  7029:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  7030:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  7031:   int iind=0, iage=0;
                   7032:   int mi; /* Effective wave */
                   7033:   int first;
                   7034:   double ***freq; /* Frequencies */
1.268     brouard  7035:   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 */
                   7036:   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  7037:   double *meanq, *stdq, *idq;
1.226     brouard  7038:   double **meanqt;
                   7039:   double *pp, **prop, *posprop, *pospropt;
                   7040:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   7041:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   7042:   double agebegin, ageend;
                   7043:     
                   7044:   pp=vector(1,nlstate);
1.251     brouard  7045:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  7046:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   7047:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   7048:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   7049:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  7050:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  7051:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  7052:   meanqt=matrix(1,lastpass,1,nqtveff);
                   7053:   strcpy(fileresp,"P_");
                   7054:   strcat(fileresp,fileresu);
                   7055:   /*strcat(fileresphtm,fileresu);*/
                   7056:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   7057:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   7058:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   7059:     exit(0);
                   7060:   }
1.240     brouard  7061:   
1.226     brouard  7062:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   7063:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   7064:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   7065:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   7066:     fflush(ficlog);
                   7067:     exit(70); 
                   7068:   }
                   7069:   else{
                   7070:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  7071: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  7072: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  7073:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   7074:   }
1.319     brouard  7075:   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  7076:   
1.226     brouard  7077:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   7078:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   7079:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   7080:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   7081:     fflush(ficlog);
                   7082:     exit(70); 
1.240     brouard  7083:   } else{
1.226     brouard  7084:     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  7085: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  7086: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  7087:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   7088:   }
1.319     brouard  7089:   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  7090:   
1.253     brouard  7091:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   7092:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  7093:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  7094:   j1=0;
1.126     brouard  7095:   
1.227     brouard  7096:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335     brouard  7097:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  7098:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  7099:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  7100:   
                   7101:   
1.226     brouard  7102:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   7103:      reference=low_education V1=0,V2=0
                   7104:      med_educ                V1=1 V2=0, 
                   7105:      high_educ               V1=0 V2=1
1.330     brouard  7106:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  7107:   */
1.249     brouard  7108:   dateintsum=0;
                   7109:   k2cpt=0;
                   7110: 
1.253     brouard  7111:   if(cptcoveff == 0 )
1.265     brouard  7112:     nl=1;  /* Constant and age model only */
1.253     brouard  7113:   else
                   7114:     nl=2;
1.265     brouard  7115: 
                   7116:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   7117:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335     brouard  7118:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  7119:    *     freq[s1][s2][iage] =0.
                   7120:    *     Loop on iind
                   7121:    *       ++freq[s1][s2][iage] weighted
                   7122:    *     end iind
                   7123:    *     if covariate and j!0
                   7124:    *       headers Variable on one line
                   7125:    *     endif cov j!=0
                   7126:    *     header of frequency table by age
                   7127:    *     Loop on age
                   7128:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   7129:    *       pos+=freq[s1][s2][iage] weighted
                   7130:    *       Loop on s1 initial state
                   7131:    *         fprintf(ficresp
                   7132:    *       end s1
                   7133:    *     end age
                   7134:    *     if j!=0 computes starting values
                   7135:    *     end compute starting values
                   7136:    *   end j1
                   7137:    * end nl 
                   7138:    */
1.253     brouard  7139:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   7140:     if(nj==1)
                   7141:       j=0;  /* First pass for the constant */
1.265     brouard  7142:     else{
1.335     brouard  7143:       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  7144:     }
1.251     brouard  7145:     first=1;
1.332     brouard  7146:     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  7147:       posproptt=0.;
1.330     brouard  7148:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  7149:        scanf("%d", i);*/
                   7150:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  7151:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  7152:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  7153:            freq[i][s2][m]=0;
1.251     brouard  7154:       
                   7155:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  7156:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  7157:          prop[i][m]=0;
                   7158:        posprop[i]=0;
                   7159:        pospropt[i]=0;
                   7160:       }
1.283     brouard  7161:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  7162:         idq[z1]=0.;
                   7163:         meanq[z1]=0.;
                   7164:         stdq[z1]=0.;
1.283     brouard  7165:       }
                   7166:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  7167:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  7168:       /*         meanqt[m][z1]=0.; */
                   7169:       /*       } */
                   7170:       /* }       */
1.251     brouard  7171:       /* dateintsum=0; */
                   7172:       /* k2cpt=0; */
                   7173:       
1.265     brouard  7174:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  7175:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   7176:        bool=1;
                   7177:        if(j !=0){
                   7178:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335     brouard  7179:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   7180:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  7181:                /* if(Tvaraff[z1] ==-20){ */
                   7182:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   7183:                /* }else  if(Tvaraff[z1] ==-10){ */
                   7184:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  7185:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335     brouard  7186:                /* 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); */
                   7187:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
1.338     brouard  7188:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  7189:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  7190:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  7191:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  7192:                  /* 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", */
                   7193:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   7194:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  7195:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   7196:                } /* Onlyf fixed */
                   7197:              } /* end z1 */
1.335     brouard  7198:            } /* cptcoveff > 0 */
1.251     brouard  7199:          } /* end any */
                   7200:        }/* end j==0 */
1.265     brouard  7201:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  7202:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  7203:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  7204:            m=mw[mi][iind];
                   7205:            if(j!=0){
                   7206:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335     brouard  7207:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  7208:                  if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  7209:                    /* iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /\* Good *\/ */
                   7210:                    iv= Tvar[Tmodelind[z1]]; /* Good *//* because cotvar starts now at first at ncovcol+nqv+ntv */ 
1.332     brouard  7211:                    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  7212:                                                                                      value is -1, we don't select. It differs from the 
                   7213:                                                                                      constant and age model which counts them. */
                   7214:                      bool=0; /* not selected */
                   7215:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  7216:                    /* i1=Tvaraff[z1]; */
                   7217:                    /* i2=TnsdVar[i1]; */
                   7218:                    /* i3=nbcode[i1][i2]; */
                   7219:                    /* i4=covar[i1][iind]; */
                   7220:                    /* if(i4 != i3){ */
                   7221:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  7222:                      bool=0;
                   7223:                    }
                   7224:                  }
                   7225:                }
                   7226:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   7227:            } /* end j==0 */
                   7228:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  7229:            if(bool==1){ /*Selected */
1.251     brouard  7230:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   7231:                 and mw[mi+1][iind]. dh depends on stepm. */
                   7232:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   7233:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   7234:              if(m >=firstpass && m <=lastpass){
                   7235:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   7236:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   7237:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   7238:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   7239:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   7240:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   7241:                if (m<lastpass) {
                   7242:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   7243:                  /*   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]); */
                   7244:                  if(s[m][iind]==-1)
                   7245:                    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.));
                   7246:                  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  7247:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   7248:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  7249:                      idq[z1]=idq[z1]+weight[iind];
                   7250:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   7251:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   7252:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  7253:                    }
1.284     brouard  7254:                  }
1.251     brouard  7255:                  /* if((int)agev[m][iind] == 55) */
                   7256:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   7257:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   7258:                  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  7259:                }
1.251     brouard  7260:              } /* end if between passes */  
                   7261:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   7262:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   7263:                k2cpt++;
                   7264:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  7265:              }
1.251     brouard  7266:            }else{
                   7267:              bool=1;
                   7268:            }/* end bool 2 */
                   7269:          } /* end m */
1.284     brouard  7270:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   7271:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   7272:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   7273:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   7274:          /* } */
1.251     brouard  7275:        } /* end bool */
                   7276:       } /* end iind = 1 to imx */
1.319     brouard  7277:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  7278:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   7279:       
                   7280:       
                   7281:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335     brouard  7282:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  7283:         pstamp(ficresp);
1.335     brouard  7284:       if  (cptcoveff>0 && j!=0){
1.265     brouard  7285:         pstamp(ficresp);
1.251     brouard  7286:        printf( "\n#********** Variable "); 
                   7287:        fprintf(ficresp, "\n#********** Variable "); 
                   7288:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   7289:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   7290:        fprintf(ficlog, "\n#********** Variable "); 
1.340     brouard  7291:        for (z1=1; z1<=cptcoveff; z1++){
1.251     brouard  7292:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  7293:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7294:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7295:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7296:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7297:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  7298:          }else{
1.330     brouard  7299:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7300:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7301:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7302:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7303:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  7304:          }
                   7305:        }
                   7306:        printf( "**********\n#");
                   7307:        fprintf(ficresp, "**********\n#");
                   7308:        fprintf(ficresphtm, "**********</h3>\n");
                   7309:        fprintf(ficresphtmfr, "**********</h3>\n");
                   7310:        fprintf(ficlog, "**********\n");
                   7311:       }
1.284     brouard  7312:       /*
                   7313:        Printing means of quantitative variables if any
                   7314:       */
                   7315:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  7316:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  7317:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  7318:        if(weightopt==1){
                   7319:          printf(" Weighted mean and standard deviation of");
                   7320:          fprintf(ficlog," Weighted mean and standard deviation of");
                   7321:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   7322:        }
1.311     brouard  7323:        /* mu = \frac{w x}{\sum w}
                   7324:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   7325:        */
                   7326:        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]));
                   7327:        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]));
                   7328:        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  7329:       }
                   7330:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   7331:       /*       for(m=1;m<=lastpass;m++){ */
                   7332:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   7333:       /*   } */
                   7334:       /* } */
1.283     brouard  7335: 
1.251     brouard  7336:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335     brouard  7337:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  7338:         fprintf(ficresp, " Age");
1.335     brouard  7339:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   7340:          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]]);
                   7341:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7342:        }
1.251     brouard  7343:       for(i=1; i<=nlstate;i++) {
1.335     brouard  7344:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  7345:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   7346:       }
1.335     brouard  7347:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  7348:       fprintf(ficresphtm, "\n");
                   7349:       
                   7350:       /* Header of frequency table by age */
                   7351:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   7352:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  7353:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  7354:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  7355:          if(s2!=0 && m!=0)
                   7356:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  7357:        }
1.226     brouard  7358:       }
1.251     brouard  7359:       fprintf(ficresphtmfr, "\n");
                   7360:     
                   7361:       /* For each age */
                   7362:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   7363:        fprintf(ficresphtm,"<tr>");
                   7364:        if(iage==iagemax+1){
                   7365:          fprintf(ficlog,"1");
                   7366:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   7367:        }else if(iage==iagemax+2){
                   7368:          fprintf(ficlog,"0");
                   7369:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   7370:        }else if(iage==iagemax+3){
                   7371:          fprintf(ficlog,"Total");
                   7372:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   7373:        }else{
1.240     brouard  7374:          if(first==1){
1.251     brouard  7375:            first=0;
                   7376:            printf("See log file for details...\n");
                   7377:          }
                   7378:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   7379:          fprintf(ficlog,"Age %d", iage);
                   7380:        }
1.265     brouard  7381:        for(s1=1; s1 <=nlstate ; s1++){
                   7382:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   7383:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  7384:        }
1.265     brouard  7385:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  7386:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  7387:            pos += freq[s1][m][iage];
                   7388:          if(pp[s1]>=1.e-10){
1.251     brouard  7389:            if(first==1){
1.265     brouard  7390:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  7391:            }
1.265     brouard  7392:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  7393:          }else{
                   7394:            if(first==1)
1.265     brouard  7395:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   7396:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  7397:          }
                   7398:        }
                   7399:       
1.265     brouard  7400:        for(s1=1; s1 <=nlstate ; s1++){ 
                   7401:          /* posprop[s1]=0; */
                   7402:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   7403:            pp[s1] += freq[s1][m][iage];
                   7404:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   7405:       
                   7406:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   7407:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   7408:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   7409:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   7410:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   7411:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   7412:        }
                   7413:        
                   7414:        /* Writing ficresp */
1.335     brouard  7415:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  7416:           if( iage <= iagemax){
                   7417:            fprintf(ficresp," %d",iage);
                   7418:           }
                   7419:         }else if( nj==2){
                   7420:           if( iage <= iagemax){
                   7421:            fprintf(ficresp," %d",iage);
1.335     brouard  7422:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  7423:           }
1.240     brouard  7424:        }
1.265     brouard  7425:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  7426:          if(pos>=1.e-5){
1.251     brouard  7427:            if(first==1)
1.265     brouard  7428:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   7429:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  7430:          }else{
                   7431:            if(first==1)
1.265     brouard  7432:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   7433:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  7434:          }
                   7435:          if( iage <= iagemax){
                   7436:            if(pos>=1.e-5){
1.335     brouard  7437:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  7438:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   7439:               }else if( nj==2){
                   7440:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   7441:               }
                   7442:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   7443:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   7444:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   7445:            } else{
1.335     brouard  7446:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  7447:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  7448:            }
1.240     brouard  7449:          }
1.265     brouard  7450:          pospropt[s1] +=posprop[s1];
                   7451:        } /* end loop s1 */
1.251     brouard  7452:        /* pospropt=0.; */
1.265     brouard  7453:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  7454:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  7455:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  7456:              if(first==1){
1.265     brouard  7457:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  7458:              }
1.265     brouard  7459:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   7460:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  7461:            }
1.265     brouard  7462:            if(s1!=0 && m!=0)
                   7463:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  7464:          }
1.265     brouard  7465:        } /* end loop s1 */
1.251     brouard  7466:        posproptt=0.; 
1.265     brouard  7467:        for(s1=1; s1 <=nlstate; s1++){
                   7468:          posproptt += pospropt[s1];
1.251     brouard  7469:        }
                   7470:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  7471:        fprintf(ficresphtm,"</tr>\n");
1.335     brouard  7472:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  7473:          if(iage <= iagemax)
                   7474:            fprintf(ficresp,"\n");
1.240     brouard  7475:        }
1.251     brouard  7476:        if(first==1)
                   7477:          printf("Others in log...\n");
                   7478:        fprintf(ficlog,"\n");
                   7479:       } /* end loop age iage */
1.265     brouard  7480:       
1.251     brouard  7481:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  7482:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  7483:        if(posproptt < 1.e-5){
1.265     brouard  7484:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  7485:        }else{
1.265     brouard  7486:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  7487:        }
1.226     brouard  7488:       }
1.251     brouard  7489:       fprintf(ficresphtm,"</tr>\n");
                   7490:       fprintf(ficresphtm,"</table>\n");
                   7491:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  7492:       if(posproptt < 1.e-5){
1.251     brouard  7493:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   7494:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  7495:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   7496:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  7497:        invalidvarcomb[j1]=1;
1.226     brouard  7498:       }else{
1.338     brouard  7499:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
1.251     brouard  7500:        invalidvarcomb[j1]=0;
1.226     brouard  7501:       }
1.251     brouard  7502:       fprintf(ficresphtmfr,"</table>\n");
                   7503:       fprintf(ficlog,"\n");
                   7504:       if(j!=0){
                   7505:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  7506:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  7507:          for(k=1; k <=(nlstate+ndeath); k++){
                   7508:            if (k != i) {
1.265     brouard  7509:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  7510:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  7511:                  if(j1==1){ /* All dummy covariates to zero */
                   7512:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   7513:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  7514:                    printf("%d%d ",i,k);
                   7515:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  7516:                    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]));
                   7517:                    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]));
                   7518:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  7519:                  }
1.253     brouard  7520:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   7521:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   7522:                    x[iage]= (double)iage;
                   7523:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  7524:                    /* 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  7525:                  }
1.268     brouard  7526:                  /* Some are not finite, but linreg will ignore these ages */
                   7527:                  no=0;
1.253     brouard  7528:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  7529:                  pstart[s1]=b;
                   7530:                  pstart[s1-1]=a;
1.252     brouard  7531:                }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 */ 
                   7532:                  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]);
                   7533:                  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  7534:                  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  7535:                  printf("%d%d ",i,k);
                   7536:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  7537:                  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  7538:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   7539:                  ;
                   7540:                }
                   7541:                /* printf("%12.7f )", param[i][jj][k]); */
                   7542:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  7543:                s1++; 
1.251     brouard  7544:              } /* end jj */
                   7545:            } /* end k!= i */
                   7546:          } /* end k */
1.265     brouard  7547:        } /* end i, s1 */
1.251     brouard  7548:       } /* end j !=0 */
                   7549:     } /* end selected combination of covariate j1 */
                   7550:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   7551:       printf("#Freqsummary: Starting values for the constants:\n");
                   7552:       fprintf(ficlog,"\n");
1.265     brouard  7553:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  7554:        for(k=1; k <=(nlstate+ndeath); k++){
                   7555:          if (k != i) {
                   7556:            printf("%d%d ",i,k);
                   7557:            fprintf(ficlog,"%d%d ",i,k);
                   7558:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  7559:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  7560:              if(jj==1){ /* Age has to be done */
1.265     brouard  7561:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   7562:                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]));
                   7563:                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  7564:              }
                   7565:              /* printf("%12.7f )", param[i][jj][k]); */
                   7566:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  7567:              s1++; 
1.250     brouard  7568:            }
1.251     brouard  7569:            printf("\n");
                   7570:            fprintf(ficlog,"\n");
1.250     brouard  7571:          }
                   7572:        }
1.284     brouard  7573:       } /* end of state i */
1.251     brouard  7574:       printf("#Freqsummary\n");
                   7575:       fprintf(ficlog,"\n");
1.265     brouard  7576:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   7577:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   7578:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   7579:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   7580:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   7581:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   7582:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   7583:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  7584:          /* } */
                   7585:        }
1.265     brouard  7586:       } /* end loop s1 */
1.251     brouard  7587:       
                   7588:       printf("\n");
                   7589:       fprintf(ficlog,"\n");
                   7590:     } /* end j=0 */
1.249     brouard  7591:   } /* end j */
1.252     brouard  7592: 
1.253     brouard  7593:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  7594:     for(i=1, jk=1; i <=nlstate; i++){
                   7595:       for(j=1; j <=nlstate+ndeath; j++){
                   7596:        if(j!=i){
                   7597:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   7598:          printf("%1d%1d",i,j);
                   7599:          fprintf(ficparo,"%1d%1d",i,j);
                   7600:          for(k=1; k<=ncovmodel;k++){
                   7601:            /*    printf(" %lf",param[i][j][k]); */
                   7602:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   7603:            p[jk]=pstart[jk];
                   7604:            printf(" %f ",pstart[jk]);
                   7605:            fprintf(ficparo," %f ",pstart[jk]);
                   7606:            jk++;
                   7607:          }
                   7608:          printf("\n");
                   7609:          fprintf(ficparo,"\n");
                   7610:        }
                   7611:       }
                   7612:     }
                   7613:   } /* end mle=-2 */
1.226     brouard  7614:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  7615:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  7616:   
1.226     brouard  7617:   fclose(ficresp);
                   7618:   fclose(ficresphtm);
                   7619:   fclose(ficresphtmfr);
1.283     brouard  7620:   free_vector(idq,1,nqfveff);
1.226     brouard  7621:   free_vector(meanq,1,nqfveff);
1.284     brouard  7622:   free_vector(stdq,1,nqfveff);
1.226     brouard  7623:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  7624:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   7625:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  7626:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  7627:   free_vector(pospropt,1,nlstate);
                   7628:   free_vector(posprop,1,nlstate);
1.251     brouard  7629:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  7630:   free_vector(pp,1,nlstate);
                   7631:   /* End of freqsummary */
                   7632: }
1.126     brouard  7633: 
1.268     brouard  7634: /* Simple linear regression */
                   7635: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   7636: 
                   7637:   /* y=a+bx regression */
                   7638:   double   sumx = 0.0;                        /* sum of x                      */
                   7639:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   7640:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   7641:   double   sumy = 0.0;                        /* sum of y                      */
                   7642:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   7643:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   7644:   double yhat;
                   7645:   
                   7646:   double denom=0;
                   7647:   int i;
                   7648:   int ne=*no;
                   7649:   
                   7650:   for ( i=ifi, ne=0;i<=ila;i++) {
                   7651:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   7652:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   7653:       continue;
                   7654:     }
                   7655:     ne=ne+1;
                   7656:     sumx  += x[i];       
                   7657:     sumx2 += x[i]*x[i];  
                   7658:     sumxy += x[i] * y[i];
                   7659:     sumy  += y[i];      
                   7660:     sumy2 += y[i]*y[i]; 
                   7661:     denom = (ne * sumx2 - sumx*sumx);
                   7662:     /* 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); */
                   7663:   } 
                   7664:   
                   7665:   denom = (ne * sumx2 - sumx*sumx);
                   7666:   if (denom == 0) {
                   7667:     // vertical, slope m is infinity
                   7668:     *b = INFINITY;
                   7669:     *a = 0;
                   7670:     if (r) *r = 0;
                   7671:     return 1;
                   7672:   }
                   7673:   
                   7674:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   7675:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   7676:   if (r!=NULL) {
                   7677:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   7678:       sqrt((sumx2 - sumx*sumx/ne) *
                   7679:           (sumy2 - sumy*sumy/ne));
                   7680:   }
                   7681:   *no=ne;
                   7682:   for ( i=ifi, ne=0;i<=ila;i++) {
                   7683:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   7684:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   7685:       continue;
                   7686:     }
                   7687:     ne=ne+1;
                   7688:     yhat = y[i] - *a -*b* x[i];
                   7689:     sume2  += yhat * yhat ;       
                   7690:     
                   7691:     denom = (ne * sumx2 - sumx*sumx);
                   7692:     /* 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); */
                   7693:   } 
                   7694:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   7695:   *sa= *sb * sqrt(sumx2/ne);
                   7696:   
                   7697:   return 0; 
                   7698: }
                   7699: 
1.126     brouard  7700: /************ Prevalence ********************/
1.227     brouard  7701: 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)
                   7702: {  
                   7703:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   7704:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   7705:      We still use firstpass and lastpass as another selection.
                   7706:   */
1.126     brouard  7707:  
1.227     brouard  7708:   int i, m, jk, j1, bool, z1,j, iv;
                   7709:   int mi; /* Effective wave */
                   7710:   int iage;
1.359     brouard  7711:   double agebegin; /*, ageend;*/
1.227     brouard  7712: 
                   7713:   double **prop;
                   7714:   double posprop; 
                   7715:   double  y2; /* in fractional years */
                   7716:   int iagemin, iagemax;
                   7717:   int first; /** to stop verbosity which is redirected to log file */
                   7718: 
                   7719:   iagemin= (int) agemin;
                   7720:   iagemax= (int) agemax;
                   7721:   /*pp=vector(1,nlstate);*/
1.251     brouard  7722:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  7723:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   7724:   j1=0;
1.222     brouard  7725:   
1.227     brouard  7726:   /*j=cptcoveff;*/
                   7727:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  7728:   
1.288     brouard  7729:   first=0;
1.335     brouard  7730:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  7731:     for (i=1; i<=nlstate; i++)  
1.251     brouard  7732:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  7733:        prop[i][iage]=0.0;
                   7734:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   7735:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   7736:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   7737:     
                   7738:     for (i=1; i<=imx; i++) { /* Each individual */
                   7739:       bool=1;
                   7740:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   7741:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   7742:        m=mw[mi][i];
                   7743:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   7744:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   7745:        for (z1=1; z1<=cptcoveff; z1++){
                   7746:          if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  7747:            iv= Tvar[Tmodelind[z1]];/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.332     brouard  7748:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  7749:              bool=0;
                   7750:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  7751:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  7752:              bool=0;
                   7753:            }
                   7754:        }
                   7755:        if(bool==1){ /* Otherwise we skip that wave/person */
                   7756:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   7757:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   7758:          if(m >=firstpass && m <=lastpass){
                   7759:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   7760:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   7761:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   7762:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  7763:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  7764:                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); 
                   7765:                exit(1);
                   7766:              }
                   7767:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   7768:                /*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]]);*/
                   7769:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   7770:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   7771:              } /* end valid statuses */ 
                   7772:            } /* end selection of dates */
                   7773:          } /* end selection of waves */
                   7774:        } /* end bool */
                   7775:       } /* end wave */
                   7776:     } /* end individual */
                   7777:     for(i=iagemin; i <= iagemax+3; i++){  
                   7778:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   7779:        posprop += prop[jk][i]; 
                   7780:       } 
                   7781:       
                   7782:       for(jk=1; jk <=nlstate ; jk++){      
                   7783:        if( i <=  iagemax){ 
                   7784:          if(posprop>=1.e-5){ 
                   7785:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   7786:          } else{
1.288     brouard  7787:            if(!first){
                   7788:              first=1;
1.266     brouard  7789:              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]);
                   7790:            }else{
1.288     brouard  7791:              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  7792:            }
                   7793:          }
                   7794:        } 
                   7795:       }/* end jk */ 
                   7796:     }/* end i */ 
1.222     brouard  7797:      /*} *//* end i1 */
1.227     brouard  7798:   } /* end j1 */
1.222     brouard  7799:   
1.227     brouard  7800:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   7801:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  7802:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  7803: }  /* End of prevalence */
1.126     brouard  7804: 
                   7805: /************* Waves Concatenation ***************/
                   7806: 
                   7807: 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)
                   7808: {
1.298     brouard  7809:   /* 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  7810:      Death is a valid wave (if date is known).
                   7811:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   7812:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  7813:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  7814:   */
1.126     brouard  7815: 
1.224     brouard  7816:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  7817:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   7818:      double sum=0., jmean=0.;*/
1.224     brouard  7819:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  7820:   int j, k=0,jk, ju, jl;
                   7821:   double sum=0.;
                   7822:   first=0;
1.214     brouard  7823:   firstwo=0;
1.217     brouard  7824:   firsthree=0;
1.218     brouard  7825:   firstfour=0;
1.164     brouard  7826:   jmin=100000;
1.126     brouard  7827:   jmax=-1;
                   7828:   jmean=0.;
1.224     brouard  7829: 
                   7830: /* Treating live states */
1.214     brouard  7831:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  7832:     mi=0;  /* First valid wave */
1.227     brouard  7833:     mli=0; /* Last valid wave */
1.309     brouard  7834:     m=firstpass;  /* Loop on waves */
                   7835:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  7836:       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 */
                   7837:        mli=m-1;/* mw[++mi][i]=m-1; */
                   7838:       }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  7839:        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  7840:        mli=m;
1.224     brouard  7841:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   7842:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  7843:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  7844:       }
1.309     brouard  7845:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  7846: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  7847:        break;
1.224     brouard  7848: #else
1.317     brouard  7849:        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  7850:          if(firsthree == 0){
1.302     brouard  7851:            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  7852:            firsthree=1;
1.317     brouard  7853:          }else if(firsthree >=1 && firsthree < 10){
                   7854:            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);
                   7855:            firsthree++;
                   7856:          }else if(firsthree == 10){
                   7857:            printf("Information, too many Information flags: no more reported to log either\n");
                   7858:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   7859:            firsthree++;
                   7860:          }else{
                   7861:            firsthree++;
1.227     brouard  7862:          }
1.309     brouard  7863:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  7864:          mli=m;
                   7865:        }
                   7866:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   7867:          nbwarn++;
1.309     brouard  7868:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  7869:            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);
                   7870:            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);
                   7871:          }
                   7872:          break;
                   7873:        }
                   7874:        break;
1.224     brouard  7875: #endif
1.227     brouard  7876:       }/* End m >= lastpass */
1.126     brouard  7877:     }/* end while */
1.224     brouard  7878: 
1.227     brouard  7879:     /* 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  7880:     /* After last pass */
1.224     brouard  7881: /* Treating death states */
1.214     brouard  7882:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  7883:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   7884:       /* } */
1.126     brouard  7885:       mi++;    /* Death is another wave */
                   7886:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  7887:       /* Only death is a correct wave */
1.126     brouard  7888:       mw[mi][i]=m;
1.257     brouard  7889:     } /* else not in a death state */
1.224     brouard  7890: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  7891:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  7892:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  7893:        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  7894:          nbwarn++;
                   7895:          if(firstfiv==0){
1.309     brouard  7896:            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  7897:            firstfiv=1;
                   7898:          }else{
1.309     brouard  7899:            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  7900:          }
1.309     brouard  7901:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   7902:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  7903:          nberr++;
                   7904:          if(firstwo==0){
1.309     brouard  7905:            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  7906:            firstwo=1;
                   7907:          }
1.309     brouard  7908:          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  7909:        }
1.257     brouard  7910:       }else{ /* if date of interview is unknown */
1.227     brouard  7911:        /* death is known but not confirmed by death status at any wave */
                   7912:        if(firstfour==0){
1.309     brouard  7913:          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  7914:          firstfour=1;
                   7915:        }
1.309     brouard  7916:        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  7917:       }
1.224     brouard  7918:     } /* end if date of death is known */
                   7919: #endif
1.309     brouard  7920:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   7921:     /* wav[i]=mw[mi][i];   */
1.126     brouard  7922:     if(mi==0){
                   7923:       nbwarn++;
                   7924:       if(first==0){
1.227     brouard  7925:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   7926:        first=1;
1.126     brouard  7927:       }
                   7928:       if(first==1){
1.227     brouard  7929:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  7930:       }
                   7931:     } /* end mi==0 */
                   7932:   } /* End individuals */
1.214     brouard  7933:   /* wav and mw are no more changed */
1.223     brouard  7934:        
1.317     brouard  7935:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   7936:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   7937: 
                   7938: 
1.126     brouard  7939:   for(i=1; i<=imx; i++){
                   7940:     for(mi=1; mi<wav[i];mi++){
                   7941:       if (stepm <=0)
1.227     brouard  7942:        dh[mi][i]=1;
1.126     brouard  7943:       else{
1.260     brouard  7944:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  7945:          if (agedc[i] < 2*AGESUP) {
                   7946:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   7947:            if(j==0) j=1;  /* Survives at least one month after exam */
                   7948:            else if(j<0){
                   7949:              nberr++;
1.359     brouard  7950:              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  7951:              j=1; /* Temporary Dangerous patch */
                   7952:              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  7953:              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  7954:              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);
                   7955:            }
                   7956:            k=k+1;
                   7957:            if (j >= jmax){
                   7958:              jmax=j;
                   7959:              ijmax=i;
                   7960:            }
                   7961:            if (j <= jmin){
                   7962:              jmin=j;
                   7963:              ijmin=i;
                   7964:            }
                   7965:            sum=sum+j;
                   7966:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   7967:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   7968:          }
                   7969:        }
                   7970:        else{
                   7971:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  7972: /*       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  7973:                                        
1.227     brouard  7974:          k=k+1;
                   7975:          if (j >= jmax) {
                   7976:            jmax=j;
                   7977:            ijmax=i;
                   7978:          }
                   7979:          else if (j <= jmin){
                   7980:            jmin=j;
                   7981:            ijmin=i;
                   7982:          }
                   7983:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   7984:          /*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]);*/
                   7985:          if(j<0){
                   7986:            nberr++;
1.359     brouard  7987:            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]);
                   7988:            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  7989:          }
                   7990:          sum=sum+j;
                   7991:        }
                   7992:        jk= j/stepm;
                   7993:        jl= j -jk*stepm;
                   7994:        ju= j -(jk+1)*stepm;
                   7995:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   7996:          if(jl==0){
                   7997:            dh[mi][i]=jk;
                   7998:            bh[mi][i]=0;
                   7999:          }else{ /* We want a negative bias in order to only have interpolation ie
                   8000:                  * to avoid the price of an extra matrix product in likelihood */
                   8001:            dh[mi][i]=jk+1;
                   8002:            bh[mi][i]=ju;
                   8003:          }
                   8004:        }else{
                   8005:          if(jl <= -ju){
                   8006:            dh[mi][i]=jk;
                   8007:            bh[mi][i]=jl;       /* bias is positive if real duration
                   8008:                                 * is higher than the multiple of stepm and negative otherwise.
                   8009:                                 */
                   8010:          }
                   8011:          else{
                   8012:            dh[mi][i]=jk+1;
                   8013:            bh[mi][i]=ju;
                   8014:          }
                   8015:          if(dh[mi][i]==0){
                   8016:            dh[mi][i]=1; /* At least one step */
                   8017:            bh[mi][i]=ju; /* At least one step */
                   8018:            /*  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);*/
                   8019:          }
                   8020:        } /* end if mle */
1.126     brouard  8021:       }
                   8022:     } /* end wave */
                   8023:   }
                   8024:   jmean=sum/k;
                   8025:   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  8026:   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  8027: }
1.126     brouard  8028: 
                   8029: /*********** Tricode ****************************/
1.220     brouard  8030:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  8031:  {
                   8032:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   8033:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   8034:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   8035:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   8036:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   8037:     */
1.130     brouard  8038: 
1.242     brouard  8039:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   8040:    int modmaxcovj=0; /* Modality max of covariates j */
                   8041:    int cptcode=0; /* Modality max of covariates j */
                   8042:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  8043: 
                   8044: 
1.242     brouard  8045:    /* cptcoveff=0;  */
                   8046:    /* *cptcov=0; */
1.126     brouard  8047:  
1.242     brouard  8048:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  8049:    for (k=1; k <= maxncov; k++)
                   8050:      for(j=1; j<=2; j++)
                   8051:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  8052: 
1.242     brouard  8053:    /* Loop on covariates without age and products and no quantitative variable */
1.335     brouard  8054:    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  8055:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
1.343     brouard  8056:      /* printf("Testing k=%d, cptcovt=%d\n",k, cptcovt); */
1.349     brouard  8057:      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  8058:        switch(Fixed[k]) {
                   8059:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  8060:         modmaxcovj=0;
                   8061:         modmincovj=0;
1.242     brouard  8062:         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  8063:           /* 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  8064:           ij=(int)(covar[Tvar[k]][i]);
                   8065:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   8066:            * If product of Vn*Vm, still boolean *:
                   8067:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   8068:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   8069:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   8070:              modality of the nth covariate of individual i. */
                   8071:           if (ij > modmaxcovj)
                   8072:             modmaxcovj=ij; 
                   8073:           else if (ij < modmincovj) 
                   8074:             modmincovj=ij; 
1.287     brouard  8075:           if (ij <0 || ij >1 ){
1.311     brouard  8076:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   8077:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   8078:             fflush(ficlog);
                   8079:             exit(1);
1.287     brouard  8080:           }
                   8081:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  8082:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   8083:             exit(1);
                   8084:           }else
                   8085:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   8086:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   8087:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   8088:           /* getting the maximum value of the modality of the covariate
                   8089:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   8090:              female ies 1, then modmaxcovj=1.
                   8091:           */
                   8092:         } /* end for loop on individuals i */
                   8093:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   8094:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   8095:         cptcode=modmaxcovj;
                   8096:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   8097:         /*for (i=0; i<=cptcode; i++) {*/
                   8098:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   8099:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   8100:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   8101:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   8102:             if( j != -1){
                   8103:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   8104:                                  covariate for which somebody answered excluding 
                   8105:                                  undefined. Usually 2: 0 and 1. */
                   8106:             }
                   8107:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   8108:                                     covariate for which somebody answered including 
                   8109:                                     undefined. Usually 3: -1, 0 and 1. */
                   8110:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   8111:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   8112:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  8113:                        
1.242     brouard  8114:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   8115:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   8116:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   8117:         /* modmincovj=3; modmaxcovj = 7; */
                   8118:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   8119:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   8120:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   8121:         /* nbcode[Tvar[j]][ij]=k; */
                   8122:         /* nbcode[Tvar[j]][1]=0; */
                   8123:         /* nbcode[Tvar[j]][2]=1; */
                   8124:         /* nbcode[Tvar[j]][3]=2; */
                   8125:         /* To be continued (not working yet). */
                   8126:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  8127: 
                   8128:         /* 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*/
                   8129:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   8130:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   8131:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   8132:         /*, could be restored in the future */
                   8133:         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  8134:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   8135:             break;
                   8136:           }
                   8137:           ij++;
1.287     brouard  8138:           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  8139:           cptcode = ij; /* New max modality for covar j */
                   8140:         } /* end of loop on modality i=-1 to 1 or more */
                   8141:         break;
                   8142:        case 1: /* Testing on varying covariate, could be simple and
                   8143:                * should look at waves or product of fixed *
                   8144:                * varying. No time to test -1, assuming 0 and 1 only */
                   8145:         ij=0;
                   8146:         for(i=0; i<=1;i++){
                   8147:           nbcode[Tvar[k]][++ij]=i;
                   8148:         }
                   8149:         break;
                   8150:        default:
                   8151:         break;
                   8152:        } /* end switch */
                   8153:      } /* end dummy test */
1.349     brouard  8154:      if(Dummy[k]==1 && Typevar[k] !=1 && Typevar[k] !=3 && Fixed ==0){ /* Fixed Quantitative covariate and not age product */ 
1.311     brouard  8155:        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  8156:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   8157:           printf("Error k=%d \n",k);
                   8158:           exit(1);
                   8159:         }
1.311     brouard  8160:         if(isnan(covar[Tvar[k]][i])){
                   8161:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   8162:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   8163:           fflush(ficlog);
                   8164:           exit(1);
                   8165:          }
                   8166:        }
1.335     brouard  8167:      } /* end Quanti */
1.287     brouard  8168:    } /* 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  8169:   
                   8170:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   8171:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   8172:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   8173:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   8174:      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 */ 
                   8175:      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 */
                   8176:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   8177:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   8178:   
                   8179:    ij=0;
                   8180:    /* 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  8181:    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 */
                   8182:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  8183:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   8184:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335     brouard  8185:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   8186:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   8187:        /* 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  8188:        /* If product not in single variable we don't print results */
                   8189:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335     brouard  8190:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   8191:        /* k=       1    2   3     4       5       6      7       8        9  */
                   8192:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   8193:        /* ij            1    2                                            3  */  
                   8194:        /* Tvaraff[ij]=  4    3                                            1  */
                   8195:        /* Tmodelind[ij]=2    3                                            9  */
                   8196:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  8197:        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*/
                   8198:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   8199:        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 */
                   8200:        if(Fixed[k]!=0)
                   8201:         anyvaryingduminmodel=1;
                   8202:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   8203:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   8204:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   8205:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   8206:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   8207:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   8208:      } 
                   8209:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   8210:    /* ij--; */
                   8211:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335     brouard  8212:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  8213:                * because they can be excluded from the model and real
                   8214:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   8215:    for(j=ij+1; j<= cptcovt; j++){
                   8216:      Tvaraff[j]=0;
                   8217:      Tmodelind[j]=0;
                   8218:    }
                   8219:    for(j=ntveff+1; j<= cptcovt; j++){
                   8220:      TmodelInvind[j]=0;
                   8221:    }
                   8222:    /* To be sorted */
                   8223:    ;
                   8224:  }
1.126     brouard  8225: 
1.145     brouard  8226: 
1.126     brouard  8227: /*********** Health Expectancies ****************/
                   8228: 
1.235     brouard  8229:  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  8230: 
                   8231: {
                   8232:   /* Health expectancies, no variances */
1.329     brouard  8233:   /* cij is the combination in the list of combination of dummy covariates */
                   8234:   /* strstart is a string of time at start of computing */
1.164     brouard  8235:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  8236:   int nhstepma, nstepma; /* Decreasing with age */
                   8237:   double age, agelim, hf;
                   8238:   double ***p3mat;
                   8239:   double eip;
                   8240: 
1.238     brouard  8241:   /* pstamp(ficreseij); */
1.126     brouard  8242:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   8243:   fprintf(ficreseij,"# Age");
                   8244:   for(i=1; i<=nlstate;i++){
                   8245:     for(j=1; j<=nlstate;j++){
                   8246:       fprintf(ficreseij," e%1d%1d ",i,j);
                   8247:     }
                   8248:     fprintf(ficreseij," e%1d. ",i);
                   8249:   }
                   8250:   fprintf(ficreseij,"\n");
                   8251: 
                   8252:   
                   8253:   if(estepm < stepm){
                   8254:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8255:   }
                   8256:   else  hstepm=estepm;   
                   8257:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   8258:    * This is mainly to measure the difference between two models: for example
                   8259:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   8260:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   8261:    * progression in between and thus overestimating or underestimating according
                   8262:    * to the curvature of the survival function. If, for the same date, we 
                   8263:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   8264:    * to compare the new estimate of Life expectancy with the same linear 
                   8265:    * hypothesis. A more precise result, taking into account a more precise
                   8266:    * curvature will be obtained if estepm is as small as stepm. */
                   8267: 
                   8268:   /* For example we decided to compute the life expectancy with the smallest unit */
                   8269:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   8270:      nhstepm is the number of hstepm from age to agelim 
                   8271:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  8272:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  8273:      and note for a fixed period like estepm months */
                   8274:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   8275:      survival function given by stepm (the optimization length). Unfortunately it
                   8276:      means that if the survival funtion is printed only each two years of age and if
                   8277:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   8278:      results. So we changed our mind and took the option of the best precision.
                   8279:   */
                   8280:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   8281: 
                   8282:   agelim=AGESUP;
                   8283:   /* If stepm=6 months */
                   8284:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   8285:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   8286:     
                   8287: /* nhstepm age range expressed in number of stepm */
                   8288:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   8289:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   8290:   /* if (stepm >= YEARM) hstepm=1;*/
                   8291:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   8292:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8293: 
                   8294:   for (age=bage; age<=fage; age ++){ 
                   8295:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   8296:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   8297:     /* if (stepm >= YEARM) hstepm=1;*/
                   8298:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   8299: 
                   8300:     /* If stepm=6 months */
                   8301:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   8302:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  8303:     /* 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  8304:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  8305:     
                   8306:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   8307:     
                   8308:     printf("%d|",(int)age);fflush(stdout);
                   8309:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   8310:     
                   8311:     /* Computing expectancies */
                   8312:     for(i=1; i<=nlstate;i++)
                   8313:       for(j=1; j<=nlstate;j++)
                   8314:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   8315:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   8316:          
                   8317:          /* 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]);*/
                   8318: 
                   8319:        }
                   8320: 
                   8321:     fprintf(ficreseij,"%3.0f",age );
                   8322:     for(i=1; i<=nlstate;i++){
                   8323:       eip=0;
                   8324:       for(j=1; j<=nlstate;j++){
                   8325:        eip +=eij[i][j][(int)age];
                   8326:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   8327:       }
                   8328:       fprintf(ficreseij,"%9.4f", eip );
                   8329:     }
                   8330:     fprintf(ficreseij,"\n");
                   8331:     
                   8332:   }
                   8333:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8334:   printf("\n");
                   8335:   fprintf(ficlog,"\n");
                   8336:   
                   8337: }
                   8338: 
1.235     brouard  8339:  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  8340: 
                   8341: {
                   8342:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  8343:      to initial status i, ei. .
1.126     brouard  8344:   */
1.336     brouard  8345:   /* Very time consuming function, but already optimized with precov */
1.126     brouard  8346:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   8347:   int nhstepma, nstepma; /* Decreasing with age */
                   8348:   double age, agelim, hf;
                   8349:   double ***p3matp, ***p3matm, ***varhe;
                   8350:   double **dnewm,**doldm;
                   8351:   double *xp, *xm;
                   8352:   double **gp, **gm;
                   8353:   double ***gradg, ***trgradg;
                   8354:   int theta;
                   8355: 
                   8356:   double eip, vip;
                   8357: 
                   8358:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   8359:   xp=vector(1,npar);
                   8360:   xm=vector(1,npar);
                   8361:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   8362:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   8363:   
                   8364:   pstamp(ficresstdeij);
                   8365:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   8366:   fprintf(ficresstdeij,"# Age");
                   8367:   for(i=1; i<=nlstate;i++){
                   8368:     for(j=1; j<=nlstate;j++)
                   8369:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   8370:     fprintf(ficresstdeij," e%1d. ",i);
                   8371:   }
                   8372:   fprintf(ficresstdeij,"\n");
                   8373: 
                   8374:   pstamp(ficrescveij);
                   8375:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   8376:   fprintf(ficrescveij,"# Age");
                   8377:   for(i=1; i<=nlstate;i++)
                   8378:     for(j=1; j<=nlstate;j++){
                   8379:       cptj= (j-1)*nlstate+i;
                   8380:       for(i2=1; i2<=nlstate;i2++)
                   8381:        for(j2=1; j2<=nlstate;j2++){
                   8382:          cptj2= (j2-1)*nlstate+i2;
                   8383:          if(cptj2 <= cptj)
                   8384:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   8385:        }
                   8386:     }
                   8387:   fprintf(ficrescveij,"\n");
                   8388:   
                   8389:   if(estepm < stepm){
                   8390:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8391:   }
                   8392:   else  hstepm=estepm;   
                   8393:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   8394:    * This is mainly to measure the difference between two models: for example
                   8395:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   8396:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   8397:    * progression in between and thus overestimating or underestimating according
                   8398:    * to the curvature of the survival function. If, for the same date, we 
                   8399:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   8400:    * to compare the new estimate of Life expectancy with the same linear 
                   8401:    * hypothesis. A more precise result, taking into account a more precise
                   8402:    * curvature will be obtained if estepm is as small as stepm. */
                   8403: 
                   8404:   /* For example we decided to compute the life expectancy with the smallest unit */
                   8405:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   8406:      nhstepm is the number of hstepm from age to agelim 
                   8407:      nstepm is the number of stepm from age to agelin. 
                   8408:      Look at hpijx to understand the reason of that which relies in memory size
                   8409:      and note for a fixed period like estepm months */
                   8410:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   8411:      survival function given by stepm (the optimization length). Unfortunately it
                   8412:      means that if the survival funtion is printed only each two years of age and if
                   8413:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   8414:      results. So we changed our mind and took the option of the best precision.
                   8415:   */
                   8416:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   8417: 
                   8418:   /* If stepm=6 months */
                   8419:   /* nhstepm age range expressed in number of stepm */
                   8420:   agelim=AGESUP;
                   8421:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   8422:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   8423:   /* if (stepm >= YEARM) hstepm=1;*/
                   8424:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   8425:   
                   8426:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8427:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8428:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   8429:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   8430:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   8431:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   8432: 
                   8433:   for (age=bage; age<=fage; age ++){ 
                   8434:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   8435:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   8436:     /* if (stepm >= YEARM) hstepm=1;*/
                   8437:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  8438:                
1.126     brouard  8439:     /* If stepm=6 months */
                   8440:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   8441:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   8442:     
                   8443:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  8444:                
1.126     brouard  8445:     /* Computing  Variances of health expectancies */
                   8446:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   8447:        decrease memory allocation */
                   8448:     for(theta=1; theta <=npar; theta++){
                   8449:       for(i=1; i<=npar; i++){ 
1.222     brouard  8450:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   8451:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  8452:       }
1.235     brouard  8453:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   8454:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  8455:                        
1.126     brouard  8456:       for(j=1; j<= nlstate; j++){
1.222     brouard  8457:        for(i=1; i<=nlstate; i++){
                   8458:          for(h=0; h<=nhstepm-1; h++){
                   8459:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   8460:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   8461:          }
                   8462:        }
1.126     brouard  8463:       }
1.218     brouard  8464:                        
1.126     brouard  8465:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  8466:        for(h=0; h<=nhstepm-1; h++){
                   8467:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   8468:        }
1.126     brouard  8469:     }/* End theta */
                   8470:     
                   8471:     
                   8472:     for(h=0; h<=nhstepm-1; h++)
                   8473:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  8474:        for(theta=1; theta <=npar; theta++)
                   8475:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  8476:     
1.218     brouard  8477:                
1.222     brouard  8478:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  8479:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  8480:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  8481:                
1.222     brouard  8482:     printf("%d|",(int)age);fflush(stdout);
                   8483:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   8484:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  8485:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  8486:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   8487:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   8488:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   8489:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   8490:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  8491:       }
                   8492:     }
1.320     brouard  8493:     /* if((int)age ==50){ */
                   8494:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   8495:     /* } */
1.126     brouard  8496:     /* Computing expectancies */
1.235     brouard  8497:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  8498:     for(i=1; i<=nlstate;i++)
                   8499:       for(j=1; j<=nlstate;j++)
1.222     brouard  8500:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   8501:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  8502:                                        
1.222     brouard  8503:          /* 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  8504:                                        
1.222     brouard  8505:        }
1.269     brouard  8506: 
                   8507:     /* Standard deviation of expectancies ij */                
1.126     brouard  8508:     fprintf(ficresstdeij,"%3.0f",age );
                   8509:     for(i=1; i<=nlstate;i++){
                   8510:       eip=0.;
                   8511:       vip=0.;
                   8512:       for(j=1; j<=nlstate;j++){
1.222     brouard  8513:        eip += eij[i][j][(int)age];
                   8514:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   8515:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   8516:        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  8517:       }
                   8518:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   8519:     }
                   8520:     fprintf(ficresstdeij,"\n");
1.218     brouard  8521:                
1.269     brouard  8522:     /* Variance of expectancies ij */          
1.126     brouard  8523:     fprintf(ficrescveij,"%3.0f",age );
                   8524:     for(i=1; i<=nlstate;i++)
                   8525:       for(j=1; j<=nlstate;j++){
1.222     brouard  8526:        cptj= (j-1)*nlstate+i;
                   8527:        for(i2=1; i2<=nlstate;i2++)
                   8528:          for(j2=1; j2<=nlstate;j2++){
                   8529:            cptj2= (j2-1)*nlstate+i2;
                   8530:            if(cptj2 <= cptj)
                   8531:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   8532:          }
1.126     brouard  8533:       }
                   8534:     fprintf(ficrescveij,"\n");
1.218     brouard  8535:                
1.126     brouard  8536:   }
                   8537:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   8538:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   8539:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   8540:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   8541:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8542:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8543:   printf("\n");
                   8544:   fprintf(ficlog,"\n");
1.218     brouard  8545:        
1.126     brouard  8546:   free_vector(xm,1,npar);
                   8547:   free_vector(xp,1,npar);
                   8548:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   8549:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   8550:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   8551: }
1.218     brouard  8552:  
1.126     brouard  8553: /************ Variance ******************/
1.235     brouard  8554:  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  8555:  {
1.279     brouard  8556:    /** Variance of health expectancies 
                   8557:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   8558:     * double **newm;
                   8559:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   8560:     */
1.218     brouard  8561:   
                   8562:    /* int movingaverage(); */
                   8563:    double **dnewm,**doldm;
                   8564:    double **dnewmp,**doldmp;
                   8565:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  8566:    int first=0;
1.218     brouard  8567:    int k;
                   8568:    double *xp;
1.279     brouard  8569:    double **gp, **gm;  /**< for var eij */
                   8570:    double ***gradg, ***trgradg; /**< for var eij */
                   8571:    double **gradgp, **trgradgp; /**< for var p point j */
                   8572:    double *gpp, *gmp; /**< for var p point j */
                   8573:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  8574:    double ***p3mat;
                   8575:    double age,agelim, hf;
                   8576:    /* double ***mobaverage; */
                   8577:    int theta;
                   8578:    char digit[4];
                   8579:    char digitp[25];
                   8580: 
                   8581:    char fileresprobmorprev[FILENAMELENGTH];
                   8582: 
                   8583:    if(popbased==1){
                   8584:      if(mobilav!=0)
                   8585:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   8586:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   8587:    }
                   8588:    else 
                   8589:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  8590: 
1.218     brouard  8591:    /* if (mobilav!=0) { */
                   8592:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8593:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   8594:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   8595:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   8596:    /*   } */
                   8597:    /* } */
                   8598: 
                   8599:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   8600:    sprintf(digit,"%-d",ij);
                   8601:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   8602:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   8603:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   8604:    strcat(fileresprobmorprev,fileresu);
                   8605:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   8606:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   8607:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   8608:    }
                   8609:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   8610:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   8611:    pstamp(ficresprobmorprev);
                   8612:    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  8613:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.337     brouard  8614: 
                   8615:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
                   8616:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
                   8617:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   8618:    /* } */
                   8619:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
1.344     brouard  8620:      /* fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); */
1.337     brouard  8621:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  8622:    }
1.337     brouard  8623:    /* for(j=1;j<=cptcoveff;j++)  */
                   8624:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
1.238     brouard  8625:    fprintf(ficresprobmorprev,"\n");
                   8626: 
1.218     brouard  8627:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   8628:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   8629:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   8630:      for(i=1; i<=nlstate;i++)
                   8631:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   8632:    }  
                   8633:    fprintf(ficresprobmorprev,"\n");
                   8634:   
                   8635:    fprintf(ficgp,"\n# Routine varevsij");
                   8636:    fprintf(ficgp,"\nunset title \n");
                   8637:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   8638:    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");
                   8639:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  8640: 
1.218     brouard  8641:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   8642:    pstamp(ficresvij);
                   8643:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   8644:    if(popbased==1)
                   8645:      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);
                   8646:    else
                   8647:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   8648:    fprintf(ficresvij,"# Age");
                   8649:    for(i=1; i<=nlstate;i++)
                   8650:      for(j=1; j<=nlstate;j++)
                   8651:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   8652:    fprintf(ficresvij,"\n");
                   8653: 
                   8654:    xp=vector(1,npar);
                   8655:    dnewm=matrix(1,nlstate,1,npar);
                   8656:    doldm=matrix(1,nlstate,1,nlstate);
                   8657:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   8658:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   8659: 
                   8660:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   8661:    gpp=vector(nlstate+1,nlstate+ndeath);
                   8662:    gmp=vector(nlstate+1,nlstate+ndeath);
                   8663:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  8664:   
1.218     brouard  8665:    if(estepm < stepm){
                   8666:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   8667:    }
                   8668:    else  hstepm=estepm;   
                   8669:    /* For example we decided to compute the life expectancy with the smallest unit */
                   8670:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   8671:       nhstepm is the number of hstepm from age to agelim 
                   8672:       nstepm is the number of stepm from age to agelim. 
                   8673:       Look at function hpijx to understand why because of memory size limitations, 
                   8674:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   8675:       survival function given by stepm (the optimization length). Unfortunately it
                   8676:       means that if the survival funtion is printed every two years of age and if
                   8677:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   8678:       results. So we changed our mind and took the option of the best precision.
                   8679:    */
                   8680:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   8681:    agelim = AGESUP;
                   8682:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   8683:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   8684:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   8685:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8686:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   8687:      gp=matrix(0,nhstepm,1,nlstate);
                   8688:      gm=matrix(0,nhstepm,1,nlstate);
                   8689:                
                   8690:                
                   8691:      for(theta=1; theta <=npar; theta++){
                   8692:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   8693:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   8694:        }
1.279     brouard  8695:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   8696:        * returns into prlim .
1.288     brouard  8697:        */
1.242     brouard  8698:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  8699: 
                   8700:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  8701:        if (popbased==1) {
                   8702:         if(mobilav ==0){
                   8703:           for(i=1; i<=nlstate;i++)
                   8704:             prlim[i][i]=probs[(int)age][i][ij];
                   8705:         }else{ /* mobilav */ 
                   8706:           for(i=1; i<=nlstate;i++)
                   8707:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   8708:         }
                   8709:        }
1.295     brouard  8710:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  8711:        */                      
                   8712:        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  8713:        /**< 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  8714:        * at horizon h in state j including mortality.
                   8715:        */
1.218     brouard  8716:        for(j=1; j<= nlstate; j++){
                   8717:         for(h=0; h<=nhstepm; h++){
                   8718:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   8719:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   8720:         }
                   8721:        }
1.279     brouard  8722:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  8723:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  8724:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  8725:        */
                   8726:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   8727:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   8728:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  8729:        }
                   8730:        
                   8731:        /* Again with minus shift */
1.218     brouard  8732:                        
                   8733:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   8734:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  8735: 
1.242     brouard  8736:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  8737:                        
                   8738:        if (popbased==1) {
                   8739:         if(mobilav ==0){
                   8740:           for(i=1; i<=nlstate;i++)
                   8741:             prlim[i][i]=probs[(int)age][i][ij];
                   8742:         }else{ /* mobilav */ 
                   8743:           for(i=1; i<=nlstate;i++)
                   8744:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   8745:         }
                   8746:        }
                   8747:                        
1.235     brouard  8748:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  8749:                        
                   8750:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   8751:         for(h=0; h<=nhstepm; h++){
                   8752:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   8753:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   8754:         }
                   8755:        }
                   8756:        /* This for computing probability of death (h=1 means
                   8757:          computed over hstepm matrices product = hstepm*stepm months) 
                   8758:          as a weighted average of prlim.
                   8759:        */
                   8760:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   8761:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   8762:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   8763:        }    
1.279     brouard  8764:        /* end shifting computations */
                   8765: 
                   8766:        /**< Computing gradient matrix at horizon h 
                   8767:        */
1.218     brouard  8768:        for(j=1; j<= nlstate; j++) /* vareij */
                   8769:         for(h=0; h<=nhstepm; h++){
                   8770:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   8771:         }
1.279     brouard  8772:        /**< Gradient of overall mortality p.3 (or p.j) 
                   8773:        */
                   8774:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  8775:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   8776:        }
                   8777:                        
                   8778:      } /* End theta */
1.279     brouard  8779:      
                   8780:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  8781:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   8782:                
                   8783:      for(h=0; h<=nhstepm; h++) /* veij */
                   8784:        for(j=1; j<=nlstate;j++)
                   8785:         for(theta=1; theta <=npar; theta++)
                   8786:           trgradg[h][j][theta]=gradg[h][theta][j];
                   8787:                
                   8788:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   8789:        for(theta=1; theta <=npar; theta++)
                   8790:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  8791:      /**< as well as its transposed matrix 
                   8792:       */               
1.218     brouard  8793:                
                   8794:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   8795:      for(i=1;i<=nlstate;i++)
                   8796:        for(j=1;j<=nlstate;j++)
                   8797:         vareij[i][j][(int)age] =0.;
1.279     brouard  8798: 
                   8799:      /* Computing trgradg by matcov by gradg at age and summing over h
                   8800:       * and k (nhstepm) formula 15 of article
                   8801:       * Lievre-Brouard-Heathcote
                   8802:       */
                   8803:      
1.218     brouard  8804:      for(h=0;h<=nhstepm;h++){
                   8805:        for(k=0;k<=nhstepm;k++){
                   8806:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   8807:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   8808:         for(i=1;i<=nlstate;i++)
                   8809:           for(j=1;j<=nlstate;j++)
                   8810:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   8811:        }
                   8812:      }
                   8813:                
1.279     brouard  8814:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
1.360   ! brouard  8815:       * p.j overall mortality formula 19 but computed directly because
1.279     brouard  8816:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   8817:       * wix is independent of theta.
                   8818:       */
1.218     brouard  8819:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   8820:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   8821:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   8822:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   8823:         varppt[j][i]=doldmp[j][i];
                   8824:      /* end ppptj */
                   8825:      /*  x centered again */
                   8826:                
1.242     brouard  8827:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  8828:                
                   8829:      if (popbased==1) {
                   8830:        if(mobilav ==0){
                   8831:         for(i=1; i<=nlstate;i++)
                   8832:           prlim[i][i]=probs[(int)age][i][ij];
                   8833:        }else{ /* mobilav */ 
                   8834:         for(i=1; i<=nlstate;i++)
                   8835:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   8836:        }
                   8837:      }
                   8838:                
                   8839:      /* This for computing probability of death (h=1 means
                   8840:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   8841:        as a weighted average of prlim.
                   8842:      */
1.235     brouard  8843:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  8844:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   8845:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   8846:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   8847:      }    
                   8848:      /* end probability of death */
                   8849:                
                   8850:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   8851:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   8852:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   8853:        for(i=1; i<=nlstate;i++){
                   8854:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   8855:        }
                   8856:      } 
                   8857:      fprintf(ficresprobmorprev,"\n");
                   8858:                
                   8859:      fprintf(ficresvij,"%.0f ",age );
                   8860:      for(i=1; i<=nlstate;i++)
                   8861:        for(j=1; j<=nlstate;j++){
                   8862:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   8863:        }
                   8864:      fprintf(ficresvij,"\n");
                   8865:      free_matrix(gp,0,nhstepm,1,nlstate);
                   8866:      free_matrix(gm,0,nhstepm,1,nlstate);
                   8867:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   8868:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   8869:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8870:    } /* End age */
                   8871:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   8872:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   8873:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   8874:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   8875:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   8876:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   8877:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   8878:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   8879:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   8880:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   8881:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   8882:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   8883:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   8884:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   8885:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   8886:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   8887:    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);
                   8888:    /*  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  8889:     */
1.218     brouard  8890:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   8891:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  8892: 
1.218     brouard  8893:    free_vector(xp,1,npar);
                   8894:    free_matrix(doldm,1,nlstate,1,nlstate);
                   8895:    free_matrix(dnewm,1,nlstate,1,npar);
                   8896:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   8897:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   8898:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   8899:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8900:    fclose(ficresprobmorprev);
                   8901:    fflush(ficgp);
                   8902:    fflush(fichtm); 
                   8903:  }  /* end varevsij */
1.126     brouard  8904: 
                   8905: /************ Variance of prevlim ******************/
1.269     brouard  8906:  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  8907: {
1.205     brouard  8908:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  8909:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  8910: 
1.268     brouard  8911:   double **dnewmpar,**doldm;
1.126     brouard  8912:   int i, j, nhstepm, hstepm;
                   8913:   double *xp;
                   8914:   double *gp, *gm;
                   8915:   double **gradg, **trgradg;
1.208     brouard  8916:   double **mgm, **mgp;
1.126     brouard  8917:   double age,agelim;
                   8918:   int theta;
                   8919:   
                   8920:   pstamp(ficresvpl);
1.288     brouard  8921:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  8922:   fprintf(ficresvpl,"# Age ");
                   8923:   if(nresult >=1)
                   8924:     fprintf(ficresvpl," Result# ");
1.126     brouard  8925:   for(i=1; i<=nlstate;i++)
                   8926:       fprintf(ficresvpl," %1d-%1d",i,i);
                   8927:   fprintf(ficresvpl,"\n");
                   8928: 
                   8929:   xp=vector(1,npar);
1.268     brouard  8930:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  8931:   doldm=matrix(1,nlstate,1,nlstate);
                   8932:   
                   8933:   hstepm=1*YEARM; /* Every year of age */
                   8934:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   8935:   agelim = AGESUP;
                   8936:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   8937:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   8938:     if (stepm >= YEARM) hstepm=1;
                   8939:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   8940:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  8941:     mgp=matrix(1,npar,1,nlstate);
                   8942:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  8943:     gp=vector(1,nlstate);
                   8944:     gm=vector(1,nlstate);
                   8945: 
                   8946:     for(theta=1; theta <=npar; theta++){
                   8947:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   8948:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   8949:       }
1.288     brouard  8950:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   8951:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   8952:       /* else */
                   8953:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  8954:       for(i=1;i<=nlstate;i++){
1.126     brouard  8955:        gp[i] = prlim[i][i];
1.208     brouard  8956:        mgp[theta][i] = prlim[i][i];
                   8957:       }
1.126     brouard  8958:       for(i=1; i<=npar; i++) /* Computes gradient */
                   8959:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  8960:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   8961:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   8962:       /* else */
                   8963:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  8964:       for(i=1;i<=nlstate;i++){
1.126     brouard  8965:        gm[i] = prlim[i][i];
1.208     brouard  8966:        mgm[theta][i] = prlim[i][i];
                   8967:       }
1.126     brouard  8968:       for(i=1;i<=nlstate;i++)
                   8969:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  8970:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  8971:     } /* End theta */
                   8972: 
                   8973:     trgradg =matrix(1,nlstate,1,npar);
                   8974: 
                   8975:     for(j=1; j<=nlstate;j++)
                   8976:       for(theta=1; theta <=npar; theta++)
                   8977:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  8978:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   8979:     /*   printf("\nmgm mgp %d ",(int)age); */
                   8980:     /*   for(j=1; j<=nlstate;j++){ */
                   8981:     /*         printf(" %d ",j); */
                   8982:     /*         for(theta=1; theta <=npar; theta++) */
                   8983:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   8984:     /*         printf("\n "); */
                   8985:     /*   } */
                   8986:     /* } */
                   8987:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   8988:     /*   printf("\n gradg %d ",(int)age); */
                   8989:     /*   for(j=1; j<=nlstate;j++){ */
                   8990:     /*         printf("%d ",j); */
                   8991:     /*         for(theta=1; theta <=npar; theta++) */
                   8992:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   8993:     /*         printf("\n "); */
                   8994:     /*   } */
                   8995:     /* } */
1.126     brouard  8996: 
                   8997:     for(i=1;i<=nlstate;i++)
                   8998:       varpl[i][(int)age] =0.;
1.209     brouard  8999:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  9000:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   9001:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  9002:     }else{
1.268     brouard  9003:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   9004:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  9005:     }
1.126     brouard  9006:     for(i=1;i<=nlstate;i++)
                   9007:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   9008: 
                   9009:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  9010:     if(nresult >=1)
                   9011:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  9012:     for(i=1; i<=nlstate;i++){
1.126     brouard  9013:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  9014:       /* for(j=1;j<=nlstate;j++) */
                   9015:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   9016:     }
1.126     brouard  9017:     fprintf(ficresvpl,"\n");
                   9018:     free_vector(gp,1,nlstate);
                   9019:     free_vector(gm,1,nlstate);
1.208     brouard  9020:     free_matrix(mgm,1,npar,1,nlstate);
                   9021:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  9022:     free_matrix(gradg,1,npar,1,nlstate);
                   9023:     free_matrix(trgradg,1,nlstate,1,npar);
                   9024:   } /* End age */
                   9025: 
                   9026:   free_vector(xp,1,npar);
                   9027:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  9028:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   9029: 
                   9030: }
                   9031: 
                   9032: 
                   9033: /************ Variance of backprevalence limit ******************/
1.269     brouard  9034:  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  9035: {
                   9036:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   9037:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   9038: 
                   9039:   double **dnewmpar,**doldm;
                   9040:   int i, j, nhstepm, hstepm;
                   9041:   double *xp;
                   9042:   double *gp, *gm;
                   9043:   double **gradg, **trgradg;
                   9044:   double **mgm, **mgp;
                   9045:   double age,agelim;
                   9046:   int theta;
                   9047:   
                   9048:   pstamp(ficresvbl);
                   9049:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   9050:   fprintf(ficresvbl,"# Age ");
                   9051:   if(nresult >=1)
                   9052:     fprintf(ficresvbl," Result# ");
                   9053:   for(i=1; i<=nlstate;i++)
                   9054:       fprintf(ficresvbl," %1d-%1d",i,i);
                   9055:   fprintf(ficresvbl,"\n");
                   9056: 
                   9057:   xp=vector(1,npar);
                   9058:   dnewmpar=matrix(1,nlstate,1,npar);
                   9059:   doldm=matrix(1,nlstate,1,nlstate);
                   9060:   
                   9061:   hstepm=1*YEARM; /* Every year of age */
                   9062:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   9063:   agelim = AGEINF;
                   9064:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   9065:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   9066:     if (stepm >= YEARM) hstepm=1;
                   9067:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   9068:     gradg=matrix(1,npar,1,nlstate);
                   9069:     mgp=matrix(1,npar,1,nlstate);
                   9070:     mgm=matrix(1,npar,1,nlstate);
                   9071:     gp=vector(1,nlstate);
                   9072:     gm=vector(1,nlstate);
                   9073: 
                   9074:     for(theta=1; theta <=npar; theta++){
                   9075:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   9076:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   9077:       }
                   9078:       if(mobilavproj > 0 )
                   9079:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   9080:       else
                   9081:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   9082:       for(i=1;i<=nlstate;i++){
                   9083:        gp[i] = bprlim[i][i];
                   9084:        mgp[theta][i] = bprlim[i][i];
                   9085:       }
                   9086:      for(i=1; i<=npar; i++) /* Computes gradient */
                   9087:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   9088:        if(mobilavproj > 0 )
                   9089:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   9090:        else
                   9091:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   9092:       for(i=1;i<=nlstate;i++){
                   9093:        gm[i] = bprlim[i][i];
                   9094:        mgm[theta][i] = bprlim[i][i];
                   9095:       }
                   9096:       for(i=1;i<=nlstate;i++)
                   9097:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   9098:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   9099:     } /* End theta */
                   9100: 
                   9101:     trgradg =matrix(1,nlstate,1,npar);
                   9102: 
                   9103:     for(j=1; j<=nlstate;j++)
                   9104:       for(theta=1; theta <=npar; theta++)
                   9105:        trgradg[j][theta]=gradg[theta][j];
                   9106:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   9107:     /*   printf("\nmgm mgp %d ",(int)age); */
                   9108:     /*   for(j=1; j<=nlstate;j++){ */
                   9109:     /*         printf(" %d ",j); */
                   9110:     /*         for(theta=1; theta <=npar; theta++) */
                   9111:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   9112:     /*         printf("\n "); */
                   9113:     /*   } */
                   9114:     /* } */
                   9115:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   9116:     /*   printf("\n gradg %d ",(int)age); */
                   9117:     /*   for(j=1; j<=nlstate;j++){ */
                   9118:     /*         printf("%d ",j); */
                   9119:     /*         for(theta=1; theta <=npar; theta++) */
                   9120:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   9121:     /*         printf("\n "); */
                   9122:     /*   } */
                   9123:     /* } */
                   9124: 
                   9125:     for(i=1;i<=nlstate;i++)
                   9126:       varbpl[i][(int)age] =0.;
                   9127:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   9128:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   9129:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   9130:     }else{
                   9131:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   9132:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   9133:     }
                   9134:     for(i=1;i<=nlstate;i++)
                   9135:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   9136: 
                   9137:     fprintf(ficresvbl,"%.0f ",age );
                   9138:     if(nresult >=1)
                   9139:       fprintf(ficresvbl,"%d ",nres );
                   9140:     for(i=1; i<=nlstate;i++)
                   9141:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   9142:     fprintf(ficresvbl,"\n");
                   9143:     free_vector(gp,1,nlstate);
                   9144:     free_vector(gm,1,nlstate);
                   9145:     free_matrix(mgm,1,npar,1,nlstate);
                   9146:     free_matrix(mgp,1,npar,1,nlstate);
                   9147:     free_matrix(gradg,1,npar,1,nlstate);
                   9148:     free_matrix(trgradg,1,nlstate,1,npar);
                   9149:   } /* End age */
                   9150: 
                   9151:   free_vector(xp,1,npar);
                   9152:   free_matrix(doldm,1,nlstate,1,npar);
                   9153:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  9154: 
                   9155: }
                   9156: 
                   9157: /************ Variance of one-step probabilities  ******************/
                   9158: 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  9159:  {
                   9160:    int i, j=0,  k1, l1, tj;
                   9161:    int k2, l2, j1,  z1;
                   9162:    int k=0, l;
                   9163:    int first=1, first1, first2;
1.326     brouard  9164:    int nres=0; /* New */
1.222     brouard  9165:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   9166:    double **dnewm,**doldm;
                   9167:    double *xp;
                   9168:    double *gp, *gm;
                   9169:    double **gradg, **trgradg;
                   9170:    double **mu;
                   9171:    double age, cov[NCOVMAX+1];
                   9172:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   9173:    int theta;
                   9174:    char fileresprob[FILENAMELENGTH];
                   9175:    char fileresprobcov[FILENAMELENGTH];
                   9176:    char fileresprobcor[FILENAMELENGTH];
                   9177:    double ***varpij;
                   9178: 
                   9179:    strcpy(fileresprob,"PROB_"); 
1.356     brouard  9180:    strcat(fileresprob,fileresu);
1.222     brouard  9181:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   9182:      printf("Problem with resultfile: %s\n", fileresprob);
                   9183:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   9184:    }
                   9185:    strcpy(fileresprobcov,"PROBCOV_"); 
                   9186:    strcat(fileresprobcov,fileresu);
                   9187:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   9188:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   9189:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   9190:    }
                   9191:    strcpy(fileresprobcor,"PROBCOR_"); 
                   9192:    strcat(fileresprobcor,fileresu);
                   9193:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   9194:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   9195:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   9196:    }
                   9197:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   9198:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   9199:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   9200:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   9201:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   9202:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   9203:    pstamp(ficresprob);
                   9204:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   9205:    fprintf(ficresprob,"# Age");
                   9206:    pstamp(ficresprobcov);
                   9207:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   9208:    fprintf(ficresprobcov,"# Age");
                   9209:    pstamp(ficresprobcor);
                   9210:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   9211:    fprintf(ficresprobcor,"# Age");
1.126     brouard  9212: 
                   9213: 
1.222     brouard  9214:    for(i=1; i<=nlstate;i++)
                   9215:      for(j=1; j<=(nlstate+ndeath);j++){
                   9216:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   9217:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   9218:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   9219:      }  
                   9220:    /* fprintf(ficresprob,"\n");
                   9221:       fprintf(ficresprobcov,"\n");
                   9222:       fprintf(ficresprobcor,"\n");
                   9223:    */
                   9224:    xp=vector(1,npar);
                   9225:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   9226:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   9227:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   9228:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   9229:    first=1;
                   9230:    fprintf(ficgp,"\n# Routine varprob");
                   9231:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   9232:    fprintf(fichtm,"\n");
                   9233: 
1.288     brouard  9234:    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  9235:    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);
                   9236:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  9237: and drawn. It helps understanding how is the covariance between two incidences.\
                   9238:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  9239:    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  9240: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   9241: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   9242: standard deviations wide on each axis. <br>\
                   9243:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   9244:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   9245: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   9246: 
1.222     brouard  9247:    cov[1]=1;
                   9248:    /* tj=cptcoveff; */
1.225     brouard  9249:    tj = (int) pow(2,cptcoveff);
1.222     brouard  9250:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   9251:    j1=0;
1.332     brouard  9252: 
                   9253:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   9254:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.342     brouard  9255:      /* 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  9256:      if(tj != 1 && TKresult[nres]!= j1)
                   9257:        continue;
                   9258: 
                   9259:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   9260:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   9261:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  9262:      if  (cptcovn>0) {
1.334     brouard  9263:        fprintf(ficresprob, "\n#********** Variable ");
                   9264:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   9265:        fprintf(ficgp, "\n#********** Variable ");
                   9266:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   9267:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   9268: 
                   9269:        /* Including quantitative variables of the resultline to be done */
                   9270:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
1.343     brouard  9271:         /* printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model); */
1.338     brouard  9272:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   9273:         /* 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  9274:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   9275:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   9276:             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  */
                   9277:             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  */
                   9278:             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  */
                   9279:             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  */
                   9280:             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  */
                   9281:             fprintf(ficresprob,"fixed ");
                   9282:             fprintf(ficresprobcov,"fixed ");
                   9283:             fprintf(ficgp,"fixed ");
                   9284:             fprintf(fichtmcov,"fixed ");
                   9285:             fprintf(ficresprobcor,"fixed ");
                   9286:           }else{
                   9287:             fprintf(ficresprob,"varyi ");
                   9288:             fprintf(ficresprobcov,"varyi ");
                   9289:             fprintf(ficgp,"varyi ");
                   9290:             fprintf(fichtmcov,"varyi ");
                   9291:             fprintf(ficresprobcor,"varyi ");
                   9292:           }
                   9293:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   9294:           /* For each selected (single) quantitative value */
1.337     brouard  9295:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
1.334     brouard  9296:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   9297:             fprintf(ficresprob,"fixed ");
                   9298:             fprintf(ficresprobcov,"fixed ");
                   9299:             fprintf(ficgp,"fixed ");
                   9300:             fprintf(fichtmcov,"fixed ");
                   9301:             fprintf(ficresprobcor,"fixed ");
                   9302:           }else{
                   9303:             fprintf(ficresprob,"varyi ");
                   9304:             fprintf(ficresprobcov,"varyi ");
                   9305:             fprintf(ficgp,"varyi ");
                   9306:             fprintf(fichtmcov,"varyi ");
                   9307:             fprintf(ficresprobcor,"varyi ");
                   9308:           }
                   9309:         }else{
                   9310:           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 */
                   9311:           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 */
                   9312:           exit(1);
                   9313:         }
                   9314:        } /* End loop on variable of this resultline */
                   9315:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  9316:        fprintf(ficresprob, "**********\n#\n");
                   9317:        fprintf(ficresprobcov, "**********\n#\n");
                   9318:        fprintf(ficgp, "**********\n#\n");
                   9319:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   9320:        fprintf(ficresprobcor, "**********\n#");    
                   9321:        if(invalidvarcomb[j1]){
                   9322:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   9323:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   9324:         continue;
                   9325:        }
                   9326:      }
                   9327:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   9328:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   9329:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   9330:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  9331:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  9332:        cov[2]=age;
                   9333:        if(nagesqr==1)
                   9334:         cov[3]= age*age;
1.334     brouard  9335:        /* New code end of combination but for each resultline */
                   9336:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  9337:         if(Typevar[k1]==1 || Typevar[k1] ==3){ /* A product with age */
1.334     brouard  9338:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  9339:         }else{
1.334     brouard  9340:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  9341:         }
1.334     brouard  9342:        }/* End of loop on model equation */
                   9343: /* Old code */
                   9344:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   9345:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   9346:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   9347:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   9348:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   9349:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   9350:        /*                                                                  * 1  1 1 1 1 */
                   9351:        /*                                                                  * 2  2 1 1 1 */
                   9352:        /*                                                                  * 3  1 2 1 1 */
                   9353:        /*                                                                  *\/ */
                   9354:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   9355:        /* } */
                   9356:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   9357:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   9358:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   9359:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   9360:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   9361:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   9362:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   9363:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   9364:        /*         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]); */
                   9365:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   9366:        /*         /\* exit(1); *\/ */
                   9367:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   9368:        /*       } */
                   9369:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   9370:        /* } */
                   9371:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   9372:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   9373:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   9374:        /*           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]])]; */
                   9375:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   9376:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   9377:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   9378:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   9379:        /*         } */
                   9380:        /*       }else{ */
                   9381:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   9382:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   9383:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   9384:        /*         }else{ */
                   9385:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   9386:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   9387:        /*         } */
                   9388:        /*       } */
                   9389:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   9390:        /* } */                 
1.326     brouard  9391: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  9392:        for(theta=1; theta <=npar; theta++){
                   9393:         for(i=1; i<=npar; i++)
                   9394:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  9395:                                
1.222     brouard  9396:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  9397:                                
1.222     brouard  9398:         k=0;
                   9399:         for(i=1; i<= (nlstate); i++){
                   9400:           for(j=1; j<=(nlstate+ndeath);j++){
                   9401:             k=k+1;
                   9402:             gp[k]=pmmij[i][j];
                   9403:           }
                   9404:         }
1.220     brouard  9405:                                
1.222     brouard  9406:         for(i=1; i<=npar; i++)
                   9407:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  9408:                                
1.222     brouard  9409:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   9410:         k=0;
                   9411:         for(i=1; i<=(nlstate); i++){
                   9412:           for(j=1; j<=(nlstate+ndeath);j++){
                   9413:             k=k+1;
                   9414:             gm[k]=pmmij[i][j];
                   9415:           }
                   9416:         }
1.220     brouard  9417:                                
1.222     brouard  9418:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   9419:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   9420:        }
1.126     brouard  9421: 
1.222     brouard  9422:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   9423:         for(theta=1; theta <=npar; theta++)
                   9424:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  9425:                        
1.222     brouard  9426:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   9427:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  9428:                        
1.222     brouard  9429:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  9430:                        
1.222     brouard  9431:        k=0;
                   9432:        for(i=1; i<=(nlstate); i++){
                   9433:         for(j=1; j<=(nlstate+ndeath);j++){
                   9434:           k=k+1;
                   9435:           mu[k][(int) age]=pmmij[i][j];
                   9436:         }
                   9437:        }
                   9438:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   9439:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   9440:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  9441:                        
1.222     brouard  9442:        /*printf("\n%d ",(int)age);
                   9443:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   9444:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   9445:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   9446:         }*/
1.220     brouard  9447:                        
1.222     brouard  9448:        fprintf(ficresprob,"\n%d ",(int)age);
                   9449:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   9450:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  9451:                        
1.222     brouard  9452:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   9453:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   9454:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   9455:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   9456:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   9457:        }
                   9458:        i=0;
                   9459:        for (k=1; k<=(nlstate);k++){
                   9460:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   9461:           i++;
                   9462:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   9463:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   9464:           for (j=1; j<=i;j++){
                   9465:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   9466:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   9467:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   9468:           }
                   9469:         }
                   9470:        }/* end of loop for state */
                   9471:      } /* end of loop for age */
                   9472:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   9473:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   9474:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   9475:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   9476:     
                   9477:      /* Confidence intervalle of pij  */
                   9478:      /*
                   9479:        fprintf(ficgp,"\nunset parametric;unset label");
                   9480:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   9481:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   9482:        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);
                   9483:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   9484:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   9485:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   9486:      */
                   9487:                
                   9488:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   9489:      first1=1;first2=2;
                   9490:      for (k2=1; k2<=(nlstate);k2++){
                   9491:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   9492:         if(l2==k2) continue;
                   9493:         j=(k2-1)*(nlstate+ndeath)+l2;
                   9494:         for (k1=1; k1<=(nlstate);k1++){
                   9495:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   9496:             if(l1==k1) continue;
                   9497:             i=(k1-1)*(nlstate+ndeath)+l1;
                   9498:             if(i<=j) continue;
                   9499:             for (age=bage; age<=fage; age ++){ 
                   9500:               if ((int)age %5==0){
                   9501:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   9502:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   9503:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   9504:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   9505:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   9506:                 c12=cv12/sqrt(v1*v2);
                   9507:                 /* Computing eigen value of matrix of covariance */
                   9508:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   9509:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   9510:                 if ((lc2 <0) || (lc1 <0) ){
                   9511:                   if(first2==1){
                   9512:                     first1=0;
                   9513:                     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);
                   9514:                   }
                   9515:                   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);
                   9516:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   9517:                   /* lc2=fabs(lc2); */
                   9518:                 }
1.220     brouard  9519:                                                                
1.222     brouard  9520:                 /* Eigen vectors */
1.280     brouard  9521:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   9522:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   9523:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   9524:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   9525:                 }else
                   9526:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  9527:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   9528:                 v21=(lc1-v1)/cv12*v11;
                   9529:                 v12=-v21;
                   9530:                 v22=v11;
                   9531:                 tnalp=v21/v11;
                   9532:                 if(first1==1){
                   9533:                   first1=0;
                   9534:                   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);
                   9535:                 }
                   9536:                 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);
                   9537:                 /*printf(fignu*/
                   9538:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   9539:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   9540:                 if(first==1){
                   9541:                   first=0;
                   9542:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   9543:                   fprintf(ficgp,"\nset parametric;unset label");
                   9544:                   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);
                   9545:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  9546:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  9547:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  9548: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  9549:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   9550:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   9551:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   9552:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   9553:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   9554:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   9555:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   9556:                   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  9557:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   9558:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  9559:                 }else{
                   9560:                   first=0;
                   9561:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   9562:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   9563:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   9564:                   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  9565:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   9566:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  9567:                 }/* if first */
                   9568:               } /* age mod 5 */
                   9569:             } /* end loop age */
                   9570:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   9571:             first=1;
                   9572:           } /*l12 */
                   9573:         } /* k12 */
                   9574:        } /*l1 */
                   9575:      }/* k1 */
1.332     brouard  9576:    }  /* loop on combination of covariates j1 */
1.326     brouard  9577:    } /* loop on nres */
1.222     brouard  9578:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   9579:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   9580:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   9581:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   9582:    free_vector(xp,1,npar);
                   9583:    fclose(ficresprob);
                   9584:    fclose(ficresprobcov);
                   9585:    fclose(ficresprobcor);
                   9586:    fflush(ficgp);
                   9587:    fflush(fichtmcov);
                   9588:  }
1.126     brouard  9589: 
                   9590: 
                   9591: /******************* Printing html file ***********/
1.201     brouard  9592: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  9593:                  int lastpass, int stepm, int weightopt, char model[],\
                   9594:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  9595:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   9596:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   9597:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.359     brouard  9598:   int jj1, k1, cpt, nres;
1.319     brouard  9599:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  9600:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   9601:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   9602: </ul>");
1.319     brouard  9603: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   9604: /* </ul>", model); */
1.214     brouard  9605:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   9606:    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",
                   9607:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  9608:    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  9609:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   9610:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  9611:    fprintf(fichtm,"\
                   9612:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  9613:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  9614:    fprintf(fichtm,"\
1.217     brouard  9615:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   9616:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   9617:    fprintf(fichtm,"\
1.288     brouard  9618:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  9619:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  9620:    fprintf(fichtm,"\
1.288     brouard  9621:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  9622:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   9623:    fprintf(fichtm,"\
1.211     brouard  9624:  - (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  9625:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  9626:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  9627:    if(prevfcast==1){
                   9628:      fprintf(fichtm,"\
                   9629:  - Prevalence projections by age and states:                           \
1.201     brouard  9630:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  9631:    }
1.126     brouard  9632: 
                   9633: 
1.225     brouard  9634:    m=pow(2,cptcoveff);
1.222     brouard  9635:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  9636: 
1.317     brouard  9637:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  9638: 
                   9639:    jj1=0;
                   9640: 
                   9641:    fprintf(fichtm," \n<ul>");
1.337     brouard  9642:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9643:      /* k1=nres; */
1.338     brouard  9644:      k1=TKresult[nres];
                   9645:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
1.337     brouard  9646:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   9647:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   9648:    /*     continue; */
1.264     brouard  9649:      jj1++;
                   9650:      if (cptcovn > 0) {
                   9651:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
1.337     brouard  9652:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   9653:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  9654:        }
1.337     brouard  9655:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   9656:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   9657:        /* } */
                   9658:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9659:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   9660:        /* } */
1.264     brouard  9661:        fprintf(fichtm,"\">");
                   9662:        
                   9663:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   9664:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  9665:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9666:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  9667:        }
1.337     brouard  9668:        /* fprintf(fichtm,"************ Results for covariates"); */
                   9669:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   9670:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   9671:        /* } */
                   9672:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9673:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   9674:        /* } */
1.264     brouard  9675:        if(invalidvarcomb[k1]){
                   9676:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   9677:         continue;
                   9678:        }
                   9679:        fprintf(fichtm,"</a></li>");
                   9680:      } /* cptcovn >0 */
                   9681:    }
1.317     brouard  9682:    fprintf(fichtm," \n</ul>");
1.264     brouard  9683: 
1.222     brouard  9684:    jj1=0;
1.237     brouard  9685: 
1.337     brouard  9686:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9687:      /* k1=nres; */
1.338     brouard  9688:      k1=TKresult[nres];
                   9689:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9690:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   9691:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   9692:    /*     continue; */
1.220     brouard  9693: 
1.222     brouard  9694:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   9695:      jj1++;
                   9696:      if (cptcovn > 0) {
1.264     brouard  9697:        fprintf(fichtm,"\n<p><a name=\"rescov");
1.337     brouard  9698:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9699:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  9700:        }
1.337     brouard  9701:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9702:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   9703:        /* } */
1.264     brouard  9704:        fprintf(fichtm,"\"</a>");
                   9705:  
1.222     brouard  9706:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  9707:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9708:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   9709:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  9710:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   9711:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  9712:        }
1.230     brouard  9713:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.338     brouard  9714:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  9715:        if(invalidvarcomb[k1]){
                   9716:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   9717:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   9718:         continue;
                   9719:        }
                   9720:      }
                   9721:      /* aij, bij */
1.259     brouard  9722:      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  9723: <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  9724:      /* Pij */
1.241     brouard  9725:      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> \
                   9726: <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  9727:      /* Quasi-incidences */
                   9728:      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  9729:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  9730:  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  9731: 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> \
                   9732: <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  9733:      /* Survival functions (period) in state j */
                   9734:      for(cpt=1; cpt<=nlstate;cpt++){
1.359     brouard  9735:        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  9736:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   9737:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  9738:      }
                   9739:      /* State specific survival functions (period) */
                   9740:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  9741:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
1.359     brouard  9742:  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  9743:  <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);
                   9744:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   9745:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  9746:      }
1.288     brouard  9747:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  9748:      for(cpt=1; cpt<=nlstate;cpt++){
1.359     brouard  9749:        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  9750:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
1.329     brouard  9751:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  9752:      }
1.296     brouard  9753:      if(prevbcast==1){
1.288     brouard  9754:        /* Backward prevalence in each health state */
1.222     brouard  9755:        for(cpt=1; cpt<=nlstate;cpt++){
1.338     brouard  9756:         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);
                   9757:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
                   9758:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  9759:        }
1.217     brouard  9760:      }
1.222     brouard  9761:      if(prevfcast==1){
1.288     brouard  9762:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  9763:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  9764:         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);
                   9765:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   9766:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   9767:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  9768:        }
                   9769:      }
1.296     brouard  9770:      if(prevbcast==1){
1.268     brouard  9771:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   9772:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  9773:         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  9774:  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 \
                   9775:  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  9776: 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);
                   9777:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   9778:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  9779:        }
                   9780:      }
1.220     brouard  9781:         
1.222     brouard  9782:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  9783:        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);
                   9784:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   9785:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  9786:      }
                   9787:      /* } /\* end i1 *\/ */
1.337     brouard  9788:    }/* End k1=nres */
1.222     brouard  9789:    fprintf(fichtm,"</ul>");
1.126     brouard  9790: 
1.222     brouard  9791:    fprintf(fichtm,"\
1.126     brouard  9792: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  9793:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  9794:  - 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  9795: But because parameters are usually highly correlated (a higher incidence of disability \
                   9796: and a higher incidence of recovery can give very close observed transition) it might \
                   9797: be very useful to look not only at linear confidence intervals estimated from the \
                   9798: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   9799: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   9800: covariance matrix of the one-step probabilities. \
                   9801: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  9802: 
1.222     brouard  9803:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   9804:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   9805:    fprintf(fichtm,"\
1.126     brouard  9806:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  9807:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  9808: 
1.222     brouard  9809:    fprintf(fichtm,"\
1.126     brouard  9810:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  9811:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   9812:    fprintf(fichtm,"\
1.126     brouard  9813:  - 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): \
                   9814:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  9815:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  9816:    fprintf(fichtm,"\
1.126     brouard  9817:  - (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): \
                   9818:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  9819:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  9820:    fprintf(fichtm,"\
1.288     brouard  9821:  - 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  9822:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   9823:    fprintf(fichtm,"\
1.128     brouard  9824:  - 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  9825:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   9826:    fprintf(fichtm,"\
1.288     brouard  9827:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  9828:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  9829: 
                   9830: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   9831: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   9832: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   9833: /*     <br>",fileres,fileres,fileres,fileres); */
                   9834: /*  else  */
1.338     brouard  9835: /*    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  9836:    fflush(fichtm);
1.126     brouard  9837: 
1.225     brouard  9838:    m=pow(2,cptcoveff);
1.222     brouard  9839:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  9840: 
1.317     brouard  9841:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   9842: 
                   9843:   jj1=0;
                   9844: 
                   9845:    fprintf(fichtm," \n<ul>");
1.337     brouard  9846:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9847:      /* k1=nres; */
1.338     brouard  9848:      k1=TKresult[nres];
1.337     brouard  9849:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   9850:      /* if(m != 1 && TKresult[nres]!= k1) */
                   9851:      /*   continue; */
1.317     brouard  9852:      jj1++;
                   9853:      if (cptcovn > 0) {
                   9854:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
1.337     brouard  9855:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9856:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  9857:        }
                   9858:        fprintf(fichtm,"\">");
                   9859:        
                   9860:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   9861:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  9862:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9863:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  9864:        }
                   9865:        if(invalidvarcomb[k1]){
                   9866:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   9867:         continue;
                   9868:        }
                   9869:        fprintf(fichtm,"</a></li>");
                   9870:      } /* cptcovn >0 */
1.337     brouard  9871:    } /* End nres */
1.317     brouard  9872:    fprintf(fichtm," \n</ul>");
                   9873: 
1.222     brouard  9874:    jj1=0;
1.237     brouard  9875: 
1.241     brouard  9876:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9877:      /* k1=nres; */
1.338     brouard  9878:      k1=TKresult[nres];
                   9879:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9880:      /* for(k1=1; k1<=m;k1++){ */
                   9881:      /* if(m != 1 && TKresult[nres]!= k1) */
                   9882:      /*   continue; */
1.222     brouard  9883:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   9884:      jj1++;
1.126     brouard  9885:      if (cptcovn > 0) {
1.317     brouard  9886:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
1.337     brouard  9887:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9888:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  9889:        }
                   9890:        fprintf(fichtm,"\"</a>");
                   9891:        
1.126     brouard  9892:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  9893:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
                   9894:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   9895:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  9896:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  9897:        }
1.237     brouard  9898: 
1.338     brouard  9899:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  9900: 
1.222     brouard  9901:        if(invalidvarcomb[k1]){
                   9902:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   9903:         continue;
                   9904:        }
1.337     brouard  9905:      } /* If cptcovn >0 */
1.126     brouard  9906:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  9907:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  9908: 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);
                   9909:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   9910:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  9911:      }
                   9912:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.360   ! brouard  9913: health expectancies in each live state (1 to %d) with confidence intervals \
        !          9914: on left y-scale as well as proportions of time spent in each live state \
        !          9915: (with confidence intervals) on right y-scale 0 to 100%%.\
        !          9916:  If popbased=1 the smooth (due to the model)                           \
1.128     brouard  9917: true period expectancies (those weighted with period prevalences are also\
                   9918:  drawn in addition to the population based expectancies computed using\
1.314     brouard  9919:  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);
                   9920:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   9921:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  9922:      /* } /\* end i1 *\/ */
1.241     brouard  9923:   }/* End nres */
1.222     brouard  9924:    fprintf(fichtm,"</ul>");
                   9925:    fflush(fichtm);
1.126     brouard  9926: }
                   9927: 
                   9928: /******************* Gnuplot file **************/
1.296     brouard  9929: 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  9930: 
1.354     brouard  9931:   char dirfileres[256],optfileres[256];
                   9932:   char gplotcondition[256], gplotlabel[256];
1.343     brouard  9933:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,k4=0,kf=0,kvar=0,kk=0,ipos=0,iposold=0,ij=0, ijp=0, l=0;
1.211     brouard  9934:   int lv=0, vlv=0, kl=0;
1.130     brouard  9935:   int ng=0;
1.201     brouard  9936:   int vpopbased;
1.223     brouard  9937:   int ioffset; /* variable offset for columns */
1.270     brouard  9938:   int iyearc=1; /* variable column for year of projection  */
                   9939:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  9940:   int nres=0; /* Index of resultline */
1.266     brouard  9941:   int istart=1; /* For starting graphs in projections */
1.219     brouard  9942: 
1.126     brouard  9943: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   9944: /*     printf("Problem with file %s",optionfilegnuplot); */
                   9945: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   9946: /*   } */
                   9947: 
                   9948:   /*#ifdef windows */
                   9949:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  9950:   /*#endif */
1.225     brouard  9951:   m=pow(2,cptcoveff);
1.126     brouard  9952: 
1.274     brouard  9953:   /* diagram of the model */
                   9954:   fprintf(ficgp,"\n#Diagram of the model \n");
                   9955:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   9956:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   9957:   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);
                   9958: 
1.343     brouard  9959:   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  9960:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   9961:   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);
                   9962:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   9963:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   9964:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   9965:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   9966: 
1.202     brouard  9967:   /* Contribution to likelihood */
                   9968:   /* Plot the probability implied in the likelihood */
1.223     brouard  9969:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   9970:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   9971:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   9972:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  9973: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  9974:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   9975: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  9976:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   9977:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   9978:   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));
                   9979:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   9980:   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));
                   9981:   for (i=1; i<= nlstate ; i ++) {
                   9982:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   9983:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   9984:     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);
                   9985:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   9986:       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);
                   9987:     }
                   9988:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   9989:   }
                   9990:   /* 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 */               
                   9991:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   9992:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   9993:   fprintf(ficgp,"\nset out;unset log\n");
                   9994:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  9995: 
1.343     brouard  9996:   /* Plot the probability implied in the likelihood by covariate value */
                   9997:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
                   9998:   /* if(debugILK==1){ */
                   9999:   for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.347     brouard  10000:     kvar=Tvar[TvarFind[kf]]; /* variable name */
                   10001:     /* k=18+Tvar[TvarFind[kf]];/\*offset because there are 18 columns in the ILK_ file but could be placed else where *\/ */
1.350     brouard  10002:     /* k=18+kf;/\*offset because there are 18 columns in the ILK_ file *\/ */
1.356     brouard  10003:     /* k=19+kf;/\*offset because there are 19 columns in the ILK_ file *\/ */
1.355     brouard  10004:     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  10005:     for (i=1; i<= nlstate ; i ++) {
                   10006:       fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   10007:       fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
1.348     brouard  10008:       if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   10009:        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);
                   10010:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   10011:          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);
                   10012:        }
                   10013:       }else{
                   10014:        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);
                   10015:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   10016:          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);
                   10017:        }
1.343     brouard  10018:       }
                   10019:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   10020:     }
                   10021:   } /* End of each covariate dummy */
                   10022:   for(ncovv=1, iposold=0, kk=0; ncovv <= ncovvt ; ncovv++){
                   10023:     /* Other example        V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   10024:      *     kmodel       =     1   2     3     4         5        6        7       8        9
                   10025:      *  varying                   1     2                                 3       4        5
                   10026:      *  ncovv                     1     2                                3 4     5 6      7 8
                   10027:      * TvarVV[ncovv]             V3     5                                1 3     3 5      1 5
                   10028:      * TvarVVind[ncovv]=kmodel    2     3                                7 7     8 8      9 9
                   10029:      * TvarFind[kmodel]       1   0     0     0         0        0        0       0        0
                   10030:      * kdata     ncovcol=[V1 V2] nqv=0 ntv=[V3 V4] nqtv=V5
                   10031:      * Dummy[kmodel]          0   0     1     2         2        3        1       1        1
                   10032:      */
                   10033:     ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   10034:     kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   10035:     /* 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]); */
                   10036:     if(ipos!=iposold){ /* Not a product or first of a product */
                   10037:       /* printf(" %d",ipos); */
                   10038:       /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   10039:       /* printf(" DebugILK ficgp suite ipos=%d != iposold=%d\n", ipos, iposold); */
                   10040:       kk++; /* Position of the ncovv column in ILK_ */
                   10041:       k=18+ncovf+kk; /*offset because there are 18 columns in the ILK_ file plus ncovf fixed covariate */
                   10042:       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)  */
                   10043:        for (i=1; i<= nlstate ; i ++) {
                   10044:          fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   10045:          fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   10046: 
1.348     brouard  10047:            /* printf("Before DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
1.343     brouard  10048:          if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   10049:            /* printf("DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
                   10050:            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);
                   10051:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   10052:              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);
                   10053:            }
                   10054:          }else{
                   10055:            /* printf("DebugILK gnuplotversion=%g <5.2\n",gnuplotversion); */
                   10056:            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);
                   10057:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   10058:              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);
                   10059:            }
                   10060:          }
                   10061:          fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   10062:        }
                   10063:       }/* End if dummy varying */
                   10064:     }else{ /*Product */
                   10065:       /* printf("*"); */
                   10066:       /* fprintf(ficresilk,"*"); */
                   10067:     }
                   10068:     iposold=ipos;
                   10069:   } /* For each time varying covariate */
                   10070:   /* } /\* debugILK==1 *\/ */
                   10071:   /* 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 */               
                   10072:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   10073:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   10074:   fprintf(ficgp,"\nset out;unset log\n");
                   10075:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   10076: 
                   10077: 
                   10078:   
1.126     brouard  10079:   strcpy(dirfileres,optionfilefiname);
                   10080:   strcpy(optfileres,"vpl");
1.223     brouard  10081:   /* 1eme*/
1.238     brouard  10082:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
1.337     brouard  10083:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
1.236     brouard  10084:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10085:        k1=TKresult[nres];
1.338     brouard  10086:        if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.238     brouard  10087:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.337     brouard  10088:        /* if(m != 1 && TKresult[nres]!= k1) */
                   10089:        /*   continue; */
1.238     brouard  10090:        /* We are interested in selected combination by the resultline */
1.246     brouard  10091:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  10092:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  10093:        strcpy(gplotlabel,"(");
1.337     brouard  10094:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10095:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10096:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10097: 
                   10098:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
                   10099:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
                   10100:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10101:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10102:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10103:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10104:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
                   10105:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
                   10106:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
                   10107:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10108:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10109:        /* } */
                   10110:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10111:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
                   10112:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10113:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.264     brouard  10114:        }
                   10115:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  10116:        /* printf("\n#\n"); */
1.238     brouard  10117:        fprintf(ficgp,"\n#\n");
                   10118:        if(invalidvarcomb[k1]){
1.260     brouard  10119:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  10120:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10121:          continue;
                   10122:        }
1.235     brouard  10123:       
1.241     brouard  10124:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   10125:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  10126:        /* 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  10127:        fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  10128:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \nset ter svg size 640, 480\nplot [%.f:%.f] \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),nres-1,nres-1,nres);
                   10129:        /* 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); */
                   10130:       /* k1-1 error should be nres-1*/
1.238     brouard  10131:        for (i=1; i<= nlstate ; i ++) {
                   10132:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10133:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   10134:        }
1.288     brouard  10135:        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  10136:        for (i=1; i<= nlstate ; i ++) {
                   10137:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10138:          else fprintf(ficgp," %%*lf (%%*lf)");
                   10139:        } 
1.260     brouard  10140:        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  10141:        for (i=1; i<= nlstate ; i ++) {
                   10142:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10143:          else fprintf(ficgp," %%*lf (%%*lf)");
                   10144:        }  
1.265     brouard  10145:        /* 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)); */
                   10146:        
                   10147:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   10148:         if(cptcoveff ==0){
1.271     brouard  10149:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  10150:        }else{
                   10151:          kl=0;
                   10152:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  10153:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   10154:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  10155:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   10156:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   10157:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   10158:            vlv= nbcode[Tvaraff[k]][lv];
                   10159:            kl++;
                   10160:            /* 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 *\/ */
                   10161:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   10162:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   10163:            /* ''  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*/
                   10164:            if(k==cptcoveff){
                   10165:              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], \
                   10166:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   10167:            }else{
                   10168:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   10169:              kl++;
                   10170:            }
                   10171:          } /* end covariate */
                   10172:        } /* end if no covariate */
                   10173: 
1.296     brouard  10174:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  10175:          /* 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  10176:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  10177:          if(cptcoveff ==0){
1.245     brouard  10178:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  10179:          }else{
                   10180:            kl=0;
                   10181:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  10182:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   10183:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  10184:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   10185:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   10186:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  10187:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   10188:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  10189:              kl++;
1.238     brouard  10190:              /* 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 *\/ */
                   10191:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   10192:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   10193:              /* ''  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*/
                   10194:              if(k==cptcoveff){
1.245     brouard  10195:                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  10196:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  10197:              }else{
1.332     brouard  10198:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  10199:                kl++;
                   10200:              }
                   10201:            } /* end covariate */
                   10202:          } /* end if no covariate */
1.296     brouard  10203:          if(prevbcast == 1){
1.268     brouard  10204:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   10205:            /* k1-1 error should be nres-1*/
                   10206:            for (i=1; i<= nlstate ; i ++) {
                   10207:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10208:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   10209:            }
1.271     brouard  10210:            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  10211:            for (i=1; i<= nlstate ; i ++) {
                   10212:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10213:              else fprintf(ficgp," %%*lf (%%*lf)");
                   10214:            } 
1.276     brouard  10215:            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  10216:            for (i=1; i<= nlstate ; i ++) {
                   10217:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10218:              else fprintf(ficgp," %%*lf (%%*lf)");
                   10219:            } 
1.274     brouard  10220:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  10221:          } /* end if backprojcast */
1.296     brouard  10222:        } /* end if prevbcast */
1.276     brouard  10223:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   10224:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  10225:       } /* nres */
1.337     brouard  10226:     /* } /\* k1 *\/ */
1.201     brouard  10227:   } /* cpt */
1.235     brouard  10228: 
                   10229:   
1.126     brouard  10230:   /*2 eme*/
1.337     brouard  10231:   /* for (k1=1; k1<= m ; k1 ++){   */
1.238     brouard  10232:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10233:       k1=TKresult[nres];
1.338     brouard  10234:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10235:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10236:       /*       continue; */
1.238     brouard  10237:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  10238:       strcpy(gplotlabel,"(");
1.337     brouard  10239:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10240:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10241:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10242:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10243:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10244:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10245:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10246:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10247:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10248:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10249:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10250:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10251:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10252:       /* } */
                   10253:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
                   10254:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10255:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10256:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10257:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  10258:       }
1.264     brouard  10259:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  10260:       fprintf(ficgp,"\n#\n");
1.223     brouard  10261:       if(invalidvarcomb[k1]){
                   10262:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10263:        continue;
                   10264:       }
1.219     brouard  10265:                        
1.241     brouard  10266:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  10267:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  10268:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   10269:        if(vpopbased==0){
1.360   ! brouard  10270:          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  10271:        }else
1.238     brouard  10272:          fprintf(ficgp,"\nreplot ");
1.360   ! brouard  10273:        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  10274:          k=2*i;
1.360   ! brouard  10275:          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 */
        !          10276:          for (j=1; j<= nlstate+1 ; j ++) { /* e.. e.1 e.2 again j-1 is the state of end, wlim_i eij*/
        !          10277:            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 */
        !          10278:            else fprintf(ficgp," %%*lf (%%*lf)");  /* skipping that field with a star */
1.238     brouard  10279:          }   
                   10280:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
1.360   ! brouard  10281:          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  10282:          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  10283:          for (j=1; j<= nlstate+1 ; j ++) {
                   10284:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   10285:            else fprintf(ficgp," %%*lf (%%*lf)");
                   10286:          }   
                   10287:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  10288:          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  10289:          for (j=1; j<= nlstate+1 ; j ++) {
                   10290:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   10291:            else fprintf(ficgp," %%*lf (%%*lf)");
                   10292:          }   
1.360   ! brouard  10293:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0,\\\n"); /* ,\\\n added for th percentage graphs */
1.238     brouard  10294:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   10295:        } /* state */
1.360   ! brouard  10296:        /* again for the percentag spent in state i-1=1 to i-1=nlstate */
        !          10297:        for (i=2; i<= nlstate+1 ; i ++) { /* For state i-1=0 is LE, while i-1=1 to nlstate are origin state */
        !          10298:          k=2*i;
        !          10299:          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 */
        !          10300:          for (j=1; j<= nlstate ; j ++)
        !          10301:            fprintf(ficgp," %%*lf (%%*lf)"); /* Skipping TLE and LE to read %LE only */
        !          10302:          for (j=1; j<= nlstate+1 ; j ++) { /* e.. e.1 e.2 again j-1 is the state of end, wlim_i eij*/
        !          10303:            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 */
        !          10304:            else fprintf(ficgp," %%*lf (%%*lf)");  /* skipping that field with a star */
        !          10305:          }   
        !          10306:          if (i== 1) fprintf(ficgp,"\" t\"%%TLE\" w l lt %d axis x1y2, \\\n",i); /* Not used */
        !          10307:          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  */
        !          10308:          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);
        !          10309:          for (j=1; j<= nlstate ; j ++)
        !          10310:            fprintf(ficgp," %%*lf (%%*lf)"); /* Skipping TLE and LE to read %LE only */
        !          10311:          for (j=1; j<= nlstate+1 ; j ++) {
        !          10312:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
        !          10313:            else fprintf(ficgp," %%*lf (%%*lf)");
        !          10314:          }   
        !          10315:          fprintf(ficgp,"\" t\"\" w l lt 0 axis x1y2,");
        !          10316:          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);
        !          10317:          for (j=1; j<= nlstate ; j ++)
        !          10318:            fprintf(ficgp," %%*lf (%%*lf)"); /* Skipping TLE and LE to read %LE only */
        !          10319:          for (j=1; j<= nlstate+1 ; j ++) {
        !          10320:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
        !          10321:            else fprintf(ficgp," %%*lf (%%*lf)");
        !          10322:          }   
        !          10323:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0 axis x1y2");
        !          10324:          else fprintf(ficgp,"\" t\"\" w l lt 0 axis x1y2,\\\n");
        !          10325:        } /* state for percent */
1.238     brouard  10326:       } /* vpopbased */
1.264     brouard  10327:       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  10328:     } /* end nres */
1.337     brouard  10329:   /* } /\* k1 end 2 eme*\/ */
1.238     brouard  10330:        
                   10331:        
                   10332:   /*3eme*/
1.337     brouard  10333:   /* for (k1=1; k1<= m ; k1 ++){ */
1.238     brouard  10334:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10335:       k1=TKresult[nres];
1.338     brouard  10336:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10337:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10338:       /*       continue; */
1.238     brouard  10339: 
1.332     brouard  10340:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  10341:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  10342:        strcpy(gplotlabel,"(");
1.337     brouard  10343:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10344:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10345:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10346:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10347:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10348:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   10349:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10350:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10351:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10352:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10353:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10354:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10355:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10356:        /* } */
                   10357:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10358:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   10359:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   10360:        }
1.264     brouard  10361:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  10362:        fprintf(ficgp,"\n#\n");
                   10363:        if(invalidvarcomb[k1]){
                   10364:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10365:          continue;
                   10366:        }
                   10367:                        
                   10368:        /*       k=2+nlstate*(2*cpt-2); */
                   10369:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  10370:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  10371:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  10372:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  10373: 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  10374:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   10375:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   10376:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   10377:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   10378:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   10379:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  10380:                                
1.238     brouard  10381:        */
                   10382:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  10383:          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  10384:          /*    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  10385:                                
1.238     brouard  10386:        } 
1.261     brouard  10387:        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  10388:       }
1.264     brouard  10389:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  10390:     } /* end nres */
1.337     brouard  10391:   /* } /\* end kl 3eme *\/ */
1.126     brouard  10392:   
1.223     brouard  10393:   /* 4eme */
1.201     brouard  10394:   /* Survival functions (period) from state i in state j by initial state i */
1.337     brouard  10395:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
1.238     brouard  10396:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10397:       k1=TKresult[nres];
1.338     brouard  10398:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10399:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10400:       /*       continue; */
1.238     brouard  10401:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  10402:        strcpy(gplotlabel,"(");
1.337     brouard  10403:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
                   10404:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10405:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10406:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10407:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10408:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10409:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10410:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10411:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10412:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10413:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10414:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10415:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10416:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10417:        /* } */
                   10418:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10419:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10420:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  10421:        }       
1.264     brouard  10422:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  10423:        fprintf(ficgp,"\n#\n");
                   10424:        if(invalidvarcomb[k1]){
                   10425:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10426:          continue;
1.223     brouard  10427:        }
1.238     brouard  10428:       
1.241     brouard  10429:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  10430:        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  10431:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   10432: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   10433:        k=3;
                   10434:        for (i=1; i<= nlstate ; i ++){
                   10435:          if(i==1){
                   10436:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   10437:          }else{
                   10438:            fprintf(ficgp,", '' ");
                   10439:          }
                   10440:          l=(nlstate+ndeath)*(i-1)+1;
                   10441:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   10442:          for (j=2; j<= nlstate+ndeath ; j ++)
                   10443:            fprintf(ficgp,"+$%d",k+l+j-1);
                   10444:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   10445:        } /* nlstate */
1.264     brouard  10446:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  10447:       } /* end cpt state*/ 
                   10448:     } /* end nres */
1.337     brouard  10449:   /* } /\* end covariate k1 *\/   */
1.238     brouard  10450: 
1.220     brouard  10451: /* 5eme */
1.201     brouard  10452:   /* Survival functions (period) from state i in state j by final state j */
1.337     brouard  10453:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
1.238     brouard  10454:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10455:       k1=TKresult[nres];
1.338     brouard  10456:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10457:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10458:       /*       continue; */
1.238     brouard  10459:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  10460:        strcpy(gplotlabel,"(");
1.238     brouard  10461:        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  10462:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10463:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10464:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10465:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10466:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10467:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10468:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10469:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10470:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10471:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10472:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10473:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10474:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10475:        /* } */
                   10476:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10477:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10478:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  10479:        }       
1.264     brouard  10480:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  10481:        fprintf(ficgp,"\n#\n");
                   10482:        if(invalidvarcomb[k1]){
                   10483:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10484:          continue;
                   10485:        }
1.227     brouard  10486:       
1.241     brouard  10487:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  10488:        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  10489:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   10490: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   10491:        k=3;
                   10492:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   10493:          if(j==1)
                   10494:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   10495:          else
                   10496:            fprintf(ficgp,", '' ");
                   10497:          l=(nlstate+ndeath)*(cpt-1) +j;
                   10498:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   10499:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   10500:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   10501:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   10502:        } /* nlstate */
                   10503:        fprintf(ficgp,", '' ");
                   10504:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   10505:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   10506:          l=(nlstate+ndeath)*(cpt-1) +j;
                   10507:          if(j < nlstate)
                   10508:            fprintf(ficgp,"$%d +",k+l);
                   10509:          else
                   10510:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   10511:        }
1.264     brouard  10512:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  10513:       } /* end cpt state*/ 
1.337     brouard  10514:     /* } /\* end covariate *\/   */
1.238     brouard  10515:   } /* end nres */
1.227     brouard  10516:   
1.220     brouard  10517: /* 6eme */
1.202     brouard  10518:   /* CV preval stable (period) for each covariate */
1.337     brouard  10519:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  10520:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10521:      k1=TKresult[nres];
1.338     brouard  10522:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10523:      /* if(m != 1 && TKresult[nres]!= k1) */
                   10524:      /*  continue; */
1.255     brouard  10525:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  10526:       strcpy(gplotlabel,"(");      
1.288     brouard  10527:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  10528:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10529:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10530:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10531:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10532:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10533:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10534:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10535:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10536:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10537:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10538:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10539:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10540:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10541:       /* } */
                   10542:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10543:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10544:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  10545:       }        
1.264     brouard  10546:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  10547:       fprintf(ficgp,"\n#\n");
1.223     brouard  10548:       if(invalidvarcomb[k1]){
1.227     brouard  10549:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10550:        continue;
1.223     brouard  10551:       }
1.227     brouard  10552:       
1.241     brouard  10553:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  10554:       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  10555:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  10556: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  10557:       k=3; /* Offset */
1.255     brouard  10558:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  10559:        if(i==1)
                   10560:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   10561:        else
                   10562:          fprintf(ficgp,", '' ");
1.255     brouard  10563:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  10564:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   10565:        for (j=2; j<= nlstate ; j ++)
                   10566:          fprintf(ficgp,"+$%d",k+l+j-1);
                   10567:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  10568:       } /* nlstate */
1.264     brouard  10569:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  10570:     } /* end cpt state*/ 
                   10571:   } /* end covariate */  
1.227     brouard  10572:   
                   10573:   
1.220     brouard  10574: /* 7eme */
1.296     brouard  10575:   if(prevbcast == 1){
1.288     brouard  10576:     /* CV backward prevalence  for each covariate */
1.337     brouard  10577:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  10578:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10579:       k1=TKresult[nres];
1.338     brouard  10580:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10581:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10582:       /*       continue; */
1.268     brouard  10583:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  10584:        strcpy(gplotlabel,"(");      
1.288     brouard  10585:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  10586:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10587:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10588:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10589:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10590:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10591:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10592:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10593:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10594:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10595:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10596:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10597:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10598:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10599:        /* } */
                   10600:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10601:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10602:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  10603:        }       
1.264     brouard  10604:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  10605:        fprintf(ficgp,"\n#\n");
                   10606:        if(invalidvarcomb[k1]){
                   10607:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10608:          continue;
                   10609:        }
                   10610:        
1.241     brouard  10611:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  10612:        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  10613:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  10614: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  10615:        k=3; /* Offset */
1.268     brouard  10616:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  10617:          if(i==1)
                   10618:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   10619:          else
                   10620:            fprintf(ficgp,", '' ");
                   10621:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  10622:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  10623:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   10624:          /* 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  10625:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  10626:          /* for (j=2; j<= nlstate ; j ++) */
                   10627:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   10628:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  10629:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  10630:        } /* nlstate */
1.264     brouard  10631:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  10632:       } /* end cpt state*/ 
                   10633:     } /* end covariate */  
1.296     brouard  10634:   } /* End if prevbcast */
1.218     brouard  10635:   
1.223     brouard  10636:   /* 8eme */
1.218     brouard  10637:   if(prevfcast==1){
1.288     brouard  10638:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  10639:     
1.337     brouard  10640:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  10641:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10642:       k1=TKresult[nres];
1.338     brouard  10643:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10644:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10645:       /*       continue; */
1.211     brouard  10646:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  10647:        strcpy(gplotlabel,"(");      
1.288     brouard  10648:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  10649:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10650:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10651:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10652:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   10653:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   10654:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10655:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10656:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10657:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10658:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10659:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10660:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10661:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10662:        /* } */
                   10663:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10664:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10665:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  10666:        }       
1.264     brouard  10667:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  10668:        fprintf(ficgp,"\n#\n");
                   10669:        if(invalidvarcomb[k1]){
                   10670:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10671:          continue;
                   10672:        }
                   10673:        
                   10674:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  10675:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  10676:        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  10677:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  10678: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  10679: 
                   10680:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   10681:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   10682:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   10683:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  10684:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10685:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   10686:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10687:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  10688:          if(i==istart){
1.227     brouard  10689:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   10690:          }else{
                   10691:            fprintf(ficgp,",\\\n '' ");
                   10692:          }
                   10693:          if(cptcoveff ==0){ /* No covariate */
                   10694:            ioffset=2; /* Age is in 2 */
                   10695:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   10696:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   10697:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   10698:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   10699:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  10700:            if(i==nlstate+1){
1.270     brouard  10701:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  10702:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   10703:              fprintf(ficgp,",\\\n '' ");
                   10704:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  10705:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  10706:                     offyear,                           \
1.268     brouard  10707:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  10708:            }else
1.227     brouard  10709:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   10710:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   10711:          }else{ /* more than 2 covariates */
1.270     brouard  10712:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   10713:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10714:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   10715:            iyearc=ioffset-1;
                   10716:            iagec=ioffset;
1.227     brouard  10717:            fprintf(ficgp," u %d:(",ioffset); 
                   10718:            kl=0;
                   10719:            strcpy(gplotcondition,"(");
1.351     brouard  10720:            /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
1.332     brouard  10721:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
1.351     brouard  10722:            for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10723:              /* lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10724:              lv=Tvresult[nres][k];
                   10725:              vlv=TinvDoQresult[nres][Tvresult[nres][k]];
1.227     brouard  10726:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   10727:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   10728:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  10729:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
1.351     brouard  10730:              /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
1.227     brouard  10731:              kl++;
1.351     brouard  10732:              /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   10733:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,lv, kl+1, vlv );
1.227     brouard  10734:              kl++;
1.351     brouard  10735:              if(k <cptcovs && cptcovs>1)
1.227     brouard  10736:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   10737:            }
                   10738:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   10739:            /* 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 *\/ */
                   10740:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   10741:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   10742:            /* ''  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*/
                   10743:            if(i==nlstate+1){
1.270     brouard  10744:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   10745:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  10746:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  10747:              fprintf(ficgp," u %d:(",iagec); 
                   10748:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   10749:                      iyearc, iagec, offyear,                           \
                   10750:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  10751: /*  '' 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  10752:            }else{
                   10753:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   10754:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   10755:            }
                   10756:          } /* end if covariate */
                   10757:        } /* nlstate */
1.264     brouard  10758:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  10759:       } /* end cpt state*/
                   10760:     } /* end covariate */
                   10761:   } /* End if prevfcast */
1.227     brouard  10762:   
1.296     brouard  10763:   if(prevbcast==1){
1.268     brouard  10764:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   10765:     
1.337     brouard  10766:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.268     brouard  10767:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10768:      k1=TKresult[nres];
1.338     brouard  10769:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10770:        /* if(m != 1 && TKresult[nres]!= k1) */
                   10771:        /*      continue; */
1.268     brouard  10772:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   10773:        strcpy(gplotlabel,"(");      
                   10774:        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  10775:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10776:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10777:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10778:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   10779:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   10780:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   10781:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10782:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10783:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10784:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10785:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10786:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10787:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10788:        /* } */
                   10789:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10790:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10791:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.268     brouard  10792:        }       
                   10793:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   10794:        fprintf(ficgp,"\n#\n");
                   10795:        if(invalidvarcomb[k1]){
                   10796:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10797:          continue;
                   10798:        }
                   10799:        
                   10800:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   10801:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   10802:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   10803:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   10804: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   10805: 
                   10806:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   10807:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   10808:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   10809:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   10810:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10811:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   10812:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10813:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   10814:          if(i==istart){
                   10815:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   10816:          }else{
                   10817:            fprintf(ficgp,",\\\n '' ");
                   10818:          }
1.351     brouard  10819:          /* if(cptcoveff ==0){ /\* No covariate *\/ */
                   10820:          if(cptcovs ==0){ /* No covariate */
1.268     brouard  10821:            ioffset=2; /* Age is in 2 */
                   10822:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   10823:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   10824:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   10825:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   10826:            fprintf(ficgp," u %d:(", ioffset); 
                   10827:            if(i==nlstate+1){
1.270     brouard  10828:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  10829:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   10830:              fprintf(ficgp,",\\\n '' ");
                   10831:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  10832:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  10833:                     offbyear,                          \
                   10834:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   10835:            }else
                   10836:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   10837:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   10838:          }else{ /* more than 2 covariates */
1.270     brouard  10839:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   10840:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10841:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   10842:            iyearc=ioffset-1;
                   10843:            iagec=ioffset;
1.268     brouard  10844:            fprintf(ficgp," u %d:(",ioffset); 
                   10845:            kl=0;
                   10846:            strcpy(gplotcondition,"(");
1.337     brouard  10847:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
1.338     brouard  10848:              if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
1.337     brouard  10849:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
                   10850:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   10851:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   10852:                lv=Tvresult[nres][k];
                   10853:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
                   10854:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   10855:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   10856:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   10857:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   10858:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10859:                kl++;
                   10860:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   10861:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
                   10862:                kl++;
1.338     brouard  10863:                if(k <cptcovs && cptcovs>1)
1.337     brouard  10864:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   10865:              }
1.268     brouard  10866:            }
                   10867:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   10868:            /* 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 *\/ */
                   10869:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   10870:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   10871:            /* ''  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*/
                   10872:            if(i==nlstate+1){
1.270     brouard  10873:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   10874:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  10875:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  10876:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  10877:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  10878:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   10879:                      iyearc,iagec,offbyear,                            \
                   10880:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  10881: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   10882:            }else{
                   10883:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   10884:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   10885:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   10886:            }
                   10887:          } /* end if covariate */
                   10888:        } /* nlstate */
                   10889:        fprintf(ficgp,"\nset out; unset label;\n");
                   10890:       } /* end cpt state*/
                   10891:     } /* end covariate */
1.296     brouard  10892:   } /* End if prevbcast */
1.268     brouard  10893:   
1.227     brouard  10894:   
1.238     brouard  10895:   /* 9eme writing MLE parameters */
                   10896:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  10897:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  10898:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  10899:     for(k=1; k <=(nlstate+ndeath); k++){
                   10900:       if (k != i) {
1.227     brouard  10901:        fprintf(ficgp,"#   current state %d\n",k);
                   10902:        for(j=1; j <=ncovmodel; j++){
                   10903:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   10904:          jk++; 
                   10905:        }
                   10906:        fprintf(ficgp,"\n");
1.126     brouard  10907:       }
                   10908:     }
1.223     brouard  10909:   }
1.187     brouard  10910:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  10911:   
1.145     brouard  10912:   /*goto avoid;*/
1.238     brouard  10913:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   10914:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  10915:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   10916:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   10917:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   10918:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   10919:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   10920:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   10921:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   10922:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   10923:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   10924:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   10925:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   10926:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   10927:   fprintf(ficgp,"#\n");
1.223     brouard  10928:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  10929:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.338     brouard  10930:     fprintf(ficgp,"#model=1+age+%s \n",model);
1.238     brouard  10931:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.351     brouard  10932:     /* fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/\* to be checked *\/ */
                   10933:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcovs,m);/* to be checked */
1.337     brouard  10934:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
1.237     brouard  10935:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10936:      /* k1=nres; */
1.338     brouard  10937:       k1=TKresult[nres];
                   10938:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10939:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
1.264     brouard  10940:       strcpy(gplotlabel,"(");
1.276     brouard  10941:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.337     brouard  10942:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   10943:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
                   10944:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
                   10945:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10946:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10947:       }
                   10948:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10949:       /*       continue; */
                   10950:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
                   10951:       /* strcpy(gplotlabel,"("); */
                   10952:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
                   10953:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   10954:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   10955:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   10956:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10957:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10958:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10959:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10960:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10961:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10962:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10963:       /* } */
                   10964:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10965:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10966:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10967:       /* }      */
1.264     brouard  10968:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  10969:       fprintf(ficgp,"\n#\n");
1.264     brouard  10970:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  10971:       fprintf(ficgp,"\nset key outside ");
                   10972:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   10973:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  10974:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   10975:       if (ng==1){
                   10976:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   10977:        fprintf(ficgp,"\nunset log y");
                   10978:       }else if (ng==2){
                   10979:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   10980:        fprintf(ficgp,"\nset log y");
                   10981:       }else if (ng==3){
                   10982:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   10983:        fprintf(ficgp,"\nset log y");
                   10984:       }else
                   10985:        fprintf(ficgp,"\nunset title ");
                   10986:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   10987:       i=1;
                   10988:       for(k2=1; k2<=nlstate; k2++) {
                   10989:        k3=i;
                   10990:        for(k=1; k<=(nlstate+ndeath); k++) {
                   10991:          if (k != k2){
                   10992:            switch( ng) {
                   10993:            case 1:
                   10994:              if(nagesqr==0)
                   10995:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   10996:              else /* nagesqr =1 */
                   10997:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   10998:              break;
                   10999:            case 2: /* ng=2 */
                   11000:              if(nagesqr==0)
                   11001:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   11002:              else /* nagesqr =1 */
                   11003:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   11004:              break;
                   11005:            case 3:
                   11006:              if(nagesqr==0)
                   11007:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   11008:              else /* nagesqr =1 */
                   11009:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   11010:              break;
                   11011:            }
                   11012:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  11013:            ijp=1; /* product no age */
                   11014:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   11015:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  11016:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  11017:              switch(Typevar[j]){
                   11018:              case 1:
                   11019:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   11020:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   11021:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   11022:                      if(DummyV[j]==0){/* Bug valgrind */
                   11023:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   11024:                      }else{ /* quantitative */
                   11025:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   11026:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   11027:                      }
                   11028:                      ij++;
1.268     brouard  11029:                    }
1.237     brouard  11030:                  }
1.329     brouard  11031:                }
                   11032:                break;
                   11033:              case 2:
                   11034:                if(cptcovprod >0){
                   11035:                  if(j==Tprod[ijp]) { /* */ 
                   11036:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   11037:                    if(ijp <=cptcovprod) { /* Product */
                   11038:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   11039:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   11040:                          /* 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)]); */
                   11041:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   11042:                        }else{ /* Vn is dummy and Vm is quanti */
                   11043:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11044:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   11045:                        }
                   11046:                      }else{ /* Vn*Vm Vn is quanti */
                   11047:                        if(DummyV[Tvard[ijp][2]]==0){
                   11048:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   11049:                        }else{ /* Both quanti */
                   11050:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   11051:                        }
1.268     brouard  11052:                      }
1.329     brouard  11053:                      ijp++;
1.237     brouard  11054:                    }
1.329     brouard  11055:                  } /* end Tprod */
                   11056:                }
                   11057:                break;
1.349     brouard  11058:              case 3:
                   11059:                if(cptcovdageprod >0){
                   11060:                  /* if(j==Tprod[ijp]) { */ /* not necessary */ 
                   11061:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
1.350     brouard  11062:                    if(ijp <=cptcovprod) { /* Product Vn*Vm and age*VN*Vm*/
                   11063:                      if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   11064:                        if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  11065:                          /* 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)]); */
                   11066:                          fprintf(ficgp,"+p%d*%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   11067:                        }else{ /* Vn is dummy and Vm is quanti */
                   11068:                          /* 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  11069:                          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  11070:                        }
1.350     brouard  11071:                      }else{ /* age* Vn*Vm Vn is quanti HERE */
1.349     brouard  11072:                        if(DummyV[Tvard[ijp][2]]==0){
1.350     brouard  11073:                          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  11074:                        }else{ /* Both quanti */
1.350     brouard  11075:                          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  11076:                        }
                   11077:                      }
                   11078:                      ijp++;
                   11079:                    }
                   11080:                    /* } */ /* end Tprod */
                   11081:                }
                   11082:                break;
1.329     brouard  11083:              case 0:
                   11084:                /* simple covariate */
1.264     brouard  11085:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  11086:                if(Dummy[j]==0){
                   11087:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   11088:                }else{ /* quantitative */
                   11089:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  11090:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  11091:                }
1.329     brouard  11092:               /* end simple */
                   11093:                break;
                   11094:              default:
                   11095:                break;
                   11096:              } /* end switch */
1.237     brouard  11097:            } /* end j */
1.329     brouard  11098:          }else{ /* k=k2 */
                   11099:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   11100:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   11101:            }else
                   11102:              i=i-ncovmodel;
1.223     brouard  11103:          }
1.227     brouard  11104:          
1.223     brouard  11105:          if(ng != 1){
                   11106:            fprintf(ficgp,")/(1");
1.227     brouard  11107:            
1.264     brouard  11108:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  11109:              if(nagesqr==0)
1.264     brouard  11110:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  11111:              else /* nagesqr =1 */
1.264     brouard  11112:                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  11113:               
1.223     brouard  11114:              ij=1;
1.329     brouard  11115:              ijp=1;
                   11116:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   11117:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   11118:                switch(Typevar[j]){
                   11119:                case 1:
                   11120:                  if(cptcovage >0){ 
                   11121:                    if(j==Tage[ij]) { /* Bug valgrind */
                   11122:                      if(ij <=cptcovage) { /* Bug valgrind */
                   11123:                        if(DummyV[j]==0){/* Bug valgrind */
                   11124:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   11125:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   11126:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   11127:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   11128:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   11129:                        }else{ /* quantitative */
                   11130:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   11131:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   11132:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   11133:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   11134:                        }
                   11135:                        ij++;
                   11136:                      }
                   11137:                    }
                   11138:                  }
                   11139:                  break;
                   11140:                case 2:
                   11141:                  if(cptcovprod >0){
                   11142:                    if(j==Tprod[ijp]) { /* */ 
                   11143:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   11144:                      if(ijp <=cptcovprod) { /* Product */
                   11145:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   11146:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   11147:                            /* 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)]); */
                   11148:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   11149:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   11150:                          }else{ /* Vn is dummy and Vm is quanti */
                   11151:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11152:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   11153:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11154:                          }
                   11155:                        }else{ /* Vn*Vm Vn is quanti */
                   11156:                          if(DummyV[Tvard[ijp][2]]==0){
                   11157:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   11158:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   11159:                          }else{ /* Both quanti */
                   11160:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   11161:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11162:                          } 
                   11163:                        }
                   11164:                        ijp++;
                   11165:                      }
                   11166:                    } /* end Tprod */
                   11167:                  } /* end if */
                   11168:                  break;
1.349     brouard  11169:                case 3:
                   11170:                  if(cptcovdageprod >0){
                   11171:                    /* if(j==Tprod[ijp]) { /\* *\/  */
                   11172:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   11173:                      if(ijp <=cptcovprod) { /* Product */
1.350     brouard  11174:                        if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   11175:                          if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  11176:                            /* 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  11177:                            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  11178:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   11179:                          }else{ /* Vn is dummy and Vm is quanti */
                   11180:                            /* 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  11181:                            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  11182:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11183:                          }
                   11184:                        }else{ /* Vn*Vm Vn is quanti */
1.350     brouard  11185:                          if(DummyV[Tvardk[ijp][2]]==0){
                   11186:                            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  11187:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   11188:                          }else{ /* Both quanti */
1.350     brouard  11189:                            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  11190:                            /* fprintf(ficgp,"+p%d*%f*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11191:                          } 
                   11192:                        }
                   11193:                        ijp++;
                   11194:                      }
                   11195:                    /* } /\* end Tprod *\/ */
                   11196:                  } /* end if */
                   11197:                  break;
1.329     brouard  11198:                case 0: 
                   11199:                  /* simple covariate */
                   11200:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   11201:                  if(Dummy[j]==0){
                   11202:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   11203:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   11204:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   11205:                  }else{ /* quantitative */
                   11206:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   11207:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   11208:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   11209:                  }
                   11210:                  /* end simple */
                   11211:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   11212:                  break;
                   11213:                default:
                   11214:                  break;
                   11215:                } /* end switch */
1.223     brouard  11216:              }
                   11217:              fprintf(ficgp,")");
                   11218:            }
                   11219:            fprintf(ficgp,")");
                   11220:            if(ng ==2)
1.276     brouard  11221:              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  11222:            else /* ng= 3 */
1.276     brouard  11223:              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  11224:           }else{ /* end ng <> 1 */
1.223     brouard  11225:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  11226:              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  11227:          }
                   11228:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   11229:            fprintf(ficgp,",");
                   11230:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   11231:            fprintf(ficgp,",");
                   11232:          i=i+ncovmodel;
                   11233:        } /* end k */
                   11234:       } /* end k2 */
1.276     brouard  11235:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   11236:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.337     brouard  11237:     } /* end resultline */
1.223     brouard  11238:   } /* end ng */
                   11239:   /* avoid: */
                   11240:   fflush(ficgp); 
1.126     brouard  11241: }  /* end gnuplot */
                   11242: 
                   11243: 
                   11244: /*************** Moving average **************/
1.219     brouard  11245: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  11246:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  11247:    
1.222     brouard  11248:    int i, cpt, cptcod;
                   11249:    int modcovmax =1;
                   11250:    int mobilavrange, mob;
                   11251:    int iage=0;
1.288     brouard  11252:    int firstA1=0, firstA2=0;
1.222     brouard  11253: 
1.266     brouard  11254:    double sum=0., sumr=0.;
1.222     brouard  11255:    double age;
1.266     brouard  11256:    double *sumnewp, *sumnewm, *sumnewmr;
                   11257:    double *agemingood, *agemaxgood; 
                   11258:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  11259:   
                   11260:   
1.278     brouard  11261:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   11262:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  11263: 
                   11264:    sumnewp = vector(1,ncovcombmax);
                   11265:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  11266:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  11267:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  11268:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  11269:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  11270:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  11271: 
                   11272:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  11273:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  11274:      sumnewp[cptcod]=0.;
1.266     brouard  11275:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   11276:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  11277:    }
                   11278:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   11279:   
1.266     brouard  11280:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   11281:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  11282:      else mobilavrange=mobilav;
                   11283:      for (age=bage; age<=fage; age++)
                   11284:        for (i=1; i<=nlstate;i++)
                   11285:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   11286:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   11287:      /* We keep the original values on the extreme ages bage, fage and for 
                   11288:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   11289:        we use a 5 terms etc. until the borders are no more concerned. 
                   11290:      */ 
                   11291:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   11292:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  11293:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   11294:           sumnewm[cptcod]=0.;
                   11295:           for (i=1; i<=nlstate;i++){
1.222     brouard  11296:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   11297:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   11298:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   11299:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   11300:             }
                   11301:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  11302:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   11303:           } /* end i */
                   11304:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   11305:         } /* end cptcod */
1.222     brouard  11306:        }/* end age */
                   11307:      }/* end mob */
1.266     brouard  11308:    }else{
                   11309:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  11310:      return -1;
1.266     brouard  11311:    }
                   11312: 
                   11313:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  11314:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   11315:      if(invalidvarcomb[cptcod]){
                   11316:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   11317:        continue;
                   11318:      }
1.219     brouard  11319: 
1.266     brouard  11320:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   11321:        sumnewm[cptcod]=0.;
                   11322:        sumnewmr[cptcod]=0.;
                   11323:        for (i=1; i<=nlstate;i++){
                   11324:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   11325:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   11326:        }
                   11327:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   11328:         agemingoodr[cptcod]=age;
                   11329:        }
                   11330:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   11331:           agemingood[cptcod]=age;
                   11332:        }
                   11333:      } /* age */
                   11334:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  11335:        sumnewm[cptcod]=0.;
1.266     brouard  11336:        sumnewmr[cptcod]=0.;
1.222     brouard  11337:        for (i=1; i<=nlstate;i++){
                   11338:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  11339:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   11340:        }
                   11341:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   11342:         agemaxgoodr[cptcod]=age;
1.222     brouard  11343:        }
                   11344:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  11345:         agemaxgood[cptcod]=age;
                   11346:        }
                   11347:      } /* age */
                   11348:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   11349:      /* but they will change */
1.288     brouard  11350:      firstA1=0;firstA2=0;
1.266     brouard  11351:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   11352:        sumnewm[cptcod]=0.;
                   11353:        sumnewmr[cptcod]=0.;
                   11354:        for (i=1; i<=nlstate;i++){
                   11355:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   11356:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   11357:        }
                   11358:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   11359:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   11360:           agemaxgoodr[cptcod]=age;  /* age min */
                   11361:           for (i=1; i<=nlstate;i++)
                   11362:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   11363:         }else{ /* bad we change the value with the values of good ages */
                   11364:           for (i=1; i<=nlstate;i++){
                   11365:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   11366:           } /* i */
                   11367:         } /* end bad */
                   11368:        }else{
                   11369:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   11370:           agemaxgood[cptcod]=age;
                   11371:         }else{ /* bad we change the value with the values of good ages */
                   11372:           for (i=1; i<=nlstate;i++){
                   11373:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   11374:           } /* i */
                   11375:         } /* end bad */
                   11376:        }/* end else */
                   11377:        sum=0.;sumr=0.;
                   11378:        for (i=1; i<=nlstate;i++){
                   11379:         sum+=mobaverage[(int)age][i][cptcod];
                   11380:         sumr+=probs[(int)age][i][cptcod];
                   11381:        }
                   11382:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  11383:         if(!firstA1){
                   11384:           firstA1=1;
                   11385:           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);
                   11386:         }
                   11387:         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  11388:        } /* end bad */
                   11389:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   11390:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  11391:         if(!firstA2){
                   11392:           firstA2=1;
                   11393:           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);
                   11394:         }
                   11395:         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  11396:        } /* end bad */
                   11397:      }/* age */
1.266     brouard  11398: 
                   11399:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  11400:        sumnewm[cptcod]=0.;
1.266     brouard  11401:        sumnewmr[cptcod]=0.;
1.222     brouard  11402:        for (i=1; i<=nlstate;i++){
                   11403:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  11404:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   11405:        } 
                   11406:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   11407:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   11408:           agemingoodr[cptcod]=age;
                   11409:           for (i=1; i<=nlstate;i++)
                   11410:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   11411:         }else{ /* bad we change the value with the values of good ages */
                   11412:           for (i=1; i<=nlstate;i++){
                   11413:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   11414:           } /* i */
                   11415:         } /* end bad */
                   11416:        }else{
                   11417:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   11418:           agemingood[cptcod]=age;
                   11419:         }else{ /* bad */
                   11420:           for (i=1; i<=nlstate;i++){
                   11421:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   11422:           } /* i */
                   11423:         } /* end bad */
                   11424:        }/* end else */
                   11425:        sum=0.;sumr=0.;
                   11426:        for (i=1; i<=nlstate;i++){
                   11427:         sum+=mobaverage[(int)age][i][cptcod];
                   11428:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  11429:        }
1.266     brouard  11430:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  11431:         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  11432:        } /* end bad */
                   11433:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   11434:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  11435:         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  11436:        } /* end bad */
                   11437:      }/* age */
1.266     brouard  11438: 
1.222     brouard  11439:                
                   11440:      for (age=bage; age<=fage; age++){
1.235     brouard  11441:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  11442:        sumnewp[cptcod]=0.;
                   11443:        sumnewm[cptcod]=0.;
                   11444:        for (i=1; i<=nlstate;i++){
                   11445:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   11446:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   11447:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   11448:        }
                   11449:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   11450:      }
                   11451:      /* printf("\n"); */
                   11452:      /* } */
1.266     brouard  11453: 
1.222     brouard  11454:      /* brutal averaging */
1.266     brouard  11455:      /* for (i=1; i<=nlstate;i++){ */
                   11456:      /*   for (age=1; age<=bage; age++){ */
                   11457:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   11458:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   11459:      /*   }     */
                   11460:      /*   for (age=fage; age<=AGESUP; age++){ */
                   11461:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   11462:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   11463:      /*   } */
                   11464:      /* } /\* end i status *\/ */
                   11465:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   11466:      /*   for (age=1; age<=AGESUP; age++){ */
                   11467:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   11468:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   11469:      /*   } */
                   11470:      /* } */
1.222     brouard  11471:    }/* end cptcod */
1.266     brouard  11472:    free_vector(agemaxgoodr,1, ncovcombmax);
                   11473:    free_vector(agemaxgood,1, ncovcombmax);
                   11474:    free_vector(agemingood,1, ncovcombmax);
                   11475:    free_vector(agemingoodr,1, ncovcombmax);
                   11476:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  11477:    free_vector(sumnewm,1, ncovcombmax);
                   11478:    free_vector(sumnewp,1, ncovcombmax);
                   11479:    return 0;
                   11480:  }/* End movingaverage */
1.218     brouard  11481:  
1.126     brouard  11482: 
1.296     brouard  11483:  
1.126     brouard  11484: /************** Forecasting ******************/
1.296     brouard  11485: /* 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)*/
                   11486: 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){
                   11487:   /* dateintemean, mean date of interviews
                   11488:      dateprojd, year, month, day of starting projection 
                   11489:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  11490:      agemin, agemax range of age
                   11491:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   11492:   */
1.296     brouard  11493:   /* double anprojd, mprojd, jprojd; */
                   11494:   /* double anprojf, mprojf, jprojf; */
1.359     brouard  11495:   int yearp, stepsize, hstepm, nhstepm, j, k, i, h,  nres=0;
1.126     brouard  11496:   double agec; /* generic age */
1.359     brouard  11497:   double agelim, ppij;
                   11498:   /*double *popcount;*/
1.126     brouard  11499:   double ***p3mat;
1.218     brouard  11500:   /* double ***mobaverage; */
1.126     brouard  11501:   char fileresf[FILENAMELENGTH];
                   11502: 
                   11503:   agelim=AGESUP;
1.211     brouard  11504:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   11505:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   11506:      We still use firstpass and lastpass as another selection.
                   11507:   */
1.214     brouard  11508:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   11509:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  11510:  
1.201     brouard  11511:   strcpy(fileresf,"F_"); 
                   11512:   strcat(fileresf,fileresu);
1.126     brouard  11513:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   11514:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   11515:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   11516:   }
1.235     brouard  11517:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   11518:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  11519: 
1.225     brouard  11520:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  11521: 
                   11522: 
                   11523:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11524:   if (stepm<=12) stepsize=1;
                   11525:   if(estepm < stepm){
                   11526:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   11527:   }
1.270     brouard  11528:   else{
                   11529:     hstepm=estepm;   
                   11530:   }
                   11531:   if(estepm > stepm){ /* Yes every two year */
                   11532:     stepsize=2;
                   11533:   }
1.296     brouard  11534:   hstepm=hstepm/stepm;
1.126     brouard  11535: 
1.296     brouard  11536:   
                   11537:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   11538:   /*                              fractional in yp1 *\/ */
                   11539:   /* aintmean=yp; */
                   11540:   /* yp2=modf((yp1*12),&yp); */
                   11541:   /* mintmean=yp; */
                   11542:   /* yp1=modf((yp2*30.5),&yp); */
                   11543:   /* jintmean=yp; */
                   11544:   /* if(jintmean==0) jintmean=1; */
                   11545:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  11546: 
1.296     brouard  11547: 
                   11548:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   11549:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   11550:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.351     brouard  11551:   /* i1=pow(2,cptcoveff); */
                   11552:   /* if (cptcovn < 1){i1=1;} */
1.126     brouard  11553:   
1.296     brouard  11554:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  11555:   
                   11556:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  11557:   
1.126     brouard  11558: /*           if (h==(int)(YEARM*yearp)){ */
1.351     brouard  11559:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11560:     k=TKresult[nres];
                   11561:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   11562:     /*  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) *\/ */
                   11563:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   11564:     /*   continue; */
                   11565:     /* if(invalidvarcomb[k]){ */
                   11566:     /*   printf("\nCombination (%d) projection ignored because no cases \n",k);  */
                   11567:     /*   continue; */
                   11568:     /* } */
1.227     brouard  11569:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
1.351     brouard  11570:     for(j=1;j<=cptcovs;j++){
                   11571:       /* for(j=1;j<=cptcoveff;j++) { */
                   11572:     /*   /\* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); *\/ */
                   11573:     /*   fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11574:     /* } */
                   11575:     /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11576:     /*   fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11577:     /* } */
                   11578:       fprintf(ficresf," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.235     brouard  11579:     }
1.351     brouard  11580:  
1.227     brouard  11581:     fprintf(ficresf," yearproj age");
                   11582:     for(j=1; j<=nlstate+ndeath;j++){ 
                   11583:       for(i=1; i<=nlstate;i++)               
                   11584:        fprintf(ficresf," p%d%d",i,j);
                   11585:       fprintf(ficresf," wp.%d",j);
                   11586:     }
1.296     brouard  11587:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  11588:       fprintf(ficresf,"\n");
1.296     brouard  11589:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  11590:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   11591:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  11592:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   11593:        nhstepm = nhstepm/hstepm; 
                   11594:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11595:        oldm=oldms;savm=savms;
1.268     brouard  11596:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  11597:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  11598:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  11599:        for (h=0; h<=nhstepm; h++){
                   11600:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  11601:            break;
                   11602:          }
                   11603:        }
                   11604:        fprintf(ficresf,"\n");
1.351     brouard  11605:        /* for(j=1;j<=cptcoveff;j++)  */
                   11606:        for(j=1;j<=cptcovs;j++) 
                   11607:          fprintf(ficresf,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.332     brouard  11608:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
1.351     brouard  11609:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* TnsdVar[Tvaraff]  correct *\/ */
1.296     brouard  11610:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  11611:        
                   11612:        for(j=1; j<=nlstate+ndeath;j++) {
                   11613:          ppij=0.;
                   11614:          for(i=1; i<=nlstate;i++) {
1.278     brouard  11615:            if (mobilav>=1)
                   11616:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   11617:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   11618:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   11619:            }
1.268     brouard  11620:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   11621:          } /* end i */
                   11622:          fprintf(ficresf," %.3f", ppij);
                   11623:        }/* end j */
1.227     brouard  11624:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11625:       } /* end agec */
1.266     brouard  11626:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   11627:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  11628:     } /* end yearp */
                   11629:   } /* end  k */
1.219     brouard  11630:        
1.126     brouard  11631:   fclose(ficresf);
1.215     brouard  11632:   printf("End of Computing forecasting \n");
                   11633:   fprintf(ficlog,"End of Computing forecasting\n");
                   11634: 
1.126     brouard  11635: }
                   11636: 
1.269     brouard  11637: /************** Back Forecasting ******************/
1.296     brouard  11638:  /* 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){ */
                   11639:  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){
                   11640:   /* back1, year, month, day of starting backprojection
1.267     brouard  11641:      agemin, agemax range of age
                   11642:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  11643:      anback2 year of end of backprojection (same day and month as back1).
                   11644:      prevacurrent and prev are prevalences.
1.267     brouard  11645:   */
1.359     brouard  11646:   int yearp, stepsize, hstepm, nhstepm, j, k,  i, h, nres=0;
1.267     brouard  11647:   double agec; /* generic age */
1.359     brouard  11648:   double agelim, ppij, ppi; /* ,jintmean,mintmean,aintmean;*/
                   11649:   /*double *popcount;*/
1.267     brouard  11650:   double ***p3mat;
                   11651:   /* double ***mobaverage; */
                   11652:   char fileresfb[FILENAMELENGTH];
                   11653:  
1.268     brouard  11654:   agelim=AGEINF;
1.267     brouard  11655:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   11656:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   11657:      We still use firstpass and lastpass as another selection.
                   11658:   */
                   11659:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   11660:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   11661: 
                   11662:   /*Do we need to compute prevalence again?*/
                   11663: 
                   11664:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   11665:   
                   11666:   strcpy(fileresfb,"FB_");
                   11667:   strcat(fileresfb,fileresu);
                   11668:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   11669:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   11670:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   11671:   }
                   11672:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   11673:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   11674:   
                   11675:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   11676:   
                   11677:    
                   11678:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11679:   if (stepm<=12) stepsize=1;
                   11680:   if(estepm < stepm){
                   11681:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   11682:   }
1.270     brouard  11683:   else{
                   11684:     hstepm=estepm;   
                   11685:   }
                   11686:   if(estepm >= stepm){ /* Yes every two year */
                   11687:     stepsize=2;
                   11688:   }
1.267     brouard  11689:   
                   11690:   hstepm=hstepm/stepm;
1.296     brouard  11691:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   11692:   /*                              fractional in yp1 *\/ */
                   11693:   /* aintmean=yp; */
                   11694:   /* yp2=modf((yp1*12),&yp); */
                   11695:   /* mintmean=yp; */
                   11696:   /* yp1=modf((yp2*30.5),&yp); */
                   11697:   /* jintmean=yp; */
                   11698:   /* if(jintmean==0) jintmean=1; */
                   11699:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  11700:   
1.351     brouard  11701:   /* i1=pow(2,cptcoveff); */
                   11702:   /* if (cptcovn < 1){i1=1;} */
1.267     brouard  11703:   
1.296     brouard  11704:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   11705:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  11706:   
                   11707:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   11708:   
1.351     brouard  11709:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11710:     k=TKresult[nres];
                   11711:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   11712:   /* for(k=1; k<=i1;k++){ */
                   11713:   /*   if(i1 != 1 && TKresult[nres]!= k) */
                   11714:   /*     continue; */
                   11715:   /*   if(invalidvarcomb[k]){ */
                   11716:   /*     printf("\nCombination (%d) projection ignored because no cases \n",k);  */
                   11717:   /*     continue; */
                   11718:   /*   } */
1.268     brouard  11719:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.351     brouard  11720:     for(j=1;j<=cptcovs;j++){
                   11721:     /* for(j=1;j<=cptcoveff;j++) { */
                   11722:     /*   fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11723:     /* } */
                   11724:       fprintf(ficresfb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.267     brouard  11725:     }
1.351     brouard  11726:    /*  fprintf(ficrespij,"******\n"); */
                   11727:    /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11728:    /*    fprintf(ficresfb," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11729:    /*  } */
1.267     brouard  11730:     fprintf(ficresfb," yearbproj age");
                   11731:     for(j=1; j<=nlstate+ndeath;j++){
                   11732:       for(i=1; i<=nlstate;i++)
1.268     brouard  11733:        fprintf(ficresfb," b%d%d",i,j);
                   11734:       fprintf(ficresfb," b.%d",j);
1.267     brouard  11735:     }
1.296     brouard  11736:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  11737:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   11738:       fprintf(ficresfb,"\n");
1.296     brouard  11739:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  11740:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  11741:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   11742:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  11743:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  11744:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  11745:        nhstepm = nhstepm/hstepm;
                   11746:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11747:        oldm=oldms;savm=savms;
1.268     brouard  11748:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  11749:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  11750:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  11751:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   11752:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   11753:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  11754:        for (h=0; h<=nhstepm; h++){
1.268     brouard  11755:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   11756:            break;
                   11757:          }
                   11758:        }
                   11759:        fprintf(ficresfb,"\n");
1.351     brouard  11760:        /* for(j=1;j<=cptcoveff;j++) */
                   11761:        for(j=1;j<=cptcovs;j++)
                   11762:          fprintf(ficresfb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11763:          /* fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.296     brouard  11764:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  11765:        for(i=1; i<=nlstate+ndeath;i++) {
                   11766:          ppij=0.;ppi=0.;
                   11767:          for(j=1; j<=nlstate;j++) {
                   11768:            /* if (mobilav==1) */
1.269     brouard  11769:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   11770:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   11771:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   11772:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  11773:              /* else { */
                   11774:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   11775:              /* } */
1.268     brouard  11776:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   11777:          } /* end j */
                   11778:          if(ppi <0.99){
                   11779:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   11780:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   11781:          }
                   11782:          fprintf(ficresfb," %.3f", ppij);
                   11783:        }/* end j */
1.267     brouard  11784:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11785:       } /* end agec */
                   11786:     } /* end yearp */
                   11787:   } /* end k */
1.217     brouard  11788:   
1.267     brouard  11789:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  11790:   
1.267     brouard  11791:   fclose(ficresfb);
                   11792:   printf("End of Computing Back forecasting \n");
                   11793:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  11794:        
1.267     brouard  11795: }
1.217     brouard  11796: 
1.269     brouard  11797: /* Variance of prevalence limit: varprlim */
                   11798:  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  11799:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  11800:  
                   11801:    char fileresvpl[FILENAMELENGTH];  
                   11802:    FILE *ficresvpl;
                   11803:    double **oldm, **savm;
                   11804:    double **varpl; /* Variances of prevalence limits by age */   
                   11805:    int i1, k, nres, j ;
                   11806:    
                   11807:     strcpy(fileresvpl,"VPL_");
                   11808:     strcat(fileresvpl,fileresu);
                   11809:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  11810:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  11811:       exit(0);
                   11812:     }
1.288     brouard  11813:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   11814:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  11815:     
                   11816:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   11817:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   11818:     
                   11819:     i1=pow(2,cptcoveff);
                   11820:     if (cptcovn < 1){i1=1;}
                   11821: 
1.337     brouard  11822:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11823:        k=TKresult[nres];
1.338     brouard  11824:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  11825:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
1.269     brouard  11826:       if(i1 != 1 && TKresult[nres]!= k)
                   11827:        continue;
                   11828:       fprintf(ficresvpl,"\n#****** ");
                   11829:       printf("\n#****** ");
                   11830:       fprintf(ficlog,"\n#****** ");
1.337     brouard  11831:       for(j=1;j<=cptcovs;j++) {
                   11832:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11833:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11834:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11835:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11836:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.269     brouard  11837:       }
1.337     brouard  11838:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   11839:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11840:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11841:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11842:       /* }      */
1.269     brouard  11843:       fprintf(ficresvpl,"******\n");
                   11844:       printf("******\n");
                   11845:       fprintf(ficlog,"******\n");
                   11846:       
                   11847:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   11848:       oldm=oldms;savm=savms;
                   11849:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   11850:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   11851:       /*}*/
                   11852:     }
                   11853:     
                   11854:     fclose(ficresvpl);
1.288     brouard  11855:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   11856:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  11857: 
                   11858:  }
                   11859: /* Variance of back prevalence: varbprlim */
                   11860:  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){
                   11861:       /*------- Variance of back (stable) prevalence------*/
                   11862: 
                   11863:    char fileresvbl[FILENAMELENGTH];  
                   11864:    FILE  *ficresvbl;
                   11865: 
                   11866:    double **oldm, **savm;
                   11867:    double **varbpl; /* Variances of back prevalence limits by age */   
                   11868:    int i1, k, nres, j ;
                   11869: 
                   11870:    strcpy(fileresvbl,"VBL_");
                   11871:    strcat(fileresvbl,fileresu);
                   11872:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   11873:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   11874:      exit(0);
                   11875:    }
                   11876:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   11877:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   11878:    
                   11879:    
                   11880:    i1=pow(2,cptcoveff);
                   11881:    if (cptcovn < 1){i1=1;}
                   11882:    
1.337     brouard  11883:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11884:      k=TKresult[nres];
1.338     brouard  11885:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  11886:     /* for(k=1; k<=i1;k++){ */
                   11887:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   11888:     /*          continue; */
1.269     brouard  11889:        fprintf(ficresvbl,"\n#****** ");
                   11890:        printf("\n#****** ");
                   11891:        fprintf(ficlog,"\n#****** ");
1.337     brouard  11892:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
1.338     brouard  11893:         printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   11894:         fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   11895:         fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
1.337     brouard  11896:        /* for(j=1;j<=cptcoveff;j++) { */
                   11897:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11898:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11899:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11900:        /* } */
                   11901:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   11902:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11903:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11904:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
1.269     brouard  11905:        }
                   11906:        fprintf(ficresvbl,"******\n");
                   11907:        printf("******\n");
                   11908:        fprintf(ficlog,"******\n");
                   11909:        
                   11910:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   11911:        oldm=oldms;savm=savms;
                   11912:        
                   11913:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   11914:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   11915:        /*}*/
                   11916:      }
                   11917:    
                   11918:    fclose(ficresvbl);
                   11919:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   11920:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   11921: 
                   11922:  } /* End of varbprlim */
                   11923: 
1.126     brouard  11924: /************** Forecasting *****not tested NB*************/
1.227     brouard  11925: /* 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  11926:   
1.227     brouard  11927: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   11928: /*   int *popage; */
                   11929: /*   double calagedatem, agelim, kk1, kk2; */
                   11930: /*   double *popeffectif,*popcount; */
                   11931: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   11932: /*   /\* double ***mobaverage; *\/ */
                   11933: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  11934: 
1.227     brouard  11935: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   11936: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   11937: /*   agelim=AGESUP; */
                   11938: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  11939:   
1.227     brouard  11940: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  11941:   
                   11942:   
1.227     brouard  11943: /*   strcpy(filerespop,"POP_");  */
                   11944: /*   strcat(filerespop,fileresu); */
                   11945: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   11946: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   11947: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   11948: /*   } */
                   11949: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   11950: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  11951: 
1.227     brouard  11952: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  11953: 
1.227     brouard  11954: /*   /\* if (mobilav!=0) { *\/ */
                   11955: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   11956: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   11957: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   11958: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   11959: /*   /\*   } *\/ */
                   11960: /*   /\* } *\/ */
1.126     brouard  11961: 
1.227     brouard  11962: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   11963: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  11964:   
1.227     brouard  11965: /*   agelim=AGESUP; */
1.126     brouard  11966:   
1.227     brouard  11967: /*   hstepm=1; */
                   11968: /*   hstepm=hstepm/stepm;  */
1.218     brouard  11969:        
1.227     brouard  11970: /*   if (popforecast==1) { */
                   11971: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   11972: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   11973: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   11974: /*     }  */
                   11975: /*     popage=ivector(0,AGESUP); */
                   11976: /*     popeffectif=vector(0,AGESUP); */
                   11977: /*     popcount=vector(0,AGESUP); */
1.126     brouard  11978:     
1.227     brouard  11979: /*     i=1;    */
                   11980: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  11981:     
1.227     brouard  11982: /*     imx=i; */
                   11983: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   11984: /*   } */
1.218     brouard  11985:   
1.227     brouard  11986: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   11987: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   11988: /*       k=k+1; */
                   11989: /*       fprintf(ficrespop,"\n#******"); */
                   11990: /*       for(j=1;j<=cptcoveff;j++) { */
                   11991: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   11992: /*       } */
                   11993: /*       fprintf(ficrespop,"******\n"); */
                   11994: /*       fprintf(ficrespop,"# Age"); */
                   11995: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   11996: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  11997:       
1.227     brouard  11998: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   11999: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  12000:        
1.227     brouard  12001: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   12002: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   12003: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  12004:          
1.227     brouard  12005: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   12006: /*       oldm=oldms;savm=savms; */
                   12007: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  12008:          
1.227     brouard  12009: /*       for (h=0; h<=nhstepm; h++){ */
                   12010: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   12011: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   12012: /*         }  */
                   12013: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   12014: /*           kk1=0.;kk2=0; */
                   12015: /*           for(i=1; i<=nlstate;i++) {               */
                   12016: /*             if (mobilav==1)  */
                   12017: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   12018: /*             else { */
                   12019: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   12020: /*             } */
                   12021: /*           } */
                   12022: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   12023: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   12024: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   12025: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   12026: /*           } */
                   12027: /*         } */
                   12028: /*         for(i=1; i<=nlstate;i++){ */
                   12029: /*           kk1=0.; */
                   12030: /*           for(j=1; j<=nlstate;j++){ */
                   12031: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   12032: /*           } */
                   12033: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   12034: /*         } */
1.218     brouard  12035:            
1.227     brouard  12036: /*         if (h==(int)(calagedatem+12*cpt)) */
                   12037: /*           for(j=1; j<=nlstate;j++)  */
                   12038: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   12039: /*       } */
                   12040: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   12041: /*     } */
                   12042: /*       } */
1.218     brouard  12043:       
1.227     brouard  12044: /*       /\******\/ */
1.218     brouard  12045:       
1.227     brouard  12046: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   12047: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   12048: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   12049: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   12050: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  12051:          
1.227     brouard  12052: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   12053: /*       oldm=oldms;savm=savms; */
                   12054: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   12055: /*       for (h=0; h<=nhstepm; h++){ */
                   12056: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   12057: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   12058: /*         }  */
                   12059: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   12060: /*           kk1=0.;kk2=0; */
                   12061: /*           for(i=1; i<=nlstate;i++) {               */
                   12062: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   12063: /*           } */
                   12064: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   12065: /*         } */
                   12066: /*       } */
                   12067: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   12068: /*     } */
                   12069: /*       } */
                   12070: /*     }  */
                   12071: /*   } */
1.218     brouard  12072:   
1.227     brouard  12073: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  12074:   
1.227     brouard  12075: /*   if (popforecast==1) { */
                   12076: /*     free_ivector(popage,0,AGESUP); */
                   12077: /*     free_vector(popeffectif,0,AGESUP); */
                   12078: /*     free_vector(popcount,0,AGESUP); */
                   12079: /*   } */
                   12080: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   12081: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   12082: /*   fclose(ficrespop); */
                   12083: /* } /\* End of popforecast *\/ */
1.218     brouard  12084:  
1.126     brouard  12085: int fileappend(FILE *fichier, char *optionfich)
                   12086: {
                   12087:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   12088:     printf("Problem with file: %s\n", optionfich);
                   12089:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   12090:     return (0);
                   12091:   }
                   12092:   fflush(fichier);
                   12093:   return (1);
                   12094: }
                   12095: 
                   12096: 
                   12097: /**************** function prwizard **********************/
                   12098: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   12099: {
                   12100: 
                   12101:   /* Wizard to print covariance matrix template */
                   12102: 
1.164     brouard  12103:   char ca[32], cb[32];
                   12104:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  12105:   int numlinepar;
                   12106: 
                   12107:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12108:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12109:   for(i=1; i <=nlstate; i++){
                   12110:     jj=0;
                   12111:     for(j=1; j <=nlstate+ndeath; j++){
                   12112:       if(j==i) continue;
                   12113:       jj++;
                   12114:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   12115:       printf("%1d%1d",i,j);
                   12116:       fprintf(ficparo,"%1d%1d",i,j);
                   12117:       for(k=1; k<=ncovmodel;k++){
                   12118:        /*        printf(" %lf",param[i][j][k]); */
                   12119:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   12120:        printf(" 0.");
                   12121:        fprintf(ficparo," 0.");
                   12122:       }
                   12123:       printf("\n");
                   12124:       fprintf(ficparo,"\n");
                   12125:     }
                   12126:   }
                   12127:   printf("# Scales (for hessian or gradient estimation)\n");
                   12128:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   12129:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   12130:   for(i=1; i <=nlstate; i++){
                   12131:     jj=0;
                   12132:     for(j=1; j <=nlstate+ndeath; j++){
                   12133:       if(j==i) continue;
                   12134:       jj++;
                   12135:       fprintf(ficparo,"%1d%1d",i,j);
                   12136:       printf("%1d%1d",i,j);
                   12137:       fflush(stdout);
                   12138:       for(k=1; k<=ncovmodel;k++){
                   12139:        /*      printf(" %le",delti3[i][j][k]); */
                   12140:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   12141:        printf(" 0.");
                   12142:        fprintf(ficparo," 0.");
                   12143:       }
                   12144:       numlinepar++;
                   12145:       printf("\n");
                   12146:       fprintf(ficparo,"\n");
                   12147:     }
                   12148:   }
                   12149:   printf("# Covariance matrix\n");
                   12150: /* # 121 Var(a12)\n\ */
                   12151: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   12152: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   12153: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   12154: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   12155: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   12156: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   12157: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   12158:   fflush(stdout);
                   12159:   fprintf(ficparo,"# Covariance matrix\n");
                   12160:   /* # 121 Var(a12)\n\ */
                   12161:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   12162:   /* #   ...\n\ */
                   12163:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   12164:   
                   12165:   for(itimes=1;itimes<=2;itimes++){
                   12166:     jj=0;
                   12167:     for(i=1; i <=nlstate; i++){
                   12168:       for(j=1; j <=nlstate+ndeath; j++){
                   12169:        if(j==i) continue;
                   12170:        for(k=1; k<=ncovmodel;k++){
                   12171:          jj++;
                   12172:          ca[0]= k+'a'-1;ca[1]='\0';
                   12173:          if(itimes==1){
                   12174:            printf("#%1d%1d%d",i,j,k);
                   12175:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   12176:          }else{
                   12177:            printf("%1d%1d%d",i,j,k);
                   12178:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   12179:            /*  printf(" %.5le",matcov[i][j]); */
                   12180:          }
                   12181:          ll=0;
                   12182:          for(li=1;li <=nlstate; li++){
                   12183:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   12184:              if(lj==li) continue;
                   12185:              for(lk=1;lk<=ncovmodel;lk++){
                   12186:                ll++;
                   12187:                if(ll<=jj){
                   12188:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   12189:                  if(ll<jj){
                   12190:                    if(itimes==1){
                   12191:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12192:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12193:                    }else{
                   12194:                      printf(" 0.");
                   12195:                      fprintf(ficparo," 0.");
                   12196:                    }
                   12197:                  }else{
                   12198:                    if(itimes==1){
                   12199:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   12200:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   12201:                    }else{
                   12202:                      printf(" 0.");
                   12203:                      fprintf(ficparo," 0.");
                   12204:                    }
                   12205:                  }
                   12206:                }
                   12207:              } /* end lk */
                   12208:            } /* end lj */
                   12209:          } /* end li */
                   12210:          printf("\n");
                   12211:          fprintf(ficparo,"\n");
                   12212:          numlinepar++;
                   12213:        } /* end k*/
                   12214:       } /*end j */
                   12215:     } /* end i */
                   12216:   } /* end itimes */
                   12217: 
                   12218: } /* end of prwizard */
                   12219: /******************* Gompertz Likelihood ******************************/
                   12220: double gompertz(double x[])
                   12221: { 
1.302     brouard  12222:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  12223:   int i,n=0; /* n is the size of the sample */
                   12224: 
1.220     brouard  12225:   for (i=1;i<=imx ; i++) {
1.126     brouard  12226:     sump=sump+weight[i];
                   12227:     /*    sump=sump+1;*/
                   12228:     num=num+1;
                   12229:   }
1.302     brouard  12230:   L=0.0;
                   12231:   /* agegomp=AGEGOMP; */
1.126     brouard  12232:   /* for (i=0; i<=imx; i++) 
                   12233:      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]);*/
                   12234: 
1.302     brouard  12235:   for (i=1;i<=imx ; i++) {
                   12236:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   12237:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   12238:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   12239:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   12240:      * +
                   12241:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   12242:      */
                   12243:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   12244:        if (cens[i] == 1){
                   12245:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   12246:        } else if (cens[i] == 0){
1.126     brouard  12247:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  12248:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   12249:       } else
                   12250:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  12251:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  12252:        L=L+A*weight[i];
1.126     brouard  12253:        /*      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  12254:      }
                   12255:   }
1.126     brouard  12256: 
1.302     brouard  12257:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  12258:  
                   12259:   return -2*L*num/sump;
                   12260: }
                   12261: 
1.136     brouard  12262: #ifdef GSL
                   12263: /******************* Gompertz_f Likelihood ******************************/
                   12264: double gompertz_f(const gsl_vector *v, void *params)
                   12265: { 
1.302     brouard  12266:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  12267:   double *x= (double *) v->data;
                   12268:   int i,n=0; /* n is the size of the sample */
                   12269: 
                   12270:   for (i=0;i<=imx-1 ; i++) {
                   12271:     sump=sump+weight[i];
                   12272:     /*    sump=sump+1;*/
                   12273:     num=num+1;
                   12274:   }
                   12275:  
                   12276:  
                   12277:   /* for (i=0; i<=imx; i++) 
                   12278:      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]);*/
                   12279:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   12280:   for (i=1;i<=imx ; i++)
                   12281:     {
                   12282:       if (cens[i] == 1 && wav[i]>1)
                   12283:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   12284:       
                   12285:       if (cens[i] == 0 && wav[i]>1)
                   12286:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   12287:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   12288:       
                   12289:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   12290:       if (wav[i] > 1 ) { /* ??? */
                   12291:        LL=LL+A*weight[i];
                   12292:        /*      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]);*/
                   12293:       }
                   12294:     }
                   12295: 
                   12296:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   12297:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   12298:  
                   12299:   return -2*LL*num/sump;
                   12300: }
                   12301: #endif
                   12302: 
1.126     brouard  12303: /******************* Printing html file ***********/
1.201     brouard  12304: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  12305:                  int lastpass, int stepm, int weightopt, char model[],\
                   12306:                  int imx,  double p[],double **matcov,double agemortsup){
                   12307:   int i,k;
                   12308: 
                   12309:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   12310:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   12311:   for (i=1;i<=2;i++) 
                   12312:     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  12313:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  12314:   fprintf(fichtm,"</ul>");
                   12315: 
                   12316: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   12317: 
                   12318:  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>");
                   12319: 
                   12320:  for (k=agegomp;k<(agemortsup-2);k++) 
                   12321:    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]);
                   12322: 
                   12323:  
                   12324:   fflush(fichtm);
                   12325: }
                   12326: 
                   12327: /******************* Gnuplot file **************/
1.201     brouard  12328: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  12329: 
                   12330:   char dirfileres[132],optfileres[132];
1.164     brouard  12331: 
1.359     brouard  12332:   /*int ng;*/
1.126     brouard  12333: 
                   12334: 
                   12335:   /*#ifdef windows */
                   12336:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   12337:     /*#endif */
                   12338: 
                   12339: 
                   12340:   strcpy(dirfileres,optionfilefiname);
                   12341:   strcpy(optfileres,"vpl");
1.199     brouard  12342:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  12343:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  12344:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  12345:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  12346:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   12347: 
                   12348: } 
                   12349: 
1.136     brouard  12350: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   12351: {
1.126     brouard  12352: 
1.136     brouard  12353:   /*-------- data file ----------*/
                   12354:   FILE *fic;
                   12355:   char dummy[]="                         ";
1.359     brouard  12356:   int i = 0, j = 0, n = 0, iv = 0;/* , v;*/
1.223     brouard  12357:   int lstra;
1.136     brouard  12358:   int linei, month, year,iout;
1.302     brouard  12359:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  12360:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  12361:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  12362:   char *stratrunc;
1.223     brouard  12363: 
1.349     brouard  12364:   /* DummyV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
                   12365:   /* FixedV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
1.339     brouard  12366:   
                   12367:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
                   12368:   
1.136     brouard  12369:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  12370:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   12371:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  12372:   }
1.126     brouard  12373: 
1.302     brouard  12374:     /* Is it a BOM UTF-8 Windows file? */
                   12375:   /* First data line */
                   12376:   linei=0;
                   12377:   while(fgets(line, MAXLINE, fic)) {
                   12378:     noffset=0;
                   12379:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   12380:     {
                   12381:       noffset=noffset+3;
                   12382:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   12383:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   12384:       fflush(ficlog); return 1;
                   12385:     }
                   12386:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   12387:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   12388:     {
                   12389:       noffset=noffset+2;
1.304     brouard  12390:       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);
                   12391:       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  12392:       fflush(ficlog); return 1;
                   12393:     }
                   12394:     else if( line[0] == 0 && line[1] == 0)
                   12395:     {
                   12396:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   12397:        noffset=noffset+4;
1.304     brouard  12398:        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);
                   12399:        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  12400:        fflush(ficlog); return 1;
                   12401:       }
                   12402:     } else{
                   12403:       ;/*printf(" Not a BOM file\n");*/
                   12404:     }
                   12405:         /* If line starts with a # it is a comment */
                   12406:     if (line[noffset] == '#') {
                   12407:       linei=linei+1;
                   12408:       break;
                   12409:     }else{
                   12410:       break;
                   12411:     }
                   12412:   }
                   12413:   fclose(fic);
                   12414:   if((fic=fopen(datafile,"r"))==NULL)    {
                   12415:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   12416:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   12417:   }
                   12418:   /* Not a Bom file */
                   12419:   
1.136     brouard  12420:   i=1;
                   12421:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   12422:     linei=linei+1;
                   12423:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   12424:       if(line[j] == '\t')
                   12425:        line[j] = ' ';
                   12426:     }
                   12427:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   12428:       ;
                   12429:     };
                   12430:     line[j+1]=0;  /* Trims blanks at end of line */
                   12431:     if(line[0]=='#'){
                   12432:       fprintf(ficlog,"Comment line\n%s\n",line);
                   12433:       printf("Comment line\n%s\n",line);
                   12434:       continue;
                   12435:     }
                   12436:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  12437:     strcpy(line, linetmp);
1.223     brouard  12438:     
                   12439:     /* Loops on waves */
                   12440:     for (j=maxwav;j>=1;j--){
                   12441:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  12442:        cutv(stra, strb, line, ' '); 
                   12443:        if(strb[0]=='.') { /* Missing value */
                   12444:          lval=-1;
                   12445:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
1.341     brouard  12446:          cotvar[j][ncovcol+nqv+ntv+iv][i]=-1; /* For performance reasons */
1.238     brouard  12447:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   12448:            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);
                   12449:            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);
                   12450:            return 1;
                   12451:          }
                   12452:        }else{
                   12453:          errno=0;
                   12454:          /* what_kind_of_number(strb); */
                   12455:          dval=strtod(strb,&endptr); 
                   12456:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   12457:          /* if(strb != endptr && *endptr == '\0') */
                   12458:          /*    dval=dlval; */
                   12459:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   12460:          if( strb[0]=='\0' || (*endptr != '\0')){
                   12461:            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);
                   12462:            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);
                   12463:            return 1;
                   12464:          }
                   12465:          cotqvar[j][iv][i]=dval; 
1.341     brouard  12466:          cotvar[j][ncovcol+nqv+ntv+iv][i]=dval; /* because cotvar starts now at first ntv */ 
1.238     brouard  12467:        }
                   12468:        strcpy(line,stra);
1.223     brouard  12469:       }/* end loop ntqv */
1.225     brouard  12470:       
1.223     brouard  12471:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  12472:        cutv(stra, strb, line, ' '); 
                   12473:        if(strb[0]=='.') { /* Missing value */
                   12474:          lval=-1;
                   12475:        }else{
                   12476:          errno=0;
                   12477:          lval=strtol(strb,&endptr,10); 
                   12478:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   12479:          if( strb[0]=='\0' || (*endptr != '\0')){
                   12480:            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);
                   12481:            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);
                   12482:            return 1;
                   12483:          }
                   12484:        }
                   12485:        if(lval <-1 || lval >1){
                   12486:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  12487:  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  12488:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  12489:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   12490:  build V1=0 V2=0 for the reference value (1),\n                                \
                   12491:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  12492:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  12493:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  12494:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  12495:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  12496:  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  12497:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  12498:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   12499:  build V1=0 V2=0 for the reference value (1),\n                                \
                   12500:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  12501:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  12502:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  12503:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  12504:          return 1;
                   12505:        }
1.341     brouard  12506:        cotvar[j][ncovcol+nqv+iv][i]=(double)(lval);
1.238     brouard  12507:        strcpy(line,stra);
1.223     brouard  12508:       }/* end loop ntv */
1.225     brouard  12509:       
1.223     brouard  12510:       /* Statuses  at wave */
1.137     brouard  12511:       cutv(stra, strb, line, ' '); 
1.223     brouard  12512:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  12513:        lval=-1;
1.136     brouard  12514:       }else{
1.238     brouard  12515:        errno=0;
                   12516:        lval=strtol(strb,&endptr,10); 
                   12517:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
1.347     brouard  12518:        if( strb[0]=='\0' || (*endptr != '\0' )){
                   12519:          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);
                   12520:          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);
                   12521:          return 1;
                   12522:        }else if( lval==0 || lval > nlstate+ndeath){
1.348     brouard  12523:          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);
                   12524:          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  12525:          return 1;
                   12526:        }
1.136     brouard  12527:       }
1.225     brouard  12528:       
1.136     brouard  12529:       s[j][i]=lval;
1.225     brouard  12530:       
1.223     brouard  12531:       /* Date of Interview */
1.136     brouard  12532:       strcpy(line,stra);
                   12533:       cutv(stra, strb,line,' ');
1.169     brouard  12534:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  12535:       }
1.169     brouard  12536:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  12537:        month=99;
                   12538:        year=9999;
1.136     brouard  12539:       }else{
1.225     brouard  12540:        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);
                   12541:        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);
                   12542:        return 1;
1.136     brouard  12543:       }
                   12544:       anint[j][i]= (double) year; 
1.302     brouard  12545:       mint[j][i]= (double)month;
                   12546:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   12547:       /*       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]); */
                   12548:       /*       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]); */
                   12549:       /* } */
1.136     brouard  12550:       strcpy(line,stra);
1.223     brouard  12551:     } /* End loop on waves */
1.225     brouard  12552:     
1.223     brouard  12553:     /* Date of death */
1.136     brouard  12554:     cutv(stra, strb,line,' '); 
1.169     brouard  12555:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  12556:     }
1.169     brouard  12557:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  12558:       month=99;
                   12559:       year=9999;
                   12560:     }else{
1.141     brouard  12561:       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  12562:       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);
                   12563:       return 1;
1.136     brouard  12564:     }
                   12565:     andc[i]=(double) year; 
                   12566:     moisdc[i]=(double) month; 
                   12567:     strcpy(line,stra);
                   12568:     
1.223     brouard  12569:     /* Date of birth */
1.136     brouard  12570:     cutv(stra, strb,line,' '); 
1.169     brouard  12571:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  12572:     }
1.169     brouard  12573:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  12574:       month=99;
                   12575:       year=9999;
                   12576:     }else{
1.141     brouard  12577:       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);
                   12578:       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  12579:       return 1;
1.136     brouard  12580:     }
                   12581:     if (year==9999) {
1.141     brouard  12582:       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);
                   12583:       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  12584:       return 1;
                   12585:       
1.136     brouard  12586:     }
                   12587:     annais[i]=(double)(year);
1.302     brouard  12588:     moisnais[i]=(double)(month);
                   12589:     for (j=1;j<=maxwav;j++){
                   12590:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   12591:        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]);
                   12592:        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]);
                   12593:       }
                   12594:     }
                   12595: 
1.136     brouard  12596:     strcpy(line,stra);
1.225     brouard  12597:     
1.223     brouard  12598:     /* Sample weight */
1.136     brouard  12599:     cutv(stra, strb,line,' '); 
                   12600:     errno=0;
                   12601:     dval=strtod(strb,&endptr); 
                   12602:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  12603:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   12604:       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  12605:       fflush(ficlog);
                   12606:       return 1;
                   12607:     }
                   12608:     weight[i]=dval; 
                   12609:     strcpy(line,stra);
1.225     brouard  12610:     
1.223     brouard  12611:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   12612:       cutv(stra, strb, line, ' '); 
                   12613:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  12614:        lval=-1;
1.311     brouard  12615:        coqvar[iv][i]=NAN; 
                   12616:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  12617:       }else{
1.225     brouard  12618:        errno=0;
                   12619:        /* what_kind_of_number(strb); */
                   12620:        dval=strtod(strb,&endptr);
                   12621:        /* if(strb != endptr && *endptr == '\0') */
                   12622:        /*   dval=dlval; */
                   12623:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   12624:        if( strb[0]=='\0' || (*endptr != '\0')){
                   12625:          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);
                   12626:          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);
                   12627:          return 1;
                   12628:        }
                   12629:        coqvar[iv][i]=dval; 
1.226     brouard  12630:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  12631:       }
                   12632:       strcpy(line,stra);
                   12633:     }/* end loop nqv */
1.136     brouard  12634:     
1.223     brouard  12635:     /* Covariate values */
1.136     brouard  12636:     for (j=ncovcol;j>=1;j--){
                   12637:       cutv(stra, strb,line,' '); 
1.223     brouard  12638:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  12639:        lval=-1;
1.136     brouard  12640:       }else{
1.225     brouard  12641:        errno=0;
                   12642:        lval=strtol(strb,&endptr,10); 
                   12643:        if( strb[0]=='\0' || (*endptr != '\0')){
                   12644:          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);
                   12645:          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);
                   12646:          return 1;
                   12647:        }
1.136     brouard  12648:       }
                   12649:       if(lval <-1 || lval >1){
1.225     brouard  12650:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  12651:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   12652:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  12653:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   12654:  build V1=0 V2=0 for the reference value (1),\n                                \
                   12655:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  12656:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  12657:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  12658:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  12659:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  12660:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   12661:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  12662:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   12663:  build V1=0 V2=0 for the reference value (1),\n                                \
                   12664:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  12665:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  12666:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  12667:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  12668:        return 1;
1.136     brouard  12669:       }
                   12670:       covar[j][i]=(double)(lval);
                   12671:       strcpy(line,stra);
                   12672:     }  
                   12673:     lstra=strlen(stra);
1.225     brouard  12674:     
1.136     brouard  12675:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   12676:       stratrunc = &(stra[lstra-9]);
                   12677:       num[i]=atol(stratrunc);
                   12678:     }
                   12679:     else
                   12680:       num[i]=atol(stra);
                   12681:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   12682:       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;}*/
                   12683:     
                   12684:     i=i+1;
                   12685:   } /* End loop reading  data */
1.225     brouard  12686:   
1.136     brouard  12687:   *imax=i-1; /* Number of individuals */
                   12688:   fclose(fic);
1.225     brouard  12689:   
1.136     brouard  12690:   return (0);
1.164     brouard  12691:   /* endread: */
1.225     brouard  12692:   printf("Exiting readdata: ");
                   12693:   fclose(fic);
                   12694:   return (1);
1.223     brouard  12695: }
1.126     brouard  12696: 
1.234     brouard  12697: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  12698:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  12699:   while (*p2 == ' ')
1.234     brouard  12700:     p2++; 
                   12701:   /* while ((*p1++ = *p2++) !=0) */
                   12702:   /*   ; */
                   12703:   /* do */
                   12704:   /*   while (*p2 == ' ') */
                   12705:   /*     p2++; */
                   12706:   /* while (*p1++ == *p2++); */
                   12707:   *stri=p2; 
1.145     brouard  12708: }
                   12709: 
1.330     brouard  12710: int decoderesult( char resultline[], int nres)
1.230     brouard  12711: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   12712: {
1.235     brouard  12713:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  12714:   char resultsav[MAXLINE];
1.330     brouard  12715:   /* int resultmodel[MAXLINE]; */
1.334     brouard  12716:   /* int modelresult[MAXLINE]; */
1.230     brouard  12717:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   12718: 
1.234     brouard  12719:   removefirstspace(&resultline);
1.332     brouard  12720:   printf("decoderesult:%s\n",resultline);
1.230     brouard  12721: 
1.332     brouard  12722:   strcpy(resultsav,resultline);
1.342     brouard  12723:   /* printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline); */
1.230     brouard  12724:   if (strlen(resultsav) >1){
1.334     brouard  12725:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  12726:   }
1.353     brouard  12727:   if(j == 0 && cptcovs== 0){ /* Resultline but no =  and no covariate in the model */
1.253     brouard  12728:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   12729:     return (0);
                   12730:   }
1.234     brouard  12731:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.353     brouard  12732:     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);
                   12733:     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);
                   12734:     if(j==0)
                   12735:       return 1;
1.234     brouard  12736:   }
1.334     brouard  12737:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  12738:     if(nbocc(resultsav,'=') >1){
1.318     brouard  12739:       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  12740:       /* 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  12741:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  12742:       /* If a blank, then strc="V4=" and strd='\0' */
                   12743:       if(strc[0]=='\0'){
                   12744:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   12745:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   12746:        return 1;
                   12747:       }
1.234     brouard  12748:     }else
                   12749:       cutl(strc,strd,resultsav,'=');
1.318     brouard  12750:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  12751:     
1.230     brouard  12752:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  12753:     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  12754:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   12755:     /* cptcovsel++;     */
                   12756:     if (nbocc(stra,'=') >0)
                   12757:       strcpy(resultsav,stra); /* and analyzes it */
                   12758:   }
1.235     brouard  12759:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  12760:   /* 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  12761:   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  12762:     if(Typevar[k1]==0){ /* Single covariate in model */
                   12763:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  12764:       match=0;
1.318     brouard  12765:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   12766:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  12767:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  12768:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  12769:          break;
                   12770:        }
                   12771:       }
                   12772:       if(match == 0){
1.338     brouard  12773:        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]);
                   12774:        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  12775:        return 1;
1.234     brouard  12776:       }
1.332     brouard  12777:     }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*/
                   12778:       /* We feed resultmodel[k1]=k2; */
                   12779:       match=0;
                   12780:       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 */
                   12781:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  12782:          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  12783:          resultmodel[nres][k1]=k2; /* Added here */
1.342     brouard  12784:          /* printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]); */
1.332     brouard  12785:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   12786:          break;
                   12787:        }
                   12788:       }
                   12789:       if(match == 0){
1.338     brouard  12790:        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]);
                   12791:        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  12792:       return 1;
                   12793:       }
1.349     brouard  12794:     }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  12795:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   12796:       match=0;
1.342     brouard  12797:       /* 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  12798:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   12799:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   12800:          /* modelresult[k2]=k1; */
1.342     brouard  12801:          /* printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]); */
1.332     brouard  12802:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   12803:        }
                   12804:       }
                   12805:       if(match == 0){
1.349     brouard  12806:        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);
                   12807:        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  12808:        return 1;
                   12809:       }
                   12810:       match=0;
                   12811:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   12812:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   12813:          /* modelresult[k2]=k1;*/
1.342     brouard  12814:          /* printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]); */
1.332     brouard  12815:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   12816:          break;
                   12817:        }
                   12818:       }
                   12819:       if(match == 0){
1.349     brouard  12820:        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);
                   12821:        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  12822:        return 1;
                   12823:       }
                   12824:     }/* End of testing */
1.333     brouard  12825:   }/* End loop cptcovt */
1.235     brouard  12826:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  12827:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  12828:   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)
                   12829:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  12830:     match=0;
1.318     brouard  12831:     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  12832:       if(Typevar[k1]==0){ /* Single only */
1.349     brouard  12833:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4  What if a product?  */
1.330     brouard  12834:          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  12835:          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  12836:          ++match;
                   12837:        }
                   12838:       }
                   12839:     }
                   12840:     if(match == 0){
1.338     brouard  12841:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   12842:       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  12843:       return 1;
1.234     brouard  12844:     }else if(match > 1){
1.338     brouard  12845:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   12846:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
1.310     brouard  12847:       return 1;
1.234     brouard  12848:     }
                   12849:   }
1.334     brouard  12850:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  12851:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  12852:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  12853:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   12854:   /* 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*/
                   12855:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  12856:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   12857:   /*    1 0 0 0 */
                   12858:   /*    2 1 0 0 */
                   12859:   /*    3 0 1 0 */ 
1.330     brouard  12860:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  12861:   /*    5 0 0 1 */
1.330     brouard  12862:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  12863:   /*    7 0 1 1 */
                   12864:   /*    8 1 1 1 */
1.237     brouard  12865:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   12866:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   12867:   /* V5*age V5 known which value for nres?  */
                   12868:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  12869:   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.
                   12870:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  12871:     /* k counting number of combination of single dummies in the equation model */
                   12872:     /* k4 counting single dummies in the equation model */
                   12873:     /* k4q counting single quantitatives in the equation model */
1.344     brouard  12874:     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  12875:        /* 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  12876:       /* 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  12877:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  12878:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   12879:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   12880:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   12881:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   12882:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  12883:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  12884:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  12885:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  12886:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   12887:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   12888:       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  12889:       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  12890:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  12891:       /* Tinvresult[nres][4]=1 */
1.334     brouard  12892:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   12893:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   12894:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   12895:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  12896:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  12897:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.342     brouard  12898:       /* 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  12899:       k4++;;
1.331     brouard  12900:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  12901:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  12902:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  12903:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  12904:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   12905:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   12906:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  12907:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   12908:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   12909:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   12910:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   12911:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   12912:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  12913:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  12914:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  12915:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  12916:       /* 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  12917:       k4q++;;
1.350     brouard  12918:     }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"*/
                   12919:       /* Tvar[k1]; */ /* Age variable */ /* 17 age*V6*V2 ?*/
1.332     brouard  12920:       /* Wrong we want the value of variable name Tvar[k1] */
1.350     brouard  12921:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   12922:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   12923:       /* 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]]); */
                   12924:       }else{
                   12925:        k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   12926:        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)*/
                   12927:        TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
                   12928:        precov[nres][k1]=Tvalsel[k3];
                   12929:       }
1.342     brouard  12930:       /* 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  12931:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.350     brouard  12932:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   12933:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   12934:       /* 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]]); */
                   12935:       }else{
                   12936:        k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
                   12937:        k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
                   12938:        TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
                   12939:        precov[nres][k1]=Tvalsel[k3q];
                   12940:       }
1.342     brouard  12941:       /* 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  12942:     }else if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
1.332     brouard  12943:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
1.342     brouard  12944:       /* 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  12945:     }else{
1.332     brouard  12946:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   12947:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  12948:     }
                   12949:   }
1.234     brouard  12950:   
1.334     brouard  12951:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  12952:   return (0);
                   12953: }
1.235     brouard  12954: 
1.230     brouard  12955: int decodemodel( char model[], int lastobs)
                   12956:  /**< This routine decodes the model and returns:
1.224     brouard  12957:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   12958:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   12959:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   12960:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   12961:        * - cptcovage number of covariates with age*products =2
                   12962:        * - cptcovs number of simple covariates
1.339     brouard  12963:        * ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
1.224     brouard  12964:        * - 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  12965:        *     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
1.319     brouard  12966:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  12967:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   12968:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   12969:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   12970:        */
1.319     brouard  12971: /* 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  12972: {
1.359     brouard  12973:   int i, j, k, ks;/* , v;*/
1.349     brouard  12974:   int n,m;
                   12975:   int  j1, k1, k11, k12, k2, k3, k4;
                   12976:   char modelsav[300];
                   12977:   char stra[300], strb[300], strc[300], strd[300],stre[300],strf[300];
1.187     brouard  12978:   char *strpt;
1.349     brouard  12979:   int  **existcomb;
                   12980:   
                   12981:   existcomb=imatrix(1,NCOVMAX,1,NCOVMAX);
                   12982:   for(i=1;i<=NCOVMAX;i++)
                   12983:     for(j=1;j<=NCOVMAX;j++)
                   12984:       existcomb[i][j]=0;
                   12985:     
1.145     brouard  12986:   /*removespace(model);*/
1.136     brouard  12987:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.349     brouard  12988:     j=0, j1=0, k1=0, k12=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  12989:     if (strstr(model,"AGE") !=0){
1.192     brouard  12990:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   12991:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  12992:       return 1;
                   12993:     }
1.141     brouard  12994:     if (strstr(model,"v") !=0){
1.338     brouard  12995:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
                   12996:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
1.141     brouard  12997:       return 1;
                   12998:     }
1.187     brouard  12999:     strcpy(modelsav,model); 
                   13000:     if ((strpt=strstr(model,"age*age")) !=0){
1.338     brouard  13001:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
1.187     brouard  13002:       if(strpt != model){
1.338     brouard  13003:        printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  13004:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  13005:  corresponding column of parameters.\n",model);
1.338     brouard  13006:        fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  13007:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  13008:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  13009:        return 1;
1.225     brouard  13010:       }
1.187     brouard  13011:       nagesqr=1;
                   13012:       if (strstr(model,"+age*age") !=0)
1.234     brouard  13013:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  13014:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  13015:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  13016:       else 
1.234     brouard  13017:        substrchaine(modelsav, model, "age*age");
1.187     brouard  13018:     }else
                   13019:       nagesqr=0;
1.349     brouard  13020:     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  13021:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   13022:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.351     brouard  13023:       cptcovs=0; /**<  Number of simple covariates V1 +V1*age +V3 +V3*V4 +age*age => V1 + V3 =4+1-3=2  Wrong */
1.187     brouard  13024:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  13025:                     * cst, age and age*age 
                   13026:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   13027:       /* including age products which are counted in cptcovage.
                   13028:        * but the covariates which are products must be treated 
                   13029:        * separately: ncovn=4- 2=2 (V1+V3). */
1.349     brouard  13030:       cptcovprod=0; /**< Number of products  V1*V2 +v3*age = 2 */
                   13031:       cptcovdageprod=0; /* Number of doouble products with age age*Vn*VM or Vn*age*Vm or Vn*Vm*age */
1.187     brouard  13032:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.349     brouard  13033:       cptcovprodage=0;
                   13034:       /* cptcovprodage=nboccstr(modelsav,"age");*/
1.225     brouard  13035:       
1.187     brouard  13036:       /*   Design
                   13037:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   13038:        *  <          ncovcol=8                >
                   13039:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   13040:        *   k=  1    2      3       4     5       6      7        8
                   13041:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
1.345     brouard  13042:        *  covar[k,i], are for fixed covariates, value of kth covariate if not including age for individual i:
1.224     brouard  13043:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   13044:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  13045:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   13046:        *  Tage[++cptcovage]=k
1.345     brouard  13047:        *       if products, new covar are created after ncovcol + nqv (quanti fixed) with k1
1.187     brouard  13048:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   13049:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   13050:        *  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
                   13051:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   13052:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   13053:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
1.345     brouard  13054:        *  <          ncovcol=8  8 fixed covariate. Additional starts at 9 (V5*V6) and 10(V7*V8)              >
1.187     brouard  13055:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   13056:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
1.345     brouard  13057:        *     Tvard[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   13058:        * p Tvar[1]@12={2,   1,     3,      3,   9,     10,     8,       8}
1.187     brouard  13059:        * p Tprod[1]@2={                         6, 5}
                   13060:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   13061:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   13062:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  13063:        *How to reorganize? Tvars(orted)
1.187     brouard  13064:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   13065:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   13066:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   13067:        * Struct []
                   13068:        */
1.225     brouard  13069:       
1.187     brouard  13070:       /* This loop fills the array Tvar from the string 'model'.*/
                   13071:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   13072:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   13073:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   13074:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   13075:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   13076:       /*       k=1 Tvar[1]=2 (from V2) */
                   13077:       /*       k=5 Tvar[5] */
                   13078:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  13079:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  13080:       /*       } */
1.198     brouard  13081:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  13082:       /*
                   13083:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  13084:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   13085:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   13086:       }
1.187     brouard  13087:       cptcovage=0;
1.351     brouard  13088: 
                   13089:       /* First loop in order to calculate */
                   13090:       /* for age*VN*Vm
                   13091:        * Provides, Typevar[k], Tage[cptcovage], existcomb[n][m], FixedV[ncovcolt+k12]
                   13092:        * Tprod[k1]=k  Tposprod[k]=k1;    Tvard[k1][1] =m;
                   13093:       */
                   13094:       /* Needs  FixedV[Tvardk[k][1]] */
                   13095:       /* For others:
                   13096:        * Sets  Typevar[k];
                   13097:        * Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   13098:        *       Tposprod[k]=k11;
                   13099:        *       Tprod[k11]=k;
                   13100:        *       Tvardk[k][1] =m;
                   13101:        * Needs FixedV[Tvardk[k][1]] == 0
                   13102:       */
                   13103:       
1.319     brouard  13104:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   13105:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   13106:                                         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" */
                   13107:        if (nbocc(modelsav,'+')==0)
                   13108:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  13109:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   13110:        /*scanf("%d",i);*/
1.349     brouard  13111:        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 */
                   13112:          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  */
                   13113:          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   */
                   13114:            Typevar[k]=3;  /* 3 for age and double product age*Vn*Vm varying of fixed */
                   13115:             if(strstr(strc,"age")!=0) { /* It means that strc=V2*age or age*V2 and thus that strd=Vn */
                   13116:               cutl(stre,strf,strc,'*') ; /* strf=age or Vm, stre=Vm or age. If strc=V6*V2 then strf=V6 and stre=V2 */
                   13117:              strcpy(strc,strb); /* save strb(=age*Vn*Vm) into strc */
                   13118:              /* We want strb=Vn*Vm */
                   13119:               if(strcmp(strf,"age")==0){ /* strf is "age" so that stre=Vm =V2 . */
                   13120:                 strcpy(strb,strd);
                   13121:                 strcat(strb,"*");
                   13122:                 strcat(strb,stre);
                   13123:               }else{  /* strf=Vm  If strf=V6 then stre=V2 */
                   13124:                 strcpy(strb,strf);
                   13125:                 strcat(strb,"*");
                   13126:                 strcat(strb,stre);
                   13127:                 strcpy(strd,strb); /* in order for strd to not be "age"  for next test (will be Vn*Vm */
                   13128:               }
1.351     brouard  13129:              /* 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]]]); */
                   13130:              /* FixedV[Tvar[Tage[k]]]=0; /\* HERY not sure if V7*V4*age Fixed might not exist  yet*\/ */
1.349     brouard  13131:             }else{  /* strc=Vn*Vm (and strd=age) and should be strb=Vn*Vm but want to keep original strb double product  */
                   13132:              strcpy(stre,strb); /* save full b in stre */
                   13133:              strcpy(strb,strc); /* save short c in new short b for next block strb=Vn*Vm*/
                   13134:              strcpy(strf,strc); /* save short c in new short f */
                   13135:               cutl(strc,strd,strf,'*'); /* We get strd=Vn and strc=Vm for next block (strb=Vn*Vm)*/
                   13136:              /* strcpy(strc,stre);*/ /* save full e in c for future */
                   13137:             }
                   13138:             cptcovdageprod++; /* double product with age  Which product is it? */
                   13139:             /* 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 *\/ */
                   13140:             /* cutl(strc,strd,strb,'*'); /\* strd=  V6    or   V2     or    age and  strc=  V2 or    age or    V2 *\/ */
1.234     brouard  13141:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
1.349     brouard  13142:            n=atoi(stre);
1.234     brouard  13143:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.349     brouard  13144:            m=atoi(strc);
                   13145:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   13146:            Tage[cptcovage]=k; /* For age*V3*V2 gives the position in model of covariates associated with age Tage[1]=6 HERY too*/
                   13147:            if(existcomb[n][m] == 0){
                   13148:              /*  r /home/brouard/Documents/Recherches/REVES/Zachary/Zach-2022/Feinuo_Sun/Feinuo-threeway/femV12V15_3wayintNBe.imach */
                   13149:              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);
                   13150:              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);
                   13151:              fflush(ficlog);
                   13152:              k1++;  /* The combination Vn*Vm will be in the model so we create it at k1 */
                   13153:              k12++;
                   13154:              existcomb[n][m]=k1;
                   13155:              existcomb[m][n]=k1;
                   13156:              Tvar[k]=ncovcol+nqv+ntv+nqtv+k1;
                   13157:              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*/
                   13158:              Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 Gives the k1 double product  Vn*Vm or age*Vn*Vm at the k position */
                   13159:              Tvard[k1][1] =m; /* m 1 for V1*/
                   13160:              Tvardk[k][1] =m; /* m 1 for V1*/
                   13161:              Tvard[k1][2] =n; /* n 4 for V4*/
                   13162:              Tvardk[k][2] =n; /* n 4 for V4*/
1.351     brouard  13163: /*           Tvar[Tage[cptcovage]]=k1;*/ /* Tvar[6=age*V3*V2]=9 (new fixed covariate) */ /* We don't know about Fixed yet HERE */
1.349     brouard  13164:              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 */
                   13165:                for (i=1; i<=lastobs;i++){/* For fixed product */
                   13166:                  /* Computes the new covariate which is a product of
                   13167:                     covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   13168:                  covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   13169:                }
                   13170:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   13171:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   13172:                k12++;
                   13173:                FixedV[ncovcolt+k12]=0;
                   13174:              }else{ /*End of FixedV */
                   13175:                cptcovprodvage++; /* Counting the number of varying covariate with age */
                   13176:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   13177:                k12++;
                   13178:                FixedV[ncovcolt+k12]=1;
                   13179:              }
                   13180:            }else{  /* k1 Vn*Vm already exists */
                   13181:              k11=existcomb[n][m];
                   13182:              Tposprod[k]=k11; /* OK */
                   13183:              Tvar[k]=Tvar[Tprod[k11]]; /* HERY */
                   13184:              Tvardk[k][1]=m;
                   13185:              Tvardk[k][2]=n;
                   13186:              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 */
                   13187:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   13188:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   13189:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   13190:                Tvar[Tage[cptcovage]]=k1;
                   13191:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   13192:                k12++;
                   13193:                FixedV[ncovcolt+k12]=0;
                   13194:              }else{ /* Already exists but time varying (and age) */
                   13195:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   13196:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   13197:                /* Tvar[Tage[cptcovage]]=k1; */
                   13198:                cptcovprodvage++;
                   13199:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   13200:                k12++;
                   13201:                FixedV[ncovcolt+k12]=1;
                   13202:              }
                   13203:            }
                   13204:            /* Tage[cptcovage]=k;  /\*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   13205:            /* Tvar[k]=k11; /\* HERY *\/ */
                   13206:          } 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 */
                   13207:             cptcovprod++;
                   13208:             if (strcmp(strc,"age")==0) { /**< Model includes age: strb= Vn*age c=age d=Vn*/
                   13209:               /* covar is not filled and then is empty */
                   13210:               cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   13211:               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 */
                   13212:               Typevar[k]=1;  /* 1 for age product */
                   13213:               cptcovage++; /* Counts the number of covariates which include age as a product */
                   13214:               Tage[cptcovage]=k;  /*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   13215:              if( FixedV[Tvar[k]] == 0){
                   13216:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   13217:              }else{
                   13218:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
                   13219:              }
                   13220:               /*printf("stre=%s ", stre);*/
                   13221:             } else if (strcmp(strd,"age")==0) { /* strb= age*Vn c=Vn */
                   13222:               cutl(stre,strb,strc,'V');
                   13223:               Tvar[k]=atoi(stre);
                   13224:               Typevar[k]=1;  /* 1 for age product */
                   13225:               cptcovage++;
                   13226:               Tage[cptcovage]=k;
                   13227:              if( FixedV[Tvar[k]] == 0){
                   13228:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   13229:              }else{
                   13230:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
1.339     brouard  13231:              }
1.349     brouard  13232:             }else{ /*  for product Vn*Vm */
                   13233:              Typevar[k]=2;  /* 2 for product Vn*Vm */
                   13234:              cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   13235:              n=atoi(stre);
                   13236:              cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   13237:              m=atoi(strc);
                   13238:              k1++;
                   13239:              cptcovprodnoage++;
                   13240:              if(existcomb[n][m] != 0 || existcomb[m][n] != 0){
                   13241:                printf("Warning in model combination V%d*V%d already exists in the model in position k1=%d!\n",n,m,existcomb[n][m]);
                   13242:                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]);
                   13243:                fflush(ficlog);
                   13244:                k11=existcomb[n][m];
                   13245:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   13246:                Tposprod[k]=k11;
                   13247:                Tprod[k11]=k;
                   13248:                Tvardk[k][1] =m; /* m 1 for V1*/
                   13249:                /* Tvard[k11][1] =m; /\* n 4 for V4*\/ */
                   13250:                Tvardk[k][2] =n; /* n 4 for V4*/                
                   13251:                /* Tvard[k11][2] =n; /\* n 4 for V4*\/ */
                   13252:              }else{ /* combination Vn*Vm doesn't exist we create it (no age)*/
                   13253:                existcomb[n][m]=k1;
                   13254:                existcomb[m][n]=k1;
                   13255:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
                   13256:                                                    because this model-covariate is a construction we invent a new column
                   13257:                                                    which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   13258:                                                    If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
                   13259:                                                    thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
                   13260:                                                    Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
                   13261:                /* Please remark that the new variables are model dependent */
                   13262:                /* If we have 4 variable but the model uses only 3, like in
                   13263:                 * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   13264:                 *  k=     1     2      3   4     5        6        7       8
                   13265:                 * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   13266:                 * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   13267:                 * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   13268:                 */
                   13269:                /* We need to feed some variables like TvarVV, but later on next loop because of ncovv (k2) is not correct */
                   13270:                Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 +V6*V2*age  */
                   13271:                Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
                   13272:                Tvard[k1][1] =m; /* m 1 for V1*/
                   13273:                Tvardk[k][1] =m; /* m 1 for V1*/
                   13274:                Tvard[k1][2] =n; /* n 4 for V4*/
                   13275:                Tvardk[k][2] =n; /* n 4 for V4*/
                   13276:                k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   13277:                /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   13278:                /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
                   13279:                /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
                   13280:                /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   13281:                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 */
                   13282:                  for (i=1; i<=lastobs;i++){/* For fixed product */
                   13283:                    /* Computes the new covariate which is a product of
                   13284:                       covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   13285:                    covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   13286:                  }
                   13287:                  /* TvarVV[k2]=n; */
                   13288:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13289:                  /* TvarVV[k2+1]=m; */
                   13290:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13291:                }else{ /* not FixedV */
                   13292:                  /* TvarVV[k2]=n; */
                   13293:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13294:                  /* TvarVV[k2+1]=m; */
                   13295:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13296:                }                 
                   13297:              }  /* End of creation of Vn*Vm if not created by age*Vn*Vm earlier  */
                   13298:            } /*  End of product Vn*Vm */
                   13299:           } /* End of age*double product or simple product */
                   13300:        }else { /* not a product */
1.234     brouard  13301:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   13302:          /*  scanf("%d",i);*/
                   13303:          cutl(strd,strc,strb,'V');
                   13304:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   13305:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   13306:          Tvar[k]=atoi(strd);
                   13307:          Typevar[k]=0;  /* 0 for simple covariates */
                   13308:        }
                   13309:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  13310:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  13311:                                  scanf("%d",i);*/
1.187     brouard  13312:       } /* end of loop + on total covariates */
1.351     brouard  13313: 
                   13314:       
1.187     brouard  13315:     } /* end if strlen(modelsave == 0) age*age might exist */
                   13316:   } /* end if strlen(model == 0) */
1.349     brouard  13317:   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  */
                   13318: 
1.136     brouard  13319:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   13320:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  13321:   
1.136     brouard  13322:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  13323:      printf("cptcovprod=%d ", cptcovprod);
                   13324:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   13325:      scanf("%d ",i);*/
                   13326: 
                   13327: 
1.230     brouard  13328: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   13329:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  13330: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   13331:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   13332:    k =           1    2   3     4       5       6      7      8        9
                   13333:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  13334:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  13335:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   13336:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   13337:          Tmodelind[combination of covar]=k;
1.225     brouard  13338: */  
                   13339: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  13340:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  13341:   /* 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  13342:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  13343:   printf("Model=1+age+%s\n\
1.349     brouard  13344: 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  13345: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   13346: 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  13347:   fprintf(ficlog,"Model=1+age+%s\n\
1.349     brouard  13348: 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  13349: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   13350: 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  13351:   for(k=-1;k<=NCOVMAX; k++){ Fixed[k]=0; Dummy[k]=0;}
                   13352:   for(k=1;k<=NCOVMAX; k++){TvarFind[k]=0; TvarVind[k]=0;}
1.351     brouard  13353: 
                   13354: 
                   13355:   /* Second loop for calculating  Fixed[k], Dummy[k]*/
                   13356: 
                   13357:   
1.349     brouard  13358:   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  13359:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  13360:       Fixed[k]= 0;
                   13361:       Dummy[k]= 0;
1.225     brouard  13362:       ncoveff++;
1.232     brouard  13363:       ncovf++;
1.234     brouard  13364:       nsd++;
                   13365:       modell[k].maintype= FTYPE;
                   13366:       TvarsD[nsd]=Tvar[k];
                   13367:       TvarsDind[nsd]=k;
1.330     brouard  13368:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  13369:       TvarF[ncovf]=Tvar[k];
                   13370:       TvarFind[ncovf]=k;
                   13371:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   13372:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.339     brouard  13373:     /* }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  13374:     }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  13375:       Fixed[k]= 0;
                   13376:       Dummy[k]= 1;
1.230     brouard  13377:       nqfveff++;
1.234     brouard  13378:       modell[k].maintype= FTYPE;
                   13379:       modell[k].subtype= FQ;
                   13380:       nsq++;
1.334     brouard  13381:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   13382:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  13383:       ncovf++;
1.234     brouard  13384:       TvarF[ncovf]=Tvar[k];
                   13385:       TvarFind[ncovf]=k;
1.231     brouard  13386:       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  13387:       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  13388:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.339     brouard  13389:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   13390:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   13391:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   13392:       ncovvt++;
                   13393:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   13394:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
                   13395: 
1.227     brouard  13396:       Fixed[k]= 1;
                   13397:       Dummy[k]= 0;
1.225     brouard  13398:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  13399:       modell[k].maintype= VTYPE;
                   13400:       modell[k].subtype= VD;
                   13401:       nsd++;
                   13402:       TvarsD[nsd]=Tvar[k];
                   13403:       TvarsDind[nsd]=k;
1.330     brouard  13404:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  13405:       ncovv++; /* Only simple time varying variables */
                   13406:       TvarV[ncovv]=Tvar[k];
1.242     brouard  13407:       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  13408:       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 */
                   13409:       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  13410:       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);
                   13411:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  13412:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.339     brouard  13413:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   13414:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   13415:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   13416:       ncovvt++;
                   13417:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   13418:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   13419:       
1.234     brouard  13420:       Fixed[k]= 1;
                   13421:       Dummy[k]= 1;
                   13422:       nqtveff++;
                   13423:       modell[k].maintype= VTYPE;
                   13424:       modell[k].subtype= VQ;
                   13425:       ncovv++; /* Only simple time varying variables */
                   13426:       nsq++;
1.334     brouard  13427:       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) */
                   13428:       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  13429:       TvarV[ncovv]=Tvar[k];
1.242     brouard  13430:       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  13431:       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 */
                   13432:       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  13433:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   13434:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
1.349     brouard  13435:       /* 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  13436:       /* printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv); */
1.227     brouard  13437:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  13438:       ncova++;
                   13439:       TvarA[ncova]=Tvar[k];
                   13440:       TvarAind[ncova]=k;
1.349     brouard  13441:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   13442:       /** 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  13443:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  13444:        Fixed[k]= 2;
                   13445:        Dummy[k]= 2;
                   13446:        modell[k].maintype= ATYPE;
                   13447:        modell[k].subtype= APFD;
1.349     brouard  13448:        ncovta++;
                   13449:        TvarAVVA[ncovta]=Tvar[k]; /*  (2)age*V3 */
                   13450:        TvarAVVAind[ncovta]=k;
1.240     brouard  13451:        /* ncoveff++; */
1.227     brouard  13452:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  13453:        Fixed[k]= 2;
                   13454:        Dummy[k]= 3;
                   13455:        modell[k].maintype= ATYPE;
                   13456:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
1.349     brouard  13457:        ncovta++;
                   13458:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   13459:        TvarAVVAind[ncovta]=k;
1.240     brouard  13460:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  13461:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  13462:        Fixed[k]= 3;
                   13463:        Dummy[k]= 2;
                   13464:        modell[k].maintype= ATYPE;
                   13465:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
1.349     brouard  13466:        ncovva++;
                   13467:        TvarVVA[ncovva]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   13468:        TvarVVAind[ncovva]=k;
                   13469:        ncovta++;
                   13470:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   13471:        TvarAVVAind[ncovta]=k;
1.240     brouard  13472:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  13473:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  13474:        Fixed[k]= 3;
                   13475:        Dummy[k]= 3;
                   13476:        modell[k].maintype= ATYPE;
                   13477:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
1.349     brouard  13478:        ncovva++;
                   13479:        TvarVVA[ncovva]=Tvar[k]; /*   */
                   13480:        TvarVVAind[ncovva]=k;
                   13481:        ncovta++;
                   13482:        TvarAVVA[ncovta]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   13483:        TvarAVVAind[ncovta]=k;
1.240     brouard  13484:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  13485:       }
1.349     brouard  13486:     }else if( Tposprod[k]>0  &&  Typevar[k]==2){  /* Detects if fixed product no age Vm*Vn */
                   13487:       printf("MEMORY ERRORR k=%d  Tposprod[k]=%d, Typevar[k]=%d\n ",k, Tposprod[k], Typevar[k]);
                   13488:       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 */
                   13489:       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]]);
                   13490:        Fixed[k]= 0;
                   13491:        Dummy[k]= 0;
                   13492:        ncoveff++;
                   13493:        ncovf++;
                   13494:        /* ncovv++; */
                   13495:        /* TvarVV[ncovv]=Tvardk[k][1]; */
                   13496:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13497:        /* ncovv++; */
                   13498:        /* TvarVV[ncovv]=Tvardk[k][2]; */
                   13499:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13500:        modell[k].maintype= FTYPE;
                   13501:        TvarF[ncovf]=Tvar[k];
                   13502:        /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
                   13503:        TvarFind[ncovf]=k;
                   13504:        TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   13505:        TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   13506:       }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  */
                   13507:        /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   13508:        /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   13509:        /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   13510:        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 */
                   13511:        ncovvt++;
                   13512:        TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   13513:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   13514:        ncovvt++;
                   13515:        TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   13516:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   13517:        
                   13518:        /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   13519:        /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   13520:        
                   13521:        if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   13522:          if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
                   13523:            Fixed[k]= 1;
                   13524:            Dummy[k]= 0;
                   13525:            modell[k].maintype= FTYPE;
                   13526:            modell[k].subtype= FPDD;            /*      Product fixed dummy * fixed dummy */
                   13527:            ncovf++; /* Fixed variables without age */
                   13528:            TvarF[ncovf]=Tvar[k];
                   13529:            TvarFind[ncovf]=k;
                   13530:          }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
                   13531:            Fixed[k]= 0;  /* Fixed product */
                   13532:            Dummy[k]= 1;
                   13533:            modell[k].maintype= FTYPE;
                   13534:            modell[k].subtype= FPDQ;            /*      Product fixed dummy * fixed quantitative */
                   13535:            ncovf++; /* Varying variables without age */
                   13536:            TvarF[ncovf]=Tvar[k];
                   13537:            TvarFind[ncovf]=k;
                   13538:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
                   13539:            Fixed[k]= 1;
                   13540:            Dummy[k]= 0;
                   13541:            modell[k].maintype= VTYPE;
                   13542:            modell[k].subtype= VPDD;            /*      Product fixed dummy * varying dummy */
                   13543:            ncovv++; /* Varying variables without age */
                   13544:            TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   13545:            TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
                   13546:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
                   13547:            Fixed[k]= 1;
                   13548:            Dummy[k]= 1;
                   13549:            modell[k].maintype= VTYPE;
                   13550:            modell[k].subtype= VPDQ;            /*      Product fixed dummy * varying quantitative */
                   13551:            ncovv++; /* Varying variables without age */
                   13552:            TvarV[ncovv]=Tvar[k];
                   13553:            TvarVind[ncovv]=k;
                   13554:          }
                   13555:        }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   13556:          if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
                   13557:            Fixed[k]= 0;  /*  Fixed product */
                   13558:            Dummy[k]= 1;
                   13559:            modell[k].maintype= FTYPE;
                   13560:            modell[k].subtype= FPDQ;            /*      Product fixed quantitative * fixed dummy */
                   13561:            ncovf++; /* Fixed variables without age */
                   13562:            TvarF[ncovf]=Tvar[k];
                   13563:            TvarFind[ncovf]=k;
                   13564:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
                   13565:            Fixed[k]= 1;
                   13566:            Dummy[k]= 1;
                   13567:            modell[k].maintype= VTYPE;
                   13568:            modell[k].subtype= VPDQ;            /*      Product fixed quantitative * varying dummy */
                   13569:            ncovv++; /* Varying variables without age */
                   13570:            TvarV[ncovv]=Tvar[k];
                   13571:            TvarVind[ncovv]=k;
                   13572:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
                   13573:            Fixed[k]= 1;
                   13574:            Dummy[k]= 1;
                   13575:            modell[k].maintype= VTYPE;
                   13576:            modell[k].subtype= VPQQ;            /*      Product fixed quantitative * varying quantitative */
                   13577:            ncovv++; /* Varying variables without age */
                   13578:            TvarV[ncovv]=Tvar[k];
                   13579:            TvarVind[ncovv]=k;
                   13580:            ncovv++; /* Varying variables without age */
                   13581:            TvarV[ncovv]=Tvar[k];
                   13582:            TvarVind[ncovv]=k;
                   13583:          }
                   13584:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
                   13585:          if(Tvard[k1][2] <=ncovcol){
                   13586:            Fixed[k]= 1;
                   13587:            Dummy[k]= 1;
                   13588:            modell[k].maintype= VTYPE;
                   13589:            modell[k].subtype= VPDD;            /*      Product time varying dummy * fixed dummy */
                   13590:            ncovv++; /* Varying variables without age */
                   13591:            TvarV[ncovv]=Tvar[k];
                   13592:            TvarVind[ncovv]=k;
                   13593:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   13594:            Fixed[k]= 1;
                   13595:            Dummy[k]= 1;
                   13596:            modell[k].maintype= VTYPE;
                   13597:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * fixed quantitative */
                   13598:            ncovv++; /* Varying variables without age */
                   13599:            TvarV[ncovv]=Tvar[k];
                   13600:            TvarVind[ncovv]=k;
                   13601:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   13602:            Fixed[k]= 1;
                   13603:            Dummy[k]= 0;
                   13604:            modell[k].maintype= VTYPE;
                   13605:            modell[k].subtype= VPDD;            /*      Product time varying dummy * time varying dummy */
                   13606:            ncovv++; /* Varying variables without age */
                   13607:            TvarV[ncovv]=Tvar[k];
                   13608:            TvarVind[ncovv]=k;
                   13609:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   13610:            Fixed[k]= 1;
                   13611:            Dummy[k]= 1;
                   13612:            modell[k].maintype= VTYPE;
                   13613:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * time varying quantitative */
                   13614:            ncovv++; /* Varying variables without age */
                   13615:            TvarV[ncovv]=Tvar[k];
                   13616:            TvarVind[ncovv]=k;
                   13617:          }
                   13618:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
                   13619:          if(Tvard[k1][2] <=ncovcol){
                   13620:            Fixed[k]= 1;
                   13621:            Dummy[k]= 1;
                   13622:            modell[k].maintype= VTYPE;
                   13623:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * fixed dummy */
                   13624:            ncovv++; /* Varying variables without age */
                   13625:            TvarV[ncovv]=Tvar[k];
                   13626:            TvarVind[ncovv]=k;
                   13627:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   13628:            Fixed[k]= 1;
                   13629:            Dummy[k]= 1;
                   13630:            modell[k].maintype= VTYPE;
                   13631:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * fixed quantitative */
                   13632:            ncovv++; /* Varying variables without age */
                   13633:            TvarV[ncovv]=Tvar[k];
                   13634:            TvarVind[ncovv]=k;
                   13635:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   13636:            Fixed[k]= 1;
                   13637:            Dummy[k]= 1;
                   13638:            modell[k].maintype= VTYPE;
                   13639:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * time varying dummy */
                   13640:            ncovv++; /* Varying variables without age */
                   13641:            TvarV[ncovv]=Tvar[k];
                   13642:            TvarVind[ncovv]=k;
                   13643:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   13644:            Fixed[k]= 1;
                   13645:            Dummy[k]= 1;
                   13646:            modell[k].maintype= VTYPE;
                   13647:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * time varying quantitative */
                   13648:            ncovv++; /* Varying variables without age */
                   13649:            TvarV[ncovv]=Tvar[k];
                   13650:            TvarVind[ncovv]=k;
                   13651:          }
                   13652:        }else{
                   13653:          printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   13654:          fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   13655:        } /*end k1*/
                   13656:       }
                   13657:     }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  13658:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  13659:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   13660:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   13661:       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 */
                   13662:       ncova++;
                   13663:       TvarA[ncova]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   13664:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   13665:       ncova++;
                   13666:       TvarA[ncova]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   13667:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
1.339     brouard  13668: 
1.349     brouard  13669:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   13670:       /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   13671:       if( FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){
                   13672:        ncovta++;
                   13673:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   13674:        TvarAVVAind[ncovta]=k;
                   13675:        ncovta++;
                   13676:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   13677:        TvarAVVAind[ncovta]=k;
                   13678:       }else{
                   13679:        ncovva++;  /* HERY  reached */
                   13680:        TvarVVA[ncovva]=Tvard[k1][1]; /*  age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4  */
                   13681:        TvarVVAind[ncovva]=k;
                   13682:        ncovva++;
                   13683:        TvarVVA[ncovva]=Tvard[k1][2]; /*   */
                   13684:        TvarVVAind[ncovva]=k;
                   13685:        ncovta++;
                   13686:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   13687:        TvarAVVAind[ncovta]=k;
                   13688:        ncovta++;
                   13689:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   13690:        TvarAVVAind[ncovta]=k;
                   13691:       }
1.339     brouard  13692:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   13693:        if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
1.349     brouard  13694:          Fixed[k]= 2;
                   13695:          Dummy[k]= 2;
1.240     brouard  13696:          modell[k].maintype= FTYPE;
                   13697:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
1.349     brouard  13698:          /* TvarF[ncova]=Tvar[k];   /\* Problem to solve *\/ */
                   13699:          /* TvarFind[ncova]=k; */
1.339     brouard  13700:        }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
1.349     brouard  13701:          Fixed[k]= 2;  /* Fixed product */
                   13702:          Dummy[k]= 3;
1.240     brouard  13703:          modell[k].maintype= FTYPE;
                   13704:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
1.349     brouard  13705:          /* TvarF[ncova]=Tvar[k]; */
                   13706:          /* TvarFind[ncova]=k; */
1.339     brouard  13707:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
1.349     brouard  13708:          Fixed[k]= 3;
                   13709:          Dummy[k]= 2;
1.240     brouard  13710:          modell[k].maintype= VTYPE;
                   13711:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
1.349     brouard  13712:          TvarV[ncova]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   13713:          TvarVind[ncova]=k;/* TvarVind[1]=5 */ 
1.339     brouard  13714:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
1.349     brouard  13715:          Fixed[k]= 3;
                   13716:          Dummy[k]= 3;
1.240     brouard  13717:          modell[k].maintype= VTYPE;
                   13718:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
1.349     brouard  13719:          /* ncovv++; /\* Varying variables without age *\/ */
                   13720:          /* TvarV[ncovv]=Tvar[k]; */
                   13721:          /* TvarVind[ncovv]=k; */
1.240     brouard  13722:        }
1.339     brouard  13723:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   13724:        if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
1.349     brouard  13725:          Fixed[k]= 2;  /*  Fixed product */
                   13726:          Dummy[k]= 2;
1.240     brouard  13727:          modell[k].maintype= FTYPE;
                   13728:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
1.349     brouard  13729:          /* ncova++; /\* Fixed variables with age *\/ */
                   13730:          /* TvarF[ncovf]=Tvar[k]; */
                   13731:          /* TvarFind[ncovf]=k; */
1.339     brouard  13732:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
1.349     brouard  13733:          Fixed[k]= 2;
                   13734:          Dummy[k]= 3;
1.240     brouard  13735:          modell[k].maintype= VTYPE;
                   13736:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
1.349     brouard  13737:          /* ncova++; /\* Varying variables with age *\/ */
                   13738:          /* TvarV[ncova]=Tvar[k]; */
                   13739:          /* TvarVind[ncova]=k; */
1.339     brouard  13740:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
1.349     brouard  13741:          Fixed[k]= 3;
                   13742:          Dummy[k]= 2;
1.240     brouard  13743:          modell[k].maintype= VTYPE;
                   13744:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
1.349     brouard  13745:          ncova++; /* Varying variables without age */
                   13746:          TvarV[ncova]=Tvar[k];
                   13747:          TvarVind[ncova]=k;
                   13748:          /* ncova++; /\* Varying variables without age *\/ */
                   13749:          /* TvarV[ncova]=Tvar[k]; */
                   13750:          /* TvarVind[ncova]=k; */
1.240     brouard  13751:        }
1.339     brouard  13752:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
1.240     brouard  13753:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  13754:          Fixed[k]= 2;
                   13755:          Dummy[k]= 2;
1.240     brouard  13756:          modell[k].maintype= VTYPE;
                   13757:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
1.349     brouard  13758:          /* ncova++; /\* Varying variables with age *\/ */
                   13759:          /* TvarV[ncova]=Tvar[k]; */
                   13760:          /* TvarVind[ncova]=k; */
1.240     brouard  13761:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  13762:          Fixed[k]= 2;
                   13763:          Dummy[k]= 3;
1.240     brouard  13764:          modell[k].maintype= VTYPE;
                   13765:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
1.349     brouard  13766:          /* ncova++; /\* Varying variables with age *\/ */
                   13767:          /* TvarV[ncova]=Tvar[k]; */
                   13768:          /* TvarVind[ncova]=k; */
1.240     brouard  13769:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349     brouard  13770:          Fixed[k]= 3;
                   13771:          Dummy[k]= 2;
1.240     brouard  13772:          modell[k].maintype= VTYPE;
                   13773:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
1.349     brouard  13774:          /* ncova++; /\* Varying variables with age *\/ */
                   13775:          /* TvarV[ncova]=Tvar[k]; */
                   13776:          /* TvarVind[ncova]=k; */
1.240     brouard  13777:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  13778:          Fixed[k]= 3;
                   13779:          Dummy[k]= 3;
1.240     brouard  13780:          modell[k].maintype= VTYPE;
                   13781:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
1.349     brouard  13782:          /* ncova++; /\* Varying variables with age *\/ */
                   13783:          /* TvarV[ncova]=Tvar[k]; */
                   13784:          /* TvarVind[ncova]=k; */
1.240     brouard  13785:        }
1.339     brouard  13786:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
1.240     brouard  13787:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  13788:          Fixed[k]= 2;
                   13789:          Dummy[k]= 2;
1.240     brouard  13790:          modell[k].maintype= VTYPE;
                   13791:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
1.349     brouard  13792:          /* ncova++; /\* Varying variables with age *\/ */
                   13793:          /* TvarV[ncova]=Tvar[k]; */
                   13794:          /* TvarVind[ncova]=k; */
1.240     brouard  13795:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  13796:          Fixed[k]= 2;
                   13797:          Dummy[k]= 3;
1.240     brouard  13798:          modell[k].maintype= VTYPE;
                   13799:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
1.349     brouard  13800:          /* ncova++; /\* Varying variables with age *\/ */
                   13801:          /* TvarV[ncova]=Tvar[k]; */
                   13802:          /* TvarVind[ncova]=k; */
1.240     brouard  13803:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349     brouard  13804:          Fixed[k]= 3;
                   13805:          Dummy[k]= 2;
1.240     brouard  13806:          modell[k].maintype= VTYPE;
                   13807:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
1.349     brouard  13808:          /* ncova++; /\* Varying variables with age *\/ */
                   13809:          /* TvarV[ncova]=Tvar[k]; */
                   13810:          /* TvarVind[ncova]=k; */
1.240     brouard  13811:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  13812:          Fixed[k]= 3;
                   13813:          Dummy[k]= 3;
1.240     brouard  13814:          modell[k].maintype= VTYPE;
                   13815:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
1.349     brouard  13816:          /* ncova++; /\* Varying variables with age *\/ */
                   13817:          /* TvarV[ncova]=Tvar[k]; */
                   13818:          /* TvarVind[ncova]=k; */
1.240     brouard  13819:        }
1.227     brouard  13820:       }else{
1.240     brouard  13821:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   13822:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   13823:       } /*end k1*/
1.349     brouard  13824:     } else{
1.226     brouard  13825:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   13826:       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  13827:     }
1.342     brouard  13828:     /* 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]); */
                   13829:     /* printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype); */
1.227     brouard  13830:     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]);
                   13831:   }
1.349     brouard  13832:   ncovvta=ncovva;
1.227     brouard  13833:   /* Searching for doublons in the model */
                   13834:   for(k1=1; k1<= cptcovt;k1++){
                   13835:     for(k2=1; k2 <k1;k2++){
1.285     brouard  13836:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   13837:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  13838:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   13839:          if(Tvar[k1]==Tvar[k2]){
1.338     brouard  13840:            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]);
                   13841:            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  13842:            return(1);
                   13843:          }
                   13844:        }else if (Typevar[k1] ==2){
                   13845:          k3=Tposprod[k1];
                   13846:          k4=Tposprod[k2];
                   13847:          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  13848:            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]]);
                   13849:            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  13850:            return(1);
                   13851:          }
                   13852:        }
1.227     brouard  13853:       }
                   13854:     }
1.225     brouard  13855:   }
                   13856:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   13857:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  13858:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   13859:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.349     brouard  13860: 
                   13861:   free_imatrix(existcomb,1,NCOVMAX,1,NCOVMAX);
1.137     brouard  13862:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  13863:   /*endread:*/
1.225     brouard  13864:   printf("Exiting decodemodel: ");
                   13865:   return (1);
1.136     brouard  13866: }
                   13867: 
1.169     brouard  13868: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  13869: {/* Check ages at death */
1.136     brouard  13870:   int i, m;
1.218     brouard  13871:   int firstone=0;
                   13872:   
1.136     brouard  13873:   for (i=1; i<=imx; i++) {
                   13874:     for(m=2; (m<= maxwav); m++) {
                   13875:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   13876:        anint[m][i]=9999;
1.216     brouard  13877:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   13878:          s[m][i]=-1;
1.136     brouard  13879:       }
                   13880:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  13881:        *nberr = *nberr + 1;
1.218     brouard  13882:        if(firstone == 0){
                   13883:          firstone=1;
1.260     brouard  13884:        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  13885:        }
1.262     brouard  13886:        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  13887:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  13888:       }
                   13889:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  13890:        (*nberr)++;
1.259     brouard  13891:        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  13892:        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  13893:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  13894:       }
                   13895:     }
                   13896:   }
                   13897: 
                   13898:   for (i=1; i<=imx; i++)  {
                   13899:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   13900:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  13901:       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  13902:        if (s[m][i] >= nlstate+1) {
1.169     brouard  13903:          if(agedc[i]>0){
                   13904:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  13905:              agev[m][i]=agedc[i];
1.214     brouard  13906:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  13907:            }else {
1.136     brouard  13908:              if ((int)andc[i]!=9999){
                   13909:                nbwarn++;
                   13910:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   13911:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   13912:                agev[m][i]=-1;
                   13913:              }
                   13914:            }
1.169     brouard  13915:          } /* agedc > 0 */
1.214     brouard  13916:        } /* end if */
1.136     brouard  13917:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   13918:                                 years but with the precision of a month */
                   13919:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   13920:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   13921:            agev[m][i]=1;
                   13922:          else if(agev[m][i] < *agemin){ 
                   13923:            *agemin=agev[m][i];
                   13924:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   13925:          }
                   13926:          else if(agev[m][i] >*agemax){
                   13927:            *agemax=agev[m][i];
1.156     brouard  13928:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  13929:          }
                   13930:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   13931:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  13932:        } /* en if 9*/
1.136     brouard  13933:        else { /* =9 */
1.214     brouard  13934:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  13935:          agev[m][i]=1;
                   13936:          s[m][i]=-1;
                   13937:        }
                   13938:       }
1.214     brouard  13939:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  13940:        agev[m][i]=1;
1.214     brouard  13941:       else{
                   13942:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   13943:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   13944:        agev[m][i]=0;
                   13945:       }
                   13946:     } /* End for lastpass */
                   13947:   }
1.136     brouard  13948:     
                   13949:   for (i=1; i<=imx; i++)  {
                   13950:     for(m=firstpass; (m<=lastpass); m++){
                   13951:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  13952:        (*nberr)++;
1.136     brouard  13953:        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);     
                   13954:        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);     
                   13955:        return 1;
                   13956:       }
                   13957:     }
                   13958:   }
                   13959: 
                   13960:   /*for (i=1; i<=imx; i++){
                   13961:   for (m=firstpass; (m<lastpass); m++){
                   13962:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   13963: }
                   13964: 
                   13965: }*/
                   13966: 
                   13967: 
1.139     brouard  13968:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   13969:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  13970: 
                   13971:   return (0);
1.164     brouard  13972:  /* endread:*/
1.136     brouard  13973:     printf("Exiting calandcheckages: ");
                   13974:     return (1);
                   13975: }
                   13976: 
1.172     brouard  13977: #if defined(_MSC_VER)
                   13978: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   13979: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   13980: //#include "stdafx.h"
                   13981: //#include <stdio.h>
                   13982: //#include <tchar.h>
                   13983: //#include <windows.h>
                   13984: //#include <iostream>
                   13985: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   13986: 
                   13987: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   13988: 
                   13989: BOOL IsWow64()
                   13990: {
                   13991:        BOOL bIsWow64 = FALSE;
                   13992: 
                   13993:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   13994:        //  (HANDLE, PBOOL);
                   13995: 
                   13996:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   13997: 
                   13998:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   13999:        const char funcName[] = "IsWow64Process";
                   14000:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   14001:                GetProcAddress(module, funcName);
                   14002: 
                   14003:        if (NULL != fnIsWow64Process)
                   14004:        {
                   14005:                if (!fnIsWow64Process(GetCurrentProcess(),
                   14006:                        &bIsWow64))
                   14007:                        //throw std::exception("Unknown error");
                   14008:                        printf("Unknown error\n");
                   14009:        }
                   14010:        return bIsWow64 != FALSE;
                   14011: }
                   14012: #endif
1.177     brouard  14013: 
1.191     brouard  14014: void syscompilerinfo(int logged)
1.292     brouard  14015: {
                   14016: #include <stdint.h>
                   14017: 
                   14018:   /* #include "syscompilerinfo.h"*/
1.185     brouard  14019:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   14020:    /* /GS /W3 /Gy
                   14021:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   14022:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   14023:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  14024:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   14025:    */ 
                   14026:    /* 64 bits */
1.185     brouard  14027:    /*
                   14028:      /GS /W3 /Gy
                   14029:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   14030:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   14031:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   14032:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   14033:    /* Optimization are useless and O3 is slower than O2 */
                   14034:    /*
                   14035:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   14036:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   14037:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   14038:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   14039:    */
1.186     brouard  14040:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  14041:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   14042:       /PDB:"visual studio
                   14043:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   14044:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   14045:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   14046:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   14047:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   14048:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   14049:       uiAccess='false'"
                   14050:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   14051:       /NOLOGO /TLBID:1
                   14052:    */
1.292     brouard  14053: 
                   14054: 
1.177     brouard  14055: #if defined __INTEL_COMPILER
1.178     brouard  14056: #if defined(__GNUC__)
                   14057:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   14058: #endif
1.177     brouard  14059: #elif defined(__GNUC__) 
1.179     brouard  14060: #ifndef  __APPLE__
1.174     brouard  14061: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  14062: #endif
1.177     brouard  14063:    struct utsname sysInfo;
1.178     brouard  14064:    int cross = CROSS;
                   14065:    if (cross){
                   14066:           printf("Cross-");
1.191     brouard  14067:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  14068:    }
1.174     brouard  14069: #endif
                   14070: 
1.191     brouard  14071:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  14072: #if defined(__clang__)
1.191     brouard  14073:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  14074: #endif
                   14075: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  14076:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  14077: #endif
                   14078: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  14079:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  14080: #endif
                   14081: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  14082:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  14083: #endif
                   14084: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  14085:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  14086: #endif
                   14087: #if defined(_MSC_VER)
1.191     brouard  14088:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  14089: #endif
                   14090: #if defined(__PGI)
1.191     brouard  14091:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  14092: #endif
                   14093: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  14094:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  14095: #endif
1.191     brouard  14096:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  14097:    
1.167     brouard  14098: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   14099: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   14100:     // Windows (x64 and x86)
1.191     brouard  14101:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  14102: #elif __unix__ // all unices, not all compilers
                   14103:     // Unix
1.191     brouard  14104:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  14105: #elif __linux__
                   14106:     // linux
1.191     brouard  14107:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  14108: #elif __APPLE__
1.174     brouard  14109:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  14110:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  14111: #endif
                   14112: 
                   14113: /*  __MINGW32__          */
                   14114: /*  __CYGWIN__  */
                   14115: /* __MINGW64__  */
                   14116: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   14117: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   14118: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   14119: /* _WIN64  // Defined for applications for Win64. */
                   14120: /* _M_X64 // Defined for compilations that target x64 processors. */
                   14121: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  14122: 
1.167     brouard  14123: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  14124:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  14125: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  14126:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  14127: #else
1.191     brouard  14128:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  14129: #endif
                   14130: 
1.169     brouard  14131: #if defined(__GNUC__)
                   14132: # if defined(__GNUC_PATCHLEVEL__)
                   14133: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   14134:                             + __GNUC_MINOR__ * 100 \
                   14135:                             + __GNUC_PATCHLEVEL__)
                   14136: # else
                   14137: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   14138:                             + __GNUC_MINOR__ * 100)
                   14139: # endif
1.174     brouard  14140:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  14141:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  14142: 
                   14143:    if (uname(&sysInfo) != -1) {
                   14144:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  14145:         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  14146:    }
                   14147:    else
                   14148:       perror("uname() error");
1.179     brouard  14149:    //#ifndef __INTEL_COMPILER 
                   14150: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  14151:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  14152:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  14153: #endif
1.169     brouard  14154: #endif
1.172     brouard  14155: 
1.286     brouard  14156:    //   void main ()
1.172     brouard  14157:    //   {
1.169     brouard  14158: #if defined(_MSC_VER)
1.174     brouard  14159:    if (IsWow64()){
1.191     brouard  14160:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   14161:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  14162:    }
                   14163:    else{
1.191     brouard  14164:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   14165:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  14166:    }
1.172     brouard  14167:    //     printf("\nPress Enter to continue...");
                   14168:    //     getchar();
                   14169:    //   }
                   14170: 
1.169     brouard  14171: #endif
                   14172:    
1.167     brouard  14173: 
1.219     brouard  14174: }
1.136     brouard  14175: 
1.219     brouard  14176: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  14177:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  14178:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  14179:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  14180:   /* double ftolpl = 1.e-10; */
1.180     brouard  14181:   double age, agebase, agelim;
1.203     brouard  14182:   double tot;
1.180     brouard  14183: 
1.202     brouard  14184:   strcpy(filerespl,"PL_");
                   14185:   strcat(filerespl,fileresu);
                   14186:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  14187:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   14188:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  14189:   }
1.288     brouard  14190:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   14191:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  14192:   pstamp(ficrespl);
1.288     brouard  14193:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  14194:   fprintf(ficrespl,"#Age ");
                   14195:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   14196:   fprintf(ficrespl,"\n");
1.180     brouard  14197:   
1.219     brouard  14198:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  14199: 
1.219     brouard  14200:   agebase=ageminpar;
                   14201:   agelim=agemaxpar;
1.180     brouard  14202: 
1.227     brouard  14203:   /* i1=pow(2,ncoveff); */
1.234     brouard  14204:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  14205:   if (cptcovn < 1){i1=1;}
1.180     brouard  14206: 
1.337     brouard  14207:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
1.238     brouard  14208:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  14209:       k=TKresult[nres];
1.338     brouard  14210:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  14211:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
                   14212:       /*       continue; */
1.235     brouard  14213: 
1.238     brouard  14214:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   14215:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   14216:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   14217:       /* k=k+1; */
                   14218:       /* to clean */
1.332     brouard  14219:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  14220:       fprintf(ficrespl,"#******");
                   14221:       printf("#******");
                   14222:       fprintf(ficlog,"#******");
1.337     brouard  14223:       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  14224:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
1.337     brouard  14225:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14226:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14227:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14228:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14229:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14230:       }
                   14231:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   14232:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14233:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14234:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14235:       /* } */
1.238     brouard  14236:       fprintf(ficrespl,"******\n");
                   14237:       printf("******\n");
                   14238:       fprintf(ficlog,"******\n");
                   14239:       if(invalidvarcomb[k]){
                   14240:        printf("\nCombination (%d) ignored because no case \n",k); 
                   14241:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   14242:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   14243:        continue;
                   14244:       }
1.219     brouard  14245: 
1.238     brouard  14246:       fprintf(ficrespl,"#Age ");
1.337     brouard  14247:       /* for(j=1;j<=cptcoveff;j++) { */
                   14248:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14249:       /* } */
                   14250:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
                   14251:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14252:       }
                   14253:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   14254:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  14255:     
1.238     brouard  14256:       for (age=agebase; age<=agelim; age++){
                   14257:        /* for (age=agebase; age<=agebase; age++){ */
1.337     brouard  14258:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
                   14259:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
1.238     brouard  14260:        fprintf(ficrespl,"%.0f ",age );
1.337     brouard  14261:        /* for(j=1;j<=cptcoveff;j++) */
                   14262:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14263:        for(j=1;j<=cptcovs;j++)
                   14264:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14265:        tot=0.;
                   14266:        for(i=1; i<=nlstate;i++){
                   14267:          tot +=  prlim[i][i];
                   14268:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   14269:        }
                   14270:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   14271:       } /* Age */
                   14272:       /* was end of cptcod */
1.337     brouard  14273:     } /* nres */
                   14274:   /* } /\* for each combination *\/ */
1.219     brouard  14275:   return 0;
1.180     brouard  14276: }
                   14277: 
1.218     brouard  14278: 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  14279:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  14280:        
                   14281:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   14282:    * at any age between ageminpar and agemaxpar
                   14283:         */
1.235     brouard  14284:   int i, j, k, i1, nres=0 ;
1.217     brouard  14285:   /* double ftolpl = 1.e-10; */
                   14286:   double age, agebase, agelim;
                   14287:   double tot;
1.218     brouard  14288:   /* double ***mobaverage; */
                   14289:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  14290: 
                   14291:   strcpy(fileresplb,"PLB_");
                   14292:   strcat(fileresplb,fileresu);
                   14293:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  14294:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   14295:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  14296:   }
1.288     brouard  14297:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   14298:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  14299:   pstamp(ficresplb);
1.288     brouard  14300:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  14301:   fprintf(ficresplb,"#Age ");
                   14302:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   14303:   fprintf(ficresplb,"\n");
                   14304:   
1.218     brouard  14305:   
                   14306:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   14307:   
                   14308:   agebase=ageminpar;
                   14309:   agelim=agemaxpar;
                   14310:   
                   14311:   
1.227     brouard  14312:   i1=pow(2,cptcoveff);
1.218     brouard  14313:   if (cptcovn < 1){i1=1;}
1.227     brouard  14314:   
1.238     brouard  14315:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.338     brouard  14316:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   14317:       k=TKresult[nres];
                   14318:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   14319:      /* if(i1 != 1 && TKresult[nres]!= k) */
                   14320:      /*        continue; */
                   14321:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
1.238     brouard  14322:       fprintf(ficresplb,"#******");
                   14323:       printf("#******");
                   14324:       fprintf(ficlog,"#******");
1.338     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) */
                   14326:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14327:        fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14328:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14329:       }
1.338     brouard  14330:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
                   14331:       /*       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14332:       /*       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14333:       /*       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14334:       /* } */
                   14335:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   14336:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14337:       /*       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14338:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14339:       /* } */
1.238     brouard  14340:       fprintf(ficresplb,"******\n");
                   14341:       printf("******\n");
                   14342:       fprintf(ficlog,"******\n");
                   14343:       if(invalidvarcomb[k]){
                   14344:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   14345:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   14346:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   14347:        continue;
                   14348:       }
1.218     brouard  14349:     
1.238     brouard  14350:       fprintf(ficresplb,"#Age ");
1.338     brouard  14351:       for(j=1;j<=cptcovs;j++) {
                   14352:        fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14353:       }
                   14354:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   14355:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  14356:     
                   14357:     
1.238     brouard  14358:       for (age=agebase; age<=agelim; age++){
                   14359:        /* for (age=agebase; age<=agebase; age++){ */
                   14360:        if(mobilavproj > 0){
                   14361:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   14362:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  14363:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  14364:        }else if (mobilavproj == 0){
                   14365:          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);
                   14366:          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);
                   14367:          exit(1);
                   14368:        }else{
                   14369:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  14370:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  14371:          /* printf("TOTOT\n"); */
                   14372:           /* exit(1); */
1.238     brouard  14373:        }
                   14374:        fprintf(ficresplb,"%.0f ",age );
1.338     brouard  14375:        for(j=1;j<=cptcovs;j++)
                   14376:          fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14377:        tot=0.;
                   14378:        for(i=1; i<=nlstate;i++){
                   14379:          tot +=  bprlim[i][i];
                   14380:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   14381:        }
                   14382:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   14383:       } /* Age */
                   14384:       /* was end of cptcod */
1.255     brouard  14385:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.338     brouard  14386:     /* } /\* end of any combination *\/ */
1.238     brouard  14387:   } /* end of nres */  
1.218     brouard  14388:   /* hBijx(p, bage, fage); */
                   14389:   /* fclose(ficrespijb); */
                   14390:   
                   14391:   return 0;
1.217     brouard  14392: }
1.218     brouard  14393:  
1.180     brouard  14394: int hPijx(double *p, int bage, int fage){
                   14395:     /*------------- h Pij x at various ages ------------*/
1.336     brouard  14396:   /* to be optimized with precov */
1.180     brouard  14397:   int stepsize;
                   14398:   int agelim;
                   14399:   int hstepm;
                   14400:   int nhstepm;
1.359     brouard  14401:   int h, i, i1, j, k, nres=0;
1.180     brouard  14402: 
                   14403:   double agedeb;
                   14404:   double ***p3mat;
                   14405: 
1.337     brouard  14406:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   14407:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   14408:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   14409:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   14410:   }
                   14411:   printf("Computing pij: result on file '%s' \n", filerespij);
                   14412:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   14413:   
                   14414:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   14415:   /*if (stepm<=24) stepsize=2;*/
                   14416:   
                   14417:   agelim=AGESUP;
                   14418:   hstepm=stepsize*YEARM; /* Every year of age */
                   14419:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   14420:   
                   14421:   /* hstepm=1;   aff par mois*/
                   14422:   pstamp(ficrespij);
                   14423:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   14424:   i1= pow(2,cptcoveff);
                   14425:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   14426:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   14427:   /*   k=k+1;  */
                   14428:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   14429:     k=TKresult[nres];
1.338     brouard  14430:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  14431:     /* for(k=1; k<=i1;k++){ */
                   14432:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   14433:     /*         continue; */
                   14434:     fprintf(ficrespij,"\n#****** ");
                   14435:     for(j=1;j<=cptcovs;j++){
                   14436:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14437:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14438:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   14439:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14440:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14441:     }
                   14442:     fprintf(ficrespij,"******\n");
                   14443:     
                   14444:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   14445:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   14446:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   14447:       
                   14448:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   14449:       
                   14450:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   14451:       oldm=oldms;savm=savms;
                   14452:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
                   14453:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   14454:       for(i=1; i<=nlstate;i++)
                   14455:        for(j=1; j<=nlstate+ndeath;j++)
                   14456:          fprintf(ficrespij," %1d-%1d",i,j);
                   14457:       fprintf(ficrespij,"\n");
                   14458:       for (h=0; h<=nhstepm; h++){
                   14459:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   14460:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.183     brouard  14461:        for(i=1; i<=nlstate;i++)
                   14462:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  14463:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.183     brouard  14464:        fprintf(ficrespij,"\n");
                   14465:       }
1.337     brouard  14466:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   14467:       fprintf(ficrespij,"\n");
1.180     brouard  14468:     }
1.337     brouard  14469:   }
                   14470:   /*}*/
                   14471:   return 0;
1.180     brouard  14472: }
1.218     brouard  14473:  
                   14474:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  14475:     /*------------- h Bij x at various ages ------------*/
1.336     brouard  14476:     /* To be optimized with precov */
1.217     brouard  14477:   int stepsize;
1.218     brouard  14478:   /* int agelim; */
                   14479:        int ageminl;
1.217     brouard  14480:   int hstepm;
                   14481:   int nhstepm;
1.238     brouard  14482:   int h, i, i1, j, k, nres;
1.218     brouard  14483:        
1.217     brouard  14484:   double agedeb;
                   14485:   double ***p3mat;
1.218     brouard  14486:        
                   14487:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   14488:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   14489:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   14490:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   14491:   }
                   14492:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   14493:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   14494:   
                   14495:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   14496:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  14497:   
1.218     brouard  14498:   /* agelim=AGESUP; */
1.289     brouard  14499:   ageminl=AGEINF; /* was 30 */
1.218     brouard  14500:   hstepm=stepsize*YEARM; /* Every year of age */
                   14501:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   14502:   
                   14503:   /* hstepm=1;   aff par mois*/
                   14504:   pstamp(ficrespijb);
1.255     brouard  14505:   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  14506:   i1= pow(2,cptcoveff);
1.218     brouard  14507:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   14508:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   14509:   /*   k=k+1;  */
1.238     brouard  14510:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  14511:     k=TKresult[nres];
1.338     brouard  14512:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  14513:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   14514:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   14515:     /*         continue; */
                   14516:     fprintf(ficrespijb,"\n#****** ");
                   14517:     for(j=1;j<=cptcovs;j++){
1.338     brouard  14518:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.337     brouard  14519:       /* for(j=1;j<=cptcoveff;j++) */
                   14520:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14521:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   14522:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14523:     }
                   14524:     fprintf(ficrespijb,"******\n");
                   14525:     if(invalidvarcomb[k]){  /* Is it necessary here? */
                   14526:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   14527:       continue;
                   14528:     }
                   14529:     
                   14530:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   14531:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   14532:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   14533:       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 */
                   14534:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
                   14535:       
                   14536:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   14537:       
                   14538:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   14539:       /* and memory limitations if stepm is small */
                   14540:       
                   14541:       /* oldm=oldms;savm=savms; */
                   14542:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   14543:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
                   14544:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   14545:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
                   14546:       for(i=1; i<=nlstate;i++)
                   14547:        for(j=1; j<=nlstate+ndeath;j++)
                   14548:          fprintf(ficrespijb," %1d-%1d",i,j);
                   14549:       fprintf(ficrespijb,"\n");
                   14550:       for (h=0; h<=nhstepm; h++){
                   14551:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   14552:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   14553:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  14554:        for(i=1; i<=nlstate;i++)
                   14555:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  14556:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.217     brouard  14557:        fprintf(ficrespijb,"\n");
1.337     brouard  14558:       }
                   14559:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   14560:       fprintf(ficrespijb,"\n");
                   14561:     } /* end age deb */
                   14562:     /* } /\* end combination *\/ */
1.238     brouard  14563:   } /* end nres */
1.218     brouard  14564:   return 0;
                   14565:  } /*  hBijx */
1.217     brouard  14566: 
1.180     brouard  14567: 
1.136     brouard  14568: /***********************************************/
                   14569: /**************** Main Program *****************/
                   14570: /***********************************************/
                   14571: 
                   14572: int main(int argc, char *argv[])
                   14573: {
                   14574: #ifdef GSL
                   14575:   const gsl_multimin_fminimizer_type *T;
                   14576:   size_t iteri = 0, it;
                   14577:   int rval = GSL_CONTINUE;
                   14578:   int status = GSL_SUCCESS;
                   14579:   double ssval;
                   14580: #endif
                   14581:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  14582:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   14583:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  14584:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  14585:   int jj, ll, li, lj, lk;
1.136     brouard  14586:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  14587:   int num_filled;
1.136     brouard  14588:   int itimes;
                   14589:   int NDIM=2;
                   14590:   int vpopbased=0;
1.235     brouard  14591:   int nres=0;
1.258     brouard  14592:   int endishere=0;
1.277     brouard  14593:   int noffset=0;
1.274     brouard  14594:   int ncurrv=0; /* Temporary variable */
                   14595:   
1.164     brouard  14596:   char ca[32], cb[32];
1.136     brouard  14597:   /*  FILE *fichtm; *//* Html File */
                   14598:   /* FILE *ficgp;*/ /*Gnuplot File */
                   14599:   struct stat info;
1.191     brouard  14600:   double agedeb=0.;
1.194     brouard  14601: 
                   14602:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  14603:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  14604: 
1.165     brouard  14605:   double fret;
1.191     brouard  14606:   double dum=0.; /* Dummy variable */
1.359     brouard  14607:   /* double*** p3mat;*/
1.218     brouard  14608:   /* double ***mobaverage; */
1.319     brouard  14609:   double wald;
1.164     brouard  14610: 
1.351     brouard  14611:   char line[MAXLINE], linetmp[MAXLINE];
1.197     brouard  14612:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   14613: 
1.234     brouard  14614:   char  modeltemp[MAXLINE];
1.332     brouard  14615:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  14616:   
1.136     brouard  14617:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  14618:   char *tok, *val; /* pathtot */
1.334     brouard  14619:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.359     brouard  14620:   int c, h; /* c2; */
1.191     brouard  14621:   int jl=0;
                   14622:   int i1, j1, jk, stepsize=0;
1.194     brouard  14623:   int count=0;
                   14624: 
1.164     brouard  14625:   int *tab; 
1.136     brouard  14626:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  14627:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   14628:   /* double anprojf, mprojf, jprojf; */
                   14629:   /* double jintmean,mintmean,aintmean;   */
                   14630:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   14631:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   14632:   double yrfproj= 10.0; /* Number of years of forward projections */
                   14633:   double yrbproj= 10.0; /* Number of years of backward projections */
                   14634:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  14635:   int mobilav=0,popforecast=0;
1.191     brouard  14636:   int hstepm=0, nhstepm=0;
1.136     brouard  14637:   int agemortsup;
                   14638:   float  sumlpop=0.;
                   14639:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   14640:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   14641: 
1.191     brouard  14642:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  14643:   double ftolpl=FTOL;
                   14644:   double **prlim;
1.217     brouard  14645:   double **bprlim;
1.317     brouard  14646:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   14647:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  14648:   double ***paramstart; /* Matrix of starting parameter values */
                   14649:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  14650:   double **matcov; /* Matrix of covariance */
1.203     brouard  14651:   double **hess; /* Hessian matrix */
1.136     brouard  14652:   double ***delti3; /* Scale */
                   14653:   double *delti; /* Scale */
                   14654:   double ***eij, ***vareij;
1.359     brouard  14655:   //double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  14656: 
1.136     brouard  14657:   double *epj, vepp;
1.164     brouard  14658: 
1.273     brouard  14659:   double dateprev1, dateprev2;
1.296     brouard  14660:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   14661:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   14662: 
1.217     brouard  14663: 
1.136     brouard  14664:   double **ximort;
1.145     brouard  14665:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  14666:   int *dcwave;
                   14667: 
1.164     brouard  14668:   char z[1]="c";
1.136     brouard  14669: 
                   14670:   /*char  *strt;*/
                   14671:   char strtend[80];
1.126     brouard  14672: 
1.164     brouard  14673: 
1.126     brouard  14674: /*   setlocale (LC_ALL, ""); */
                   14675: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   14676: /*   textdomain (PACKAGE); */
                   14677: /*   setlocale (LC_CTYPE, ""); */
                   14678: /*   setlocale (LC_MESSAGES, ""); */
                   14679: 
                   14680:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  14681:   rstart_time = time(NULL);  
                   14682:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   14683:   start_time = *localtime(&rstart_time);
1.126     brouard  14684:   curr_time=start_time;
1.157     brouard  14685:   /*tml = *localtime(&start_time.tm_sec);*/
                   14686:   /* strcpy(strstart,asctime(&tml)); */
                   14687:   strcpy(strstart,asctime(&start_time));
1.126     brouard  14688: 
                   14689: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  14690: /*  tp.tm_sec = tp.tm_sec +86400; */
                   14691: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  14692: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   14693: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   14694: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  14695: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  14696: /*   strt=asctime(&tmg); */
                   14697: /*   printf("Time(after) =%s",strstart);  */
                   14698: /*  (void) time (&time_value);
                   14699: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   14700: *  tm = *localtime(&time_value);
                   14701: *  strstart=asctime(&tm);
                   14702: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   14703: */
                   14704: 
                   14705:   nberr=0; /* Number of errors and warnings */
                   14706:   nbwarn=0;
1.184     brouard  14707: #ifdef WIN32
                   14708:   _getcwd(pathcd, size);
                   14709: #else
1.126     brouard  14710:   getcwd(pathcd, size);
1.184     brouard  14711: #endif
1.191     brouard  14712:   syscompilerinfo(0);
1.359     brouard  14713:   printf("\nIMaCh prax version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  14714:   if(argc <=1){
                   14715:     printf("\nEnter the parameter file name: ");
1.205     brouard  14716:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   14717:       printf("ERROR Empty parameter file name\n");
                   14718:       goto end;
                   14719:     }
1.126     brouard  14720:     i=strlen(pathr);
                   14721:     if(pathr[i-1]=='\n')
                   14722:       pathr[i-1]='\0';
1.156     brouard  14723:     i=strlen(pathr);
1.205     brouard  14724:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  14725:       pathr[i-1]='\0';
1.205     brouard  14726:     }
                   14727:     i=strlen(pathr);
                   14728:     if( i==0 ){
                   14729:       printf("ERROR Empty parameter file name\n");
                   14730:       goto end;
                   14731:     }
                   14732:     for (tok = pathr; tok != NULL; ){
1.126     brouard  14733:       printf("Pathr |%s|\n",pathr);
                   14734:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   14735:       printf("val= |%s| pathr=%s\n",val,pathr);
                   14736:       strcpy (pathtot, val);
                   14737:       if(pathr[0] == '\0') break; /* Dirty */
                   14738:     }
                   14739:   }
1.281     brouard  14740:   else if (argc<=2){
                   14741:     strcpy(pathtot,argv[1]);
                   14742:   }
1.126     brouard  14743:   else{
                   14744:     strcpy(pathtot,argv[1]);
1.281     brouard  14745:     strcpy(z,argv[2]);
                   14746:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  14747:   }
                   14748:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   14749:   /*cygwin_split_path(pathtot,path,optionfile);
                   14750:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   14751:   /* cutv(path,optionfile,pathtot,'\\');*/
                   14752: 
                   14753:   /* Split argv[0], imach program to get pathimach */
                   14754:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   14755:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   14756:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   14757:  /*   strcpy(pathimach,argv[0]); */
                   14758:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   14759:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   14760:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  14761: #ifdef WIN32
                   14762:   _chdir(path); /* Can be a relative path */
                   14763:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   14764: #else
1.126     brouard  14765:   chdir(path); /* Can be a relative path */
1.184     brouard  14766:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   14767: #endif
                   14768:   printf("Current directory %s!\n",pathcd);
1.126     brouard  14769:   strcpy(command,"mkdir ");
                   14770:   strcat(command,optionfilefiname);
                   14771:   if((outcmd=system(command)) != 0){
1.169     brouard  14772:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  14773:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   14774:     /* fclose(ficlog); */
                   14775: /*     exit(1); */
                   14776:   }
                   14777: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   14778: /*     perror("mkdir"); */
                   14779: /*   } */
                   14780: 
                   14781:   /*-------- arguments in the command line --------*/
                   14782: 
1.186     brouard  14783:   /* Main Log file */
1.126     brouard  14784:   strcat(filelog, optionfilefiname);
                   14785:   strcat(filelog,".log");    /* */
                   14786:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   14787:     printf("Problem with logfile %s\n",filelog);
                   14788:     goto end;
                   14789:   }
                   14790:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  14791:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  14792:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   14793:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   14794:  path=%s \n\
                   14795:  optionfile=%s\n\
                   14796:  optionfilext=%s\n\
1.156     brouard  14797:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  14798: 
1.197     brouard  14799:   syscompilerinfo(1);
1.167     brouard  14800: 
1.126     brouard  14801:   printf("Local time (at start):%s",strstart);
                   14802:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   14803:   fflush(ficlog);
                   14804: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  14805: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  14806: 
                   14807:   /* */
                   14808:   strcpy(fileres,"r");
                   14809:   strcat(fileres, optionfilefiname);
1.201     brouard  14810:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  14811:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  14812:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  14813: 
1.186     brouard  14814:   /* Main ---------arguments file --------*/
1.126     brouard  14815: 
                   14816:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  14817:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   14818:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  14819:     fflush(ficlog);
1.149     brouard  14820:     /* goto end; */
                   14821:     exit(70); 
1.126     brouard  14822:   }
                   14823: 
                   14824:   strcpy(filereso,"o");
1.201     brouard  14825:   strcat(filereso,fileresu);
1.126     brouard  14826:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   14827:     printf("Problem with Output resultfile: %s\n", filereso);
                   14828:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   14829:     fflush(ficlog);
                   14830:     goto end;
                   14831:   }
1.278     brouard  14832:       /*-------- Rewriting parameter file ----------*/
                   14833:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   14834:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   14835:   strcat(rfileres,".");    /* */
                   14836:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   14837:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   14838:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   14839:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   14840:     fflush(ficlog);
                   14841:     goto end;
                   14842:   }
                   14843:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  14844: 
1.278     brouard  14845:                                      
1.126     brouard  14846:   /* Reads comments: lines beginning with '#' */
                   14847:   numlinepar=0;
1.277     brouard  14848:   /* Is it a BOM UTF-8 Windows file? */
                   14849:   /* First parameter line */
1.197     brouard  14850:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  14851:     noffset=0;
                   14852:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   14853:     {
                   14854:       noffset=noffset+3;
                   14855:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   14856:     }
1.302     brouard  14857: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   14858:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  14859:     {
                   14860:       noffset=noffset+2;
                   14861:       printf("# File is an UTF16BE BOM file\n");
                   14862:     }
                   14863:     else if( line[0] == 0 && line[1] == 0)
                   14864:     {
                   14865:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   14866:        noffset=noffset+4;
                   14867:        printf("# File is an UTF16BE BOM file\n");
                   14868:       }
                   14869:     } else{
                   14870:       ;/*printf(" Not a BOM file\n");*/
                   14871:     }
                   14872:   
1.197     brouard  14873:     /* If line starts with a # it is a comment */
1.277     brouard  14874:     if (line[noffset] == '#') {
1.197     brouard  14875:       numlinepar++;
                   14876:       fputs(line,stdout);
                   14877:       fputs(line,ficparo);
1.278     brouard  14878:       fputs(line,ficres);
1.197     brouard  14879:       fputs(line,ficlog);
                   14880:       continue;
                   14881:     }else
                   14882:       break;
                   14883:   }
                   14884:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   14885:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   14886:     if (num_filled != 5) {
                   14887:       printf("Should be 5 parameters\n");
1.283     brouard  14888:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  14889:     }
1.126     brouard  14890:     numlinepar++;
1.197     brouard  14891:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  14892:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   14893:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   14894:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  14895:   }
                   14896:   /* Second parameter line */
                   14897:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  14898:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   14899:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  14900:     if (line[0] == '#') {
                   14901:       numlinepar++;
1.283     brouard  14902:       printf("%s",line);
                   14903:       fprintf(ficres,"%s",line);
                   14904:       fprintf(ficparo,"%s",line);
                   14905:       fprintf(ficlog,"%s",line);
1.197     brouard  14906:       continue;
                   14907:     }else
                   14908:       break;
                   14909:   }
1.223     brouard  14910:   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", \
                   14911:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   14912:     if (num_filled != 11) {
                   14913:       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  14914:       printf("but line=%s\n",line);
1.283     brouard  14915:       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");
                   14916:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  14917:     }
1.286     brouard  14918:     if( lastpass > maxwav){
                   14919:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   14920:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   14921:       fflush(ficlog);
                   14922:       goto end;
                   14923:     }
                   14924:       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  14925:     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  14926:     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  14927:     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  14928:   }
1.203     brouard  14929:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  14930:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  14931:   /* Third parameter line */
                   14932:   while(fgets(line, MAXLINE, ficpar)) {
                   14933:     /* If line starts with a # it is a comment */
                   14934:     if (line[0] == '#') {
                   14935:       numlinepar++;
1.283     brouard  14936:       printf("%s",line);
                   14937:       fprintf(ficres,"%s",line);
                   14938:       fprintf(ficparo,"%s",line);
                   14939:       fprintf(ficlog,"%s",line);
1.197     brouard  14940:       continue;
                   14941:     }else
                   14942:       break;
                   14943:   }
1.351     brouard  14944:   if((num_filled=sscanf(line,"model=%[^.\n]", model)) !=EOF){ /* Every character after model but dot and  return */
                   14945:     if (num_filled != 1){
                   14946:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   14947:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   14948:       model[0]='\0';
                   14949:       goto end;
                   14950:     }else{
                   14951:       trimbtab(linetmp,line); /* Trims multiple blanks in line */
                   14952:       strcpy(line, linetmp);
                   14953:     }
                   14954:   }
                   14955:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){ /* Every character after 1+age but dot and  return */
1.279     brouard  14956:     if (num_filled != 1){
1.302     brouard  14957:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   14958:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  14959:       model[0]='\0';
                   14960:       goto end;
                   14961:     }
                   14962:     else{
                   14963:       if (model[0]=='+'){
                   14964:        for(i=1; i<=strlen(model);i++)
                   14965:          modeltemp[i-1]=model[i];
1.201     brouard  14966:        strcpy(model,modeltemp); 
1.197     brouard  14967:       }
                   14968:     }
1.338     brouard  14969:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  14970:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  14971:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   14972:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   14973:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  14974:   }
                   14975:   /* 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); */
                   14976:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   14977:   /* 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  14978:   /* 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); */
                   14979:   /* 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  14980:   fflush(ficlog);
1.190     brouard  14981:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   14982:   if(model[0]=='#'){
1.279     brouard  14983:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   14984:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   14985:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  14986:     if(mle != -1){
1.279     brouard  14987:       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  14988:       exit(1);
                   14989:     }
                   14990:   }
1.126     brouard  14991:   while((c=getc(ficpar))=='#' && c!= EOF){
                   14992:     ungetc(c,ficpar);
                   14993:     fgets(line, MAXLINE, ficpar);
                   14994:     numlinepar++;
1.195     brouard  14995:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   14996:       z[0]=line[1];
1.342     brouard  14997:     }else if(line[1]=='d'){ /* For debugging individual values of covariates in ficresilk */
1.343     brouard  14998:       debugILK=1;printf("DebugILK\n");
1.195     brouard  14999:     }
                   15000:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  15001:     fputs(line, stdout);
                   15002:     //puts(line);
1.126     brouard  15003:     fputs(line,ficparo);
                   15004:     fputs(line,ficlog);
                   15005:   }
                   15006:   ungetc(c,ficpar);
                   15007: 
                   15008:    
1.290     brouard  15009:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   15010:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   15011:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
1.341     brouard  15012:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /\**< Time varying covariate (dummy and quantitative)*\/ */
                   15013:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /**< Might be better */
1.136     brouard  15014:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   15015:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   15016:      v1+v2*age+v2*v3 makes cptcovn = 3
                   15017:   */
                   15018:   if (strlen(model)>1) 
1.187     brouard  15019:     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  15020:   else
1.187     brouard  15021:     ncovmodel=2; /* Constant and age */
1.133     brouard  15022:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   15023:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  15024:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   15025:     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);
                   15026:     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);
                   15027:     fflush(stdout);
                   15028:     fclose (ficlog);
                   15029:     goto end;
                   15030:   }
1.126     brouard  15031:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   15032:   delti=delti3[1][1];
                   15033:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   15034:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  15035: /* We could also provide initial parameters values giving by simple logistic regression 
                   15036:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   15037:       /* for(i=1;i<nlstate;i++){ */
                   15038:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   15039:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   15040:       /* } */
1.126     brouard  15041:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  15042:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   15043:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  15044:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   15045:     fclose (ficparo);
                   15046:     fclose (ficlog);
                   15047:     goto end;
                   15048:     exit(0);
1.220     brouard  15049:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  15050:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  15051:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   15052:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  15053:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   15054:     matcov=matrix(1,npar,1,npar);
1.203     brouard  15055:     hess=matrix(1,npar,1,npar);
1.220     brouard  15056:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  15057:     /* Read guessed parameters */
1.126     brouard  15058:     /* Reads comments: lines beginning with '#' */
                   15059:     while((c=getc(ficpar))=='#' && c!= EOF){
                   15060:       ungetc(c,ficpar);
                   15061:       fgets(line, MAXLINE, ficpar);
                   15062:       numlinepar++;
1.141     brouard  15063:       fputs(line,stdout);
1.126     brouard  15064:       fputs(line,ficparo);
                   15065:       fputs(line,ficlog);
                   15066:     }
                   15067:     ungetc(c,ficpar);
                   15068:     
                   15069:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  15070:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  15071:     for(i=1; i <=nlstate; i++){
1.234     brouard  15072:       j=0;
1.126     brouard  15073:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  15074:        if(jj==i) continue;
                   15075:        j++;
1.292     brouard  15076:        while((c=getc(ficpar))=='#' && c!= EOF){
                   15077:          ungetc(c,ficpar);
                   15078:          fgets(line, MAXLINE, ficpar);
                   15079:          numlinepar++;
                   15080:          fputs(line,stdout);
                   15081:          fputs(line,ficparo);
                   15082:          fputs(line,ficlog);
                   15083:        }
                   15084:        ungetc(c,ficpar);
1.234     brouard  15085:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   15086:        if ((i1 != i) || (j1 != jj)){
                   15087:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  15088: It might be a problem of design; if ncovcol and the model are correct\n \
                   15089: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  15090:          exit(1);
                   15091:        }
                   15092:        fprintf(ficparo,"%1d%1d",i1,j1);
                   15093:        if(mle==1)
                   15094:          printf("%1d%1d",i,jj);
                   15095:        fprintf(ficlog,"%1d%1d",i,jj);
                   15096:        for(k=1; k<=ncovmodel;k++){
                   15097:          fscanf(ficpar," %lf",&param[i][j][k]);
                   15098:          if(mle==1){
                   15099:            printf(" %lf",param[i][j][k]);
                   15100:            fprintf(ficlog," %lf",param[i][j][k]);
                   15101:          }
                   15102:          else
                   15103:            fprintf(ficlog," %lf",param[i][j][k]);
                   15104:          fprintf(ficparo," %lf",param[i][j][k]);
                   15105:        }
                   15106:        fscanf(ficpar,"\n");
                   15107:        numlinepar++;
                   15108:        if(mle==1)
                   15109:          printf("\n");
                   15110:        fprintf(ficlog,"\n");
                   15111:        fprintf(ficparo,"\n");
1.126     brouard  15112:       }
                   15113:     }  
                   15114:     fflush(ficlog);
1.234     brouard  15115:     
1.251     brouard  15116:     /* Reads parameters values */
1.126     brouard  15117:     p=param[1][1];
1.251     brouard  15118:     pstart=paramstart[1][1];
1.126     brouard  15119:     
                   15120:     /* Reads comments: lines beginning with '#' */
                   15121:     while((c=getc(ficpar))=='#' && c!= EOF){
                   15122:       ungetc(c,ficpar);
                   15123:       fgets(line, MAXLINE, ficpar);
                   15124:       numlinepar++;
1.141     brouard  15125:       fputs(line,stdout);
1.126     brouard  15126:       fputs(line,ficparo);
                   15127:       fputs(line,ficlog);
                   15128:     }
                   15129:     ungetc(c,ficpar);
                   15130: 
                   15131:     for(i=1; i <=nlstate; i++){
                   15132:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  15133:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   15134:        if ( (i1-i) * (j1-j) != 0){
                   15135:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   15136:          exit(1);
                   15137:        }
                   15138:        printf("%1d%1d",i,j);
                   15139:        fprintf(ficparo,"%1d%1d",i1,j1);
                   15140:        fprintf(ficlog,"%1d%1d",i1,j1);
                   15141:        for(k=1; k<=ncovmodel;k++){
                   15142:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   15143:          printf(" %le",delti3[i][j][k]);
                   15144:          fprintf(ficparo," %le",delti3[i][j][k]);
                   15145:          fprintf(ficlog," %le",delti3[i][j][k]);
                   15146:        }
                   15147:        fscanf(ficpar,"\n");
                   15148:        numlinepar++;
                   15149:        printf("\n");
                   15150:        fprintf(ficparo,"\n");
                   15151:        fprintf(ficlog,"\n");
1.126     brouard  15152:       }
                   15153:     }
                   15154:     fflush(ficlog);
1.234     brouard  15155:     
1.145     brouard  15156:     /* Reads covariance matrix */
1.126     brouard  15157:     delti=delti3[1][1];
1.220     brouard  15158:                
                   15159:                
1.126     brouard  15160:     /* 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  15161:                
1.126     brouard  15162:     /* Reads comments: lines beginning with '#' */
                   15163:     while((c=getc(ficpar))=='#' && c!= EOF){
                   15164:       ungetc(c,ficpar);
                   15165:       fgets(line, MAXLINE, ficpar);
                   15166:       numlinepar++;
1.141     brouard  15167:       fputs(line,stdout);
1.126     brouard  15168:       fputs(line,ficparo);
                   15169:       fputs(line,ficlog);
                   15170:     }
                   15171:     ungetc(c,ficpar);
1.220     brouard  15172:                
1.126     brouard  15173:     matcov=matrix(1,npar,1,npar);
1.203     brouard  15174:     hess=matrix(1,npar,1,npar);
1.131     brouard  15175:     for(i=1; i <=npar; i++)
                   15176:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  15177:                
1.194     brouard  15178:     /* Scans npar lines */
1.126     brouard  15179:     for(i=1; i <=npar; i++){
1.226     brouard  15180:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  15181:       if(count != 3){
1.226     brouard  15182:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  15183: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   15184: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  15185:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  15186: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   15187: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  15188:        exit(1);
1.220     brouard  15189:       }else{
1.226     brouard  15190:        if(mle==1)
                   15191:          printf("%1d%1d%d",i1,j1,jk);
                   15192:       }
                   15193:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   15194:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  15195:       for(j=1; j <=i; j++){
1.226     brouard  15196:        fscanf(ficpar," %le",&matcov[i][j]);
                   15197:        if(mle==1){
                   15198:          printf(" %.5le",matcov[i][j]);
                   15199:        }
                   15200:        fprintf(ficlog," %.5le",matcov[i][j]);
                   15201:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  15202:       }
                   15203:       fscanf(ficpar,"\n");
                   15204:       numlinepar++;
                   15205:       if(mle==1)
1.220     brouard  15206:                                printf("\n");
1.126     brouard  15207:       fprintf(ficlog,"\n");
                   15208:       fprintf(ficparo,"\n");
                   15209:     }
1.194     brouard  15210:     /* End of read covariance matrix npar lines */
1.126     brouard  15211:     for(i=1; i <=npar; i++)
                   15212:       for(j=i+1;j<=npar;j++)
1.226     brouard  15213:        matcov[i][j]=matcov[j][i];
1.126     brouard  15214:     
                   15215:     if(mle==1)
                   15216:       printf("\n");
                   15217:     fprintf(ficlog,"\n");
                   15218:     
                   15219:     fflush(ficlog);
                   15220:     
                   15221:   }    /* End of mle != -3 */
1.218     brouard  15222:   
1.186     brouard  15223:   /*  Main data
                   15224:    */
1.290     brouard  15225:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   15226:   /* num=lvector(1,n); */
                   15227:   /* moisnais=vector(1,n); */
                   15228:   /* annais=vector(1,n); */
                   15229:   /* moisdc=vector(1,n); */
                   15230:   /* andc=vector(1,n); */
                   15231:   /* weight=vector(1,n); */
                   15232:   /* agedc=vector(1,n); */
                   15233:   /* cod=ivector(1,n); */
                   15234:   /* for(i=1;i<=n;i++){ */
                   15235:   num=lvector(firstobs,lastobs);
                   15236:   moisnais=vector(firstobs,lastobs);
                   15237:   annais=vector(firstobs,lastobs);
                   15238:   moisdc=vector(firstobs,lastobs);
                   15239:   andc=vector(firstobs,lastobs);
                   15240:   weight=vector(firstobs,lastobs);
                   15241:   agedc=vector(firstobs,lastobs);
                   15242:   cod=ivector(firstobs,lastobs);
                   15243:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  15244:     num[i]=0;
                   15245:     moisnais[i]=0;
                   15246:     annais[i]=0;
                   15247:     moisdc[i]=0;
                   15248:     andc[i]=0;
                   15249:     agedc[i]=0;
                   15250:     cod[i]=0;
                   15251:     weight[i]=1.0; /* Equal weights, 1 by default */
                   15252:   }
1.290     brouard  15253:   mint=matrix(1,maxwav,firstobs,lastobs);
                   15254:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  15255:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
1.336     brouard  15256:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
1.126     brouard  15257:   tab=ivector(1,NCOVMAX);
1.144     brouard  15258:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  15259:   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  15260: 
1.136     brouard  15261:   /* Reads data from file datafile */
                   15262:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   15263:     goto end;
                   15264: 
                   15265:   /* Calculation of the number of parameters from char model */
1.234     brouard  15266:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  15267:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   15268:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   15269:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   15270:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  15271:   */
                   15272:   
                   15273:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   15274:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  15275:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335     brouard  15276:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  15277:   TvarsD=ivector(1,NCOVMAX); /*  */
                   15278:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   15279:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  15280:   TvarF=ivector(1,NCOVMAX); /*  */
                   15281:   TvarFind=ivector(1,NCOVMAX); /*  */
                   15282:   TvarV=ivector(1,NCOVMAX); /*  */
                   15283:   TvarVind=ivector(1,NCOVMAX); /*  */
                   15284:   TvarA=ivector(1,NCOVMAX); /*  */
                   15285:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  15286:   TvarFD=ivector(1,NCOVMAX); /*  */
                   15287:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   15288:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   15289:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   15290:   TvarVD=ivector(1,NCOVMAX); /*  */
                   15291:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   15292:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   15293:   TvarVQind=ivector(1,NCOVMAX); /*  */
1.339     brouard  15294:   TvarVV=ivector(1,NCOVMAX); /*  */
                   15295:   TvarVVind=ivector(1,NCOVMAX); /*  */
1.349     brouard  15296:   TvarVVA=ivector(1,NCOVMAX); /*  */
                   15297:   TvarVVAind=ivector(1,NCOVMAX); /*  */
                   15298:   TvarAVVA=ivector(1,NCOVMAX); /*  */
                   15299:   TvarAVVAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  15300: 
1.230     brouard  15301:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  15302:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  15303:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   15304:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   15305:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.349     brouard  15306:   DummyV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   15307:   FixedV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   15308: 
1.137     brouard  15309:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   15310:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   15311:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   15312:   */
                   15313:   /* For model-covariate k tells which data-covariate to use but
                   15314:     because this model-covariate is a construction we invent a new column
                   15315:     ncovcol + k1
                   15316:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   15317:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  15318:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   15319:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  15320:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   15321:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  15322:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  15323:   */
1.145     brouard  15324:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   15325:   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  15326:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   15327:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.351     brouard  15328:   Tvardk=imatrix(0,NCOVMAX,1,2);
1.145     brouard  15329:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  15330:                         4 covariates (3 plus signs)
                   15331:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  15332:                           */  
                   15333:   for(i=1;i<NCOVMAX;i++)
                   15334:     Tage[i]=0;
1.230     brouard  15335:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  15336:                                * individual dummy, fixed or varying:
                   15337:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   15338:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  15339:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   15340:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   15341:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   15342:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   15343:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  15344:                                * individual quantitative, fixed or varying:
                   15345:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   15346:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   15347:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.349     brouard  15348: 
                   15349: /* Probably useless zeroes */
                   15350:   for(i=1;i<NCOVMAX;i++){
                   15351:     DummyV[i]=0;
                   15352:     FixedV[i]=0;
                   15353:   }
                   15354: 
                   15355:   for(i=1; i <=ncovcol;i++){
                   15356:     DummyV[i]=0;
                   15357:     FixedV[i]=0;
                   15358:   }
                   15359:   for(i=ncovcol+1; i <=ncovcol+nqv;i++){
                   15360:     DummyV[i]=1;
                   15361:     FixedV[i]=0;
                   15362:   }
                   15363:   for(i=ncovcol+nqv+1; i <=ncovcol+nqv+ntv;i++){
                   15364:     DummyV[i]=0;
                   15365:     FixedV[i]=1;
                   15366:   }
                   15367:   for(i=ncovcol+nqv+ntv+1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   15368:     DummyV[i]=1;
                   15369:     FixedV[i]=1;
                   15370:   }
                   15371:   for(i=1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   15372:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",i,i,DummyV[i],i,FixedV[i]);
                   15373:     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]);
                   15374:   }
                   15375: 
                   15376: 
                   15377: 
1.186     brouard  15378: /* Main decodemodel */
                   15379: 
1.187     brouard  15380: 
1.223     brouard  15381:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  15382:     goto end;
                   15383: 
1.137     brouard  15384:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   15385:     nbwarn++;
                   15386:     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); 
                   15387:     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); 
                   15388:   }
1.136     brouard  15389:     /*  if(mle==1){*/
1.137     brouard  15390:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   15391:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  15392:   }
                   15393: 
                   15394:     /*-calculation of age at interview from date of interview and age at death -*/
                   15395:   agev=matrix(1,maxwav,1,imx);
                   15396: 
                   15397:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   15398:     goto end;
                   15399: 
1.126     brouard  15400: 
1.136     brouard  15401:   agegomp=(int)agemin;
1.290     brouard  15402:   free_vector(moisnais,firstobs,lastobs);
                   15403:   free_vector(annais,firstobs,lastobs);
1.126     brouard  15404:   /* free_matrix(mint,1,maxwav,1,n);
                   15405:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  15406:   /* free_vector(moisdc,1,n); */
                   15407:   /* free_vector(andc,1,n); */
1.145     brouard  15408:   /* */
                   15409:   
1.126     brouard  15410:   wav=ivector(1,imx);
1.214     brouard  15411:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   15412:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   15413:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   15414:   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.*/
                   15415:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   15416:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  15417:    
                   15418:   /* Concatenates waves */
1.214     brouard  15419:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   15420:      Death is a valid wave (if date is known).
                   15421:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   15422:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   15423:      and mw[mi+1][i]. dh depends on stepm.
                   15424:   */
                   15425: 
1.126     brouard  15426:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  15427:   /* Concatenates waves */
1.145     brouard  15428:  
1.290     brouard  15429:   free_vector(moisdc,firstobs,lastobs);
                   15430:   free_vector(andc,firstobs,lastobs);
1.215     brouard  15431: 
1.126     brouard  15432:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   15433:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   15434:   ncodemax[1]=1;
1.145     brouard  15435:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  15436:   cptcoveff=0;
1.220     brouard  15437:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335     brouard  15438:     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  15439:   }
                   15440:   
                   15441:   ncovcombmax=pow(2,cptcoveff);
1.338     brouard  15442:   invalidvarcomb=ivector(0, ncovcombmax); 
                   15443:   for(i=0;i<ncovcombmax;i++)
1.227     brouard  15444:     invalidvarcomb[i]=0;
                   15445:   
1.211     brouard  15446:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  15447:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  15448:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  15449:   
1.200     brouard  15450:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  15451:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  15452:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  15453:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   15454:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   15455:    * (currently 0 or 1) in the data.
                   15456:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   15457:    * corresponding modality (h,j).
                   15458:    */
                   15459: 
1.145     brouard  15460:   h=0;
                   15461:   /*if (cptcovn > 0) */
1.126     brouard  15462:   m=pow(2,cptcoveff);
                   15463:  
1.144     brouard  15464:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  15465:           * For k=4 covariates, h goes from 1 to m=2**k
                   15466:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   15467:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  15468:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   15469:           *______________________________   *______________________
                   15470:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   15471:           *     2     2     1     1     1   *     1     0  0  0  1 
                   15472:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   15473:           *     4     2     2     1     1   *     3     0  0  1  1 
                   15474:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   15475:           *     6     2     1     2     1   *     5     0  1  0  1 
                   15476:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   15477:           *     8     2     2     2     1   *     7     0  1  1  1 
                   15478:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   15479:           *    10     2     1     1     2   *     9     1  0  0  1 
                   15480:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   15481:           *    12     2     2     1     2   *    11     1  0  1  1 
                   15482:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   15483:           *    14     2     1     2     2   *    13     1  1  0  1 
                   15484:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   15485:           *    16     2     2     2     2   *    15     1  1  1  1          
                   15486:           */                                     
1.212     brouard  15487:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  15488:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   15489:      * and the value of each covariate?
                   15490:      * V1=1, V2=1, V3=2, V4=1 ?
                   15491:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   15492:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   15493:      * In order to get the real value in the data, we use nbcode
                   15494:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   15495:      * We are keeping this crazy system in order to be able (in the future?) 
                   15496:      * to have more than 2 values (0 or 1) for a covariate.
                   15497:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   15498:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   15499:      *              bbbbbbbb
                   15500:      *              76543210     
                   15501:      *   h-1        00000101 (6-1=5)
1.219     brouard  15502:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  15503:      *           &
                   15504:      *     1        00000001 (1)
1.219     brouard  15505:      *              00000000        = 1 & ((h-1) >> (k-1))
                   15506:      *          +1= 00000001 =1 
1.211     brouard  15507:      *
                   15508:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   15509:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   15510:      *    >>k'            11
                   15511:      *          &   00000001
                   15512:      *            = 00000001
                   15513:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   15514:      * Reverse h=6 and m=16?
                   15515:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   15516:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   15517:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   15518:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   15519:      * V3=decodtabm(14,3,2**4)=2
                   15520:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   15521:      *(h-1) >> (j-1)    0011 =13 >> 2
                   15522:      *          &1 000000001
                   15523:      *           = 000000001
                   15524:      *         +1= 000000010 =2
                   15525:      *                  2211
                   15526:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   15527:      *                  V3=2
1.220     brouard  15528:                 * codtabm and decodtabm are identical
1.211     brouard  15529:      */
                   15530: 
1.145     brouard  15531: 
                   15532:  free_ivector(Ndum,-1,NCOVMAX);
                   15533: 
                   15534: 
1.126     brouard  15535:     
1.186     brouard  15536:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  15537:   strcpy(optionfilegnuplot,optionfilefiname);
                   15538:   if(mle==-3)
1.201     brouard  15539:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  15540:   strcat(optionfilegnuplot,".gp");
                   15541: 
                   15542:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   15543:     printf("Problem with file %s",optionfilegnuplot);
                   15544:   }
                   15545:   else{
1.204     brouard  15546:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  15547:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  15548:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   15549:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  15550:   }
                   15551:   /*  fclose(ficgp);*/
1.186     brouard  15552: 
                   15553: 
                   15554:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  15555: 
                   15556:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   15557:   if(mle==-3)
1.201     brouard  15558:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  15559:   strcat(optionfilehtm,".htm");
                   15560:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  15561:     printf("Problem with %s \n",optionfilehtm);
                   15562:     exit(0);
1.126     brouard  15563:   }
                   15564: 
                   15565:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   15566:   strcat(optionfilehtmcov,"-cov.htm");
                   15567:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   15568:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   15569:   }
                   15570:   else{
                   15571:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   15572: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  15573: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  15574:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   15575:   }
                   15576: 
1.335     brouard  15577:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   15578: <title>IMaCh %s</title></head>\n\
                   15579:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   15580: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   15581: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   15582: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   15583: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   15584:   
                   15585:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  15586: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  15587: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.337     brouard  15588: 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  15589: \n\
                   15590: <hr  size=\"2\" color=\"#EC5E5E\">\
                   15591:  <ul><li><h4>Parameter files</h4>\n\
                   15592:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   15593:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   15594:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   15595:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   15596:  - Date and time at start: %s</ul>\n",\
1.335     brouard  15597:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  15598:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   15599:          fileres,fileres,\
                   15600:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   15601:   fflush(fichtm);
                   15602: 
                   15603:   strcpy(pathr,path);
                   15604:   strcat(pathr,optionfilefiname);
1.184     brouard  15605: #ifdef WIN32
                   15606:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   15607: #else
1.126     brouard  15608:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  15609: #endif
                   15610:          
1.126     brouard  15611:   
1.220     brouard  15612:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   15613:                 and for any valid combination of covariates
1.126     brouard  15614:      and prints on file fileres'p'. */
1.359     brouard  15615:   freqsummary(fileres, p, pstart, (double)agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  15616:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  15617: 
                   15618:   fprintf(fichtm,"\n");
1.286     brouard  15619:   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  15620:          ftol, stepm);
                   15621:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   15622:   ncurrv=1;
                   15623:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   15624:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   15625:   ncurrv=i;
                   15626:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  15627:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  15628:   ncurrv=i;
                   15629:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  15630:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  15631:   ncurrv=i;
                   15632:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   15633:   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", \
                   15634:           nlstate, ndeath, maxwav, mle, weightopt);
                   15635: 
                   15636:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   15637: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   15638: 
                   15639:   
1.317     brouard  15640:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  15641: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   15642: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  15643:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  15644:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  15645:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   15646:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   15647:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   15648:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  15649: 
1.126     brouard  15650:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   15651:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   15652:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   15653: 
                   15654:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  15655:   /* For mortality only */
1.126     brouard  15656:   if (mle==-3){
1.136     brouard  15657:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  15658:     for(i=1;i<=NDIM;i++)
                   15659:       for(j=1;j<=NDIM;j++)
                   15660:        ximort[i][j]=0.;
1.186     brouard  15661:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  15662:     cens=ivector(firstobs,lastobs);
                   15663:     ageexmed=vector(firstobs,lastobs);
                   15664:     agecens=vector(firstobs,lastobs);
                   15665:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  15666:                
1.126     brouard  15667:     for (i=1; i<=imx; i++){
                   15668:       dcwave[i]=-1;
                   15669:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  15670:        if (s[m][i]>nlstate) {
                   15671:          dcwave[i]=m;
                   15672:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   15673:          break;
                   15674:        }
1.126     brouard  15675:     }
1.226     brouard  15676:     
1.126     brouard  15677:     for (i=1; i<=imx; i++) {
                   15678:       if (wav[i]>0){
1.226     brouard  15679:        ageexmed[i]=agev[mw[1][i]][i];
                   15680:        j=wav[i];
                   15681:        agecens[i]=1.; 
                   15682:        
                   15683:        if (ageexmed[i]> 1 && wav[i] > 0){
                   15684:          agecens[i]=agev[mw[j][i]][i];
                   15685:          cens[i]= 1;
                   15686:        }else if (ageexmed[i]< 1) 
                   15687:          cens[i]= -1;
                   15688:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   15689:          cens[i]=0 ;
1.126     brouard  15690:       }
                   15691:       else cens[i]=-1;
                   15692:     }
                   15693:     
                   15694:     for (i=1;i<=NDIM;i++) {
                   15695:       for (j=1;j<=NDIM;j++)
1.226     brouard  15696:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  15697:     }
                   15698:     
1.302     brouard  15699:     p[1]=0.0268; p[NDIM]=0.083;
                   15700:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  15701:     
                   15702:     
1.136     brouard  15703: #ifdef GSL
                   15704:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  15705: #else
1.359     brouard  15706:     printf("Powell-mort\n");  fprintf(ficlog,"Powell-mort\n");
1.136     brouard  15707: #endif
1.201     brouard  15708:     strcpy(filerespow,"POW-MORT_"); 
                   15709:     strcat(filerespow,fileresu);
1.126     brouard  15710:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   15711:       printf("Problem with resultfile: %s\n", filerespow);
                   15712:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   15713:     }
1.136     brouard  15714: #ifdef GSL
                   15715:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  15716: #else
1.126     brouard  15717:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  15718: #endif
1.126     brouard  15719:     /*  for (i=1;i<=nlstate;i++)
                   15720:        for(j=1;j<=nlstate+ndeath;j++)
                   15721:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   15722:     */
                   15723:     fprintf(ficrespow,"\n");
1.136     brouard  15724: #ifdef GSL
                   15725:     /* gsl starts here */ 
                   15726:     T = gsl_multimin_fminimizer_nmsimplex;
                   15727:     gsl_multimin_fminimizer *sfm = NULL;
                   15728:     gsl_vector *ss, *x;
                   15729:     gsl_multimin_function minex_func;
                   15730: 
                   15731:     /* Initial vertex size vector */
                   15732:     ss = gsl_vector_alloc (NDIM);
                   15733:     
                   15734:     if (ss == NULL){
                   15735:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   15736:     }
                   15737:     /* Set all step sizes to 1 */
                   15738:     gsl_vector_set_all (ss, 0.001);
                   15739: 
                   15740:     /* Starting point */
1.126     brouard  15741:     
1.136     brouard  15742:     x = gsl_vector_alloc (NDIM);
                   15743:     
                   15744:     if (x == NULL){
                   15745:       gsl_vector_free(ss);
                   15746:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   15747:     }
                   15748:   
                   15749:     /* Initialize method and iterate */
                   15750:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  15751:     /*     gsl_vector_set(x, 0, 0.0268); */
                   15752:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  15753:     gsl_vector_set(x, 0, p[1]);
                   15754:     gsl_vector_set(x, 1, p[2]);
                   15755: 
                   15756:     minex_func.f = &gompertz_f;
                   15757:     minex_func.n = NDIM;
                   15758:     minex_func.params = (void *)&p; /* ??? */
                   15759:     
                   15760:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   15761:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   15762:     
                   15763:     printf("Iterations beginning .....\n\n");
                   15764:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   15765: 
                   15766:     iteri=0;
                   15767:     while (rval == GSL_CONTINUE){
                   15768:       iteri++;
                   15769:       status = gsl_multimin_fminimizer_iterate(sfm);
                   15770:       
                   15771:       if (status) printf("error: %s\n", gsl_strerror (status));
                   15772:       fflush(0);
                   15773:       
                   15774:       if (status) 
                   15775:         break;
                   15776:       
                   15777:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   15778:       ssval = gsl_multimin_fminimizer_size (sfm);
                   15779:       
                   15780:       if (rval == GSL_SUCCESS)
                   15781:         printf ("converged to a local maximum at\n");
                   15782:       
                   15783:       printf("%5d ", iteri);
                   15784:       for (it = 0; it < NDIM; it++){
                   15785:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   15786:       }
                   15787:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   15788:     }
                   15789:     
                   15790:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   15791:     
                   15792:     gsl_vector_free(x); /* initial values */
                   15793:     gsl_vector_free(ss); /* inital step size */
                   15794:     for (it=0; it<NDIM; it++){
                   15795:       p[it+1]=gsl_vector_get(sfm->x,it);
                   15796:       fprintf(ficrespow," %.12lf", p[it]);
                   15797:     }
                   15798:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   15799: #endif
                   15800: #ifdef POWELL
                   15801:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   15802: #endif  
1.126     brouard  15803:     fclose(ficrespow);
                   15804:     
1.203     brouard  15805:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  15806: 
                   15807:     for(i=1; i <=NDIM; i++)
                   15808:       for(j=i+1;j<=NDIM;j++)
1.359     brouard  15809:        matcov[i][j]=matcov[j][i];
1.126     brouard  15810:     
                   15811:     printf("\nCovariance matrix\n ");
1.203     brouard  15812:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  15813:     for(i=1; i <=NDIM; i++) {
                   15814:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  15815:                                printf("%f ",matcov[i][j]);
                   15816:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  15817:       }
1.203     brouard  15818:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  15819:     }
                   15820:     
                   15821:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  15822:     for (i=1;i<=NDIM;i++) {
1.126     brouard  15823:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  15824:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   15825:     }
1.302     brouard  15826:     lsurv=vector(agegomp,AGESUP);
                   15827:     lpop=vector(agegomp,AGESUP);
                   15828:     tpop=vector(agegomp,AGESUP);
1.126     brouard  15829:     lsurv[agegomp]=100000;
                   15830:     
                   15831:     for (k=agegomp;k<=AGESUP;k++) {
                   15832:       agemortsup=k;
                   15833:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   15834:     }
                   15835:     
                   15836:     for (k=agegomp;k<agemortsup;k++)
                   15837:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   15838:     
                   15839:     for (k=agegomp;k<agemortsup;k++){
                   15840:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   15841:       sumlpop=sumlpop+lpop[k];
                   15842:     }
                   15843:     
                   15844:     tpop[agegomp]=sumlpop;
                   15845:     for (k=agegomp;k<(agemortsup-3);k++){
                   15846:       /*  tpop[k+1]=2;*/
                   15847:       tpop[k+1]=tpop[k]-lpop[k];
                   15848:     }
                   15849:     
                   15850:     
                   15851:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   15852:     for (k=agegomp;k<(agemortsup-2);k++) 
                   15853:       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]);
                   15854:     
                   15855:     
                   15856:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  15857:                ageminpar=50;
                   15858:                agemaxpar=100;
1.194     brouard  15859:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   15860:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   15861: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   15862: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   15863:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   15864: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   15865: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  15866:     }else{
                   15867:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   15868:                        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  15869:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  15870:                }
1.201     brouard  15871:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  15872:                     stepm, weightopt,\
                   15873:                     model,imx,p,matcov,agemortsup);
                   15874:     
1.302     brouard  15875:     free_vector(lsurv,agegomp,AGESUP);
                   15876:     free_vector(lpop,agegomp,AGESUP);
                   15877:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  15878:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  15879:     free_ivector(dcwave,firstobs,lastobs);
                   15880:     free_vector(agecens,firstobs,lastobs);
                   15881:     free_vector(ageexmed,firstobs,lastobs);
                   15882:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  15883: #ifdef GSL
1.136     brouard  15884: #endif
1.186     brouard  15885:   } /* Endof if mle==-3 mortality only */
1.205     brouard  15886:   /* Standard  */
                   15887:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   15888:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   15889:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  15890:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  15891:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   15892:     for (k=1; k<=npar;k++)
                   15893:       printf(" %d %8.5f",k,p[k]);
                   15894:     printf("\n");
1.205     brouard  15895:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   15896:       /* mlikeli uses func not funcone */
1.247     brouard  15897:       /* for(i=1;i<nlstate;i++){ */
                   15898:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   15899:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   15900:       /* } */
1.205     brouard  15901:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   15902:     }
                   15903:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   15904:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   15905:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   15906:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   15907:     }
                   15908:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  15909:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   15910:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335     brouard  15911:           /* exit(0); */
1.126     brouard  15912:     for (k=1; k<=npar;k++)
                   15913:       printf(" %d %8.5f",k,p[k]);
                   15914:     printf("\n");
                   15915:     
                   15916:     /*--------- results files --------------*/
1.283     brouard  15917:     /* 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  15918:     
                   15919:     
                   15920:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  15921:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  15922:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  15923: 
                   15924:     printf("#model=  1      +     age ");
                   15925:     fprintf(ficres,"#model=  1      +     age ");
                   15926:     fprintf(ficlog,"#model=  1      +     age ");
                   15927:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   15928: </ul>", model);
                   15929: 
                   15930:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   15931:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   15932:     if(nagesqr==1){
                   15933:       printf("  + age*age  ");
                   15934:       fprintf(ficres,"  + age*age  ");
                   15935:       fprintf(ficlog,"  + age*age  ");
                   15936:       fprintf(fichtm, "<th>+ age*age</th>");
                   15937:     }
                   15938:     for(j=1;j <=ncovmodel-2;j++){
                   15939:       if(Typevar[j]==0) {
                   15940:        printf("  +      V%d  ",Tvar[j]);
                   15941:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   15942:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   15943:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   15944:       }else if(Typevar[j]==1) {
                   15945:        printf("  +    V%d*age ",Tvar[j]);
                   15946:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   15947:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   15948:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   15949:       }else if(Typevar[j]==2) {
                   15950:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   15951:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   15952:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   15953:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  15954:       }else if(Typevar[j]==3) { /* TO VERIFY */
                   15955:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   15956:        fprintf(ficres,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   15957:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   15958:        fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  15959:       }
                   15960:     }
                   15961:     printf("\n");
                   15962:     fprintf(ficres,"\n");
                   15963:     fprintf(ficlog,"\n");
                   15964:     fprintf(fichtm, "</tr>");
                   15965:     fprintf(fichtm, "\n");
                   15966:     
                   15967:     
1.126     brouard  15968:     for(i=1,jk=1; i <=nlstate; i++){
                   15969:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  15970:        if (k != i) {
1.319     brouard  15971:          fprintf(fichtm, "<tr>");
1.225     brouard  15972:          printf("%d%d ",i,k);
                   15973:          fprintf(ficlog,"%d%d ",i,k);
                   15974:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  15975:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  15976:          for(j=1; j <=ncovmodel; j++){
                   15977:            printf("%12.7f ",p[jk]);
                   15978:            fprintf(ficlog,"%12.7f ",p[jk]);
                   15979:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  15980:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  15981:            jk++; 
                   15982:          }
                   15983:          printf("\n");
                   15984:          fprintf(ficlog,"\n");
                   15985:          fprintf(ficres,"\n");
1.319     brouard  15986:          fprintf(fichtm, "</tr>\n");
1.225     brouard  15987:        }
1.126     brouard  15988:       }
                   15989:     }
1.319     brouard  15990:     /* fprintf(fichtm,"</tr>\n"); */
                   15991:     fprintf(fichtm,"</table>\n");
                   15992:     fprintf(fichtm, "\n");
                   15993: 
1.203     brouard  15994:     if(mle != 0){
                   15995:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  15996:       ftolhess=ftol; /* Usually correct */
1.203     brouard  15997:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   15998:       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");
                   15999:       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  16000:       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  16001:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   16002:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   16003:       if(nagesqr==1){
                   16004:        printf("  + age*age  ");
                   16005:        fprintf(ficres,"  + age*age  ");
                   16006:        fprintf(ficlog,"  + age*age  ");
                   16007:        fprintf(fichtm, "<th>+ age*age</th>");
                   16008:       }
                   16009:       for(j=1;j <=ncovmodel-2;j++){
                   16010:        if(Typevar[j]==0) {
                   16011:          printf("  +      V%d  ",Tvar[j]);
                   16012:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   16013:        }else if(Typevar[j]==1) {
                   16014:          printf("  +    V%d*age ",Tvar[j]);
                   16015:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   16016:        }else if(Typevar[j]==2) {
                   16017:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  16018:        }else if(Typevar[j]==3) { /* TO VERIFY */
                   16019:          fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  16020:        }
                   16021:       }
                   16022:       fprintf(fichtm, "</tr>\n");
                   16023:  
1.203     brouard  16024:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  16025:        for(k=1; k <=(nlstate+ndeath); k++){
                   16026:          if (k != i) {
1.319     brouard  16027:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  16028:            printf("%d%d ",i,k);
                   16029:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  16030:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  16031:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  16032:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  16033:              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]));
                   16034:              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  16035:              if(fabs(wald) > 1.96){
1.321     brouard  16036:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  16037:              }else{
                   16038:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   16039:              }
1.324     brouard  16040:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  16041:              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  16042:              jk++; 
                   16043:            }
                   16044:            printf("\n");
                   16045:            fprintf(ficlog,"\n");
1.319     brouard  16046:            fprintf(fichtm, "</tr>\n");
1.225     brouard  16047:          }
                   16048:        }
1.193     brouard  16049:       }
1.203     brouard  16050:     } /* end of hesscov and Wald tests */
1.319     brouard  16051:     fprintf(fichtm,"</table>\n");
1.225     brouard  16052:     
1.203     brouard  16053:     /*  */
1.126     brouard  16054:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   16055:     printf("# Scales (for hessian or gradient estimation)\n");
                   16056:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   16057:     for(i=1,jk=1; i <=nlstate; i++){
                   16058:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  16059:        if (j!=i) {
                   16060:          fprintf(ficres,"%1d%1d",i,j);
                   16061:          printf("%1d%1d",i,j);
                   16062:          fprintf(ficlog,"%1d%1d",i,j);
                   16063:          for(k=1; k<=ncovmodel;k++){
                   16064:            printf(" %.5e",delti[jk]);
                   16065:            fprintf(ficlog," %.5e",delti[jk]);
                   16066:            fprintf(ficres," %.5e",delti[jk]);
                   16067:            jk++;
                   16068:          }
                   16069:          printf("\n");
                   16070:          fprintf(ficlog,"\n");
                   16071:          fprintf(ficres,"\n");
                   16072:        }
1.126     brouard  16073:       }
                   16074:     }
                   16075:     
                   16076:     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  16077:     if(mle >= 1) /* Too big for the screen */
1.126     brouard  16078:       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");
                   16079:     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");
                   16080:     /* # 121 Var(a12)\n\ */
                   16081:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   16082:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   16083:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   16084:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   16085:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   16086:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   16087:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   16088:     
                   16089:     
                   16090:     /* Just to have a covariance matrix which will be more understandable
                   16091:        even is we still don't want to manage dictionary of variables
                   16092:     */
                   16093:     for(itimes=1;itimes<=2;itimes++){
                   16094:       jj=0;
                   16095:       for(i=1; i <=nlstate; i++){
1.225     brouard  16096:        for(j=1; j <=nlstate+ndeath; j++){
                   16097:          if(j==i) continue;
                   16098:          for(k=1; k<=ncovmodel;k++){
                   16099:            jj++;
                   16100:            ca[0]= k+'a'-1;ca[1]='\0';
                   16101:            if(itimes==1){
                   16102:              if(mle>=1)
                   16103:                printf("#%1d%1d%d",i,j,k);
                   16104:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   16105:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   16106:            }else{
                   16107:              if(mle>=1)
                   16108:                printf("%1d%1d%d",i,j,k);
                   16109:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   16110:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   16111:            }
                   16112:            ll=0;
                   16113:            for(li=1;li <=nlstate; li++){
                   16114:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   16115:                if(lj==li) continue;
                   16116:                for(lk=1;lk<=ncovmodel;lk++){
                   16117:                  ll++;
                   16118:                  if(ll<=jj){
                   16119:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   16120:                    if(ll<jj){
                   16121:                      if(itimes==1){
                   16122:                        if(mle>=1)
                   16123:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   16124:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   16125:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   16126:                      }else{
                   16127:                        if(mle>=1)
                   16128:                          printf(" %.5e",matcov[jj][ll]); 
                   16129:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   16130:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   16131:                      }
                   16132:                    }else{
                   16133:                      if(itimes==1){
                   16134:                        if(mle>=1)
                   16135:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   16136:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   16137:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   16138:                      }else{
                   16139:                        if(mle>=1)
                   16140:                          printf(" %.7e",matcov[jj][ll]); 
                   16141:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   16142:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   16143:                      }
                   16144:                    }
                   16145:                  }
                   16146:                } /* end lk */
                   16147:              } /* end lj */
                   16148:            } /* end li */
                   16149:            if(mle>=1)
                   16150:              printf("\n");
                   16151:            fprintf(ficlog,"\n");
                   16152:            fprintf(ficres,"\n");
                   16153:            numlinepar++;
                   16154:          } /* end k*/
                   16155:        } /*end j */
1.126     brouard  16156:       } /* end i */
                   16157:     } /* end itimes */
                   16158:     
                   16159:     fflush(ficlog);
                   16160:     fflush(ficres);
1.225     brouard  16161:     while(fgets(line, MAXLINE, ficpar)) {
                   16162:       /* If line starts with a # it is a comment */
                   16163:       if (line[0] == '#') {
                   16164:        numlinepar++;
                   16165:        fputs(line,stdout);
                   16166:        fputs(line,ficparo);
                   16167:        fputs(line,ficlog);
1.299     brouard  16168:        fputs(line,ficres);
1.225     brouard  16169:        continue;
                   16170:       }else
                   16171:        break;
                   16172:     }
                   16173:     
1.209     brouard  16174:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   16175:     /*   ungetc(c,ficpar); */
                   16176:     /*   fgets(line, MAXLINE, ficpar); */
                   16177:     /*   fputs(line,stdout); */
                   16178:     /*   fputs(line,ficparo); */
                   16179:     /* } */
                   16180:     /* ungetc(c,ficpar); */
1.126     brouard  16181:     
                   16182:     estepm=0;
1.209     brouard  16183:     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  16184:       
                   16185:       if (num_filled != 6) {
                   16186:        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);
                   16187:        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);
                   16188:        goto end;
                   16189:       }
                   16190:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   16191:     }
                   16192:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   16193:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   16194:     
1.209     brouard  16195:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  16196:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   16197:     if (fage <= 2) {
                   16198:       bage = ageminpar;
                   16199:       fage = agemaxpar;
                   16200:     }
                   16201:     
                   16202:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  16203:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   16204:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  16205:                
1.186     brouard  16206:     /* Other stuffs, more or less useful */    
1.254     brouard  16207:     while(fgets(line, MAXLINE, ficpar)) {
                   16208:       /* If line starts with a # it is a comment */
                   16209:       if (line[0] == '#') {
                   16210:        numlinepar++;
                   16211:        fputs(line,stdout);
                   16212:        fputs(line,ficparo);
                   16213:        fputs(line,ficlog);
1.299     brouard  16214:        fputs(line,ficres);
1.254     brouard  16215:        continue;
                   16216:       }else
                   16217:        break;
                   16218:     }
                   16219: 
                   16220:     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){
                   16221:       
                   16222:       if (num_filled != 7) {
                   16223:        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);
                   16224:        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);
                   16225:        goto end;
                   16226:       }
                   16227:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   16228:       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);
                   16229:       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);
                   16230:       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  16231:     }
1.254     brouard  16232: 
                   16233:     while(fgets(line, MAXLINE, ficpar)) {
                   16234:       /* If line starts with a # it is a comment */
                   16235:       if (line[0] == '#') {
                   16236:        numlinepar++;
                   16237:        fputs(line,stdout);
                   16238:        fputs(line,ficparo);
                   16239:        fputs(line,ficlog);
1.299     brouard  16240:        fputs(line,ficres);
1.254     brouard  16241:        continue;
                   16242:       }else
                   16243:        break;
1.126     brouard  16244:     }
                   16245:     
                   16246:     
                   16247:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   16248:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   16249:     
1.254     brouard  16250:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   16251:       if (num_filled != 1) {
                   16252:        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);
                   16253:        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);
                   16254:        goto end;
                   16255:       }
                   16256:       printf("pop_based=%d\n",popbased);
                   16257:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   16258:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   16259:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   16260:     }
                   16261:      
1.258     brouard  16262:     /* Results */
1.359     brouard  16263:     /* Value of covariate in each resultine will be computed (if product) and sorted according to model rank */
1.332     brouard  16264:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   16265:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  16266:     endishere=0;
1.258     brouard  16267:     nresult=0;
1.308     brouard  16268:     parameterline=0;
1.258     brouard  16269:     do{
                   16270:       if(!fgets(line, MAXLINE, ficpar)){
                   16271:        endishere=1;
1.308     brouard  16272:        parameterline=15;
1.258     brouard  16273:       }else if (line[0] == '#') {
                   16274:        /* If line starts with a # it is a comment */
1.254     brouard  16275:        numlinepar++;
                   16276:        fputs(line,stdout);
                   16277:        fputs(line,ficparo);
                   16278:        fputs(line,ficlog);
1.299     brouard  16279:        fputs(line,ficres);
1.254     brouard  16280:        continue;
1.258     brouard  16281:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   16282:        parameterline=11;
1.296     brouard  16283:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  16284:        parameterline=12;
1.307     brouard  16285:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  16286:        parameterline=13;
1.307     brouard  16287:       }
1.258     brouard  16288:       else{
                   16289:        parameterline=14;
1.254     brouard  16290:       }
1.308     brouard  16291:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  16292:       case 11:
1.296     brouard  16293:        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)){
                   16294:                  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  16295:          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);
                   16296:          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);
                   16297:          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);
                   16298:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  16299:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   16300:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  16301:           prvforecast = 1;
                   16302:        } 
                   16303:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  16304:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   16305:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   16306:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  16307:           prvforecast = 2;
                   16308:        }
                   16309:        else {
                   16310:          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);
                   16311:          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);
                   16312:          goto end;
1.258     brouard  16313:        }
1.254     brouard  16314:        break;
1.258     brouard  16315:       case 12:
1.296     brouard  16316:        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)){
                   16317:           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);
                   16318:          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);
                   16319:          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);
                   16320:          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);
                   16321:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  16322:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   16323:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  16324:           prvbackcast = 1;
                   16325:        } 
                   16326:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  16327:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   16328:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   16329:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  16330:           prvbackcast = 2;
                   16331:        }
                   16332:        else {
                   16333:          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);
                   16334:          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);
                   16335:          goto end;
1.258     brouard  16336:        }
1.230     brouard  16337:        break;
1.258     brouard  16338:       case 13:
1.332     brouard  16339:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  16340:        nresult++; /* Sum of resultlines */
1.342     brouard  16341:        /* printf("Result %d: result:%s\n",nresult, resultlineori); */
1.332     brouard  16342:        /* removefirstspace(&resultlineori); */
                   16343:        
                   16344:        if(strstr(resultlineori,"v") !=0){
                   16345:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   16346:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   16347:          return 1;
                   16348:        }
                   16349:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
1.342     brouard  16350:        /* printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori); */
1.318     brouard  16351:        if(nresult > MAXRESULTLINESPONE-1){
                   16352:          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);
                   16353:          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  16354:          goto end;
                   16355:        }
1.332     brouard  16356:        
1.310     brouard  16357:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  16358:          fprintf(ficparo,"result: %s\n",resultline);
                   16359:          fprintf(ficres,"result: %s\n",resultline);
                   16360:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  16361:        } else
                   16362:          goto end;
1.307     brouard  16363:        break;
                   16364:       case 14:
                   16365:        printf("Error: Unknown command '%s'\n",line);
                   16366:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  16367:        if(line[0] == ' ' || line[0] == '\n'){
                   16368:          printf("It should not be an empty line '%s'\n",line);
                   16369:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   16370:        }         
1.307     brouard  16371:        if(ncovmodel >=2 && nresult==0 ){
                   16372:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   16373:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  16374:        }
1.307     brouard  16375:        /* goto end; */
                   16376:        break;
1.308     brouard  16377:       case 15:
                   16378:        printf("End of resultlines.\n");
                   16379:        fprintf(ficlog,"End of resultlines.\n");
                   16380:        break;
                   16381:       default: /* parameterline =0 */
1.307     brouard  16382:        nresult=1;
                   16383:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  16384:       } /* End switch parameterline */
                   16385:     }while(endishere==0); /* End do */
1.126     brouard  16386:     
1.230     brouard  16387:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  16388:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  16389:     
                   16390:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  16391:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  16392:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  16393: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   16394: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  16395:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  16396: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   16397: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  16398:     }else{
1.270     brouard  16399:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  16400:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   16401:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   16402:       if(prvforecast==1){
                   16403:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   16404:         jprojd=jproj1;
                   16405:         mprojd=mproj1;
                   16406:         anprojd=anproj1;
                   16407:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   16408:         jprojf=jproj2;
                   16409:         mprojf=mproj2;
                   16410:         anprojf=anproj2;
                   16411:       } else if(prvforecast == 2){
                   16412:         dateprojd=dateintmean;
                   16413:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   16414:         dateprojf=dateintmean+yrfproj;
                   16415:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   16416:       }
                   16417:       if(prvbackcast==1){
                   16418:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   16419:         jbackd=jback1;
                   16420:         mbackd=mback1;
                   16421:         anbackd=anback1;
                   16422:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   16423:         jbackf=jback2;
                   16424:         mbackf=mback2;
                   16425:         anbackf=anback2;
                   16426:       } else if(prvbackcast == 2){
                   16427:         datebackd=dateintmean;
                   16428:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   16429:         datebackf=dateintmean-yrbproj;
                   16430:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   16431:       }
                   16432:       
1.350     brouard  16433:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);/* HERE valgrind Tvard*/
1.220     brouard  16434:     }
                   16435:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  16436:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   16437:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  16438:                
1.225     brouard  16439:     /*------------ free_vector  -------------*/
                   16440:     /*  chdir(path); */
1.220     brouard  16441:                
1.215     brouard  16442:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   16443:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   16444:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   16445:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  16446:     free_lvector(num,firstobs,lastobs);
                   16447:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  16448:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   16449:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   16450:     fclose(ficparo);
                   16451:     fclose(ficres);
1.220     brouard  16452:                
                   16453:                
1.186     brouard  16454:     /* Other results (useful)*/
1.220     brouard  16455:                
                   16456:                
1.126     brouard  16457:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  16458:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   16459:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  16460:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  16461:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  16462:     fclose(ficrespl);
                   16463: 
                   16464:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  16465:     /*#include "hpijx.h"*/
1.332     brouard  16466:     /** 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?*/
                   16467:     /* calls hpxij with combination k */
1.180     brouard  16468:     hPijx(p, bage, fage);
1.145     brouard  16469:     fclose(ficrespij);
1.227     brouard  16470:     
1.220     brouard  16471:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  16472:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  16473:     k=1;
1.126     brouard  16474:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  16475:     
1.269     brouard  16476:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   16477:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   16478:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  16479:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  16480:        for(k=1;k<=ncovcombmax;k++)
                   16481:          probs[i][j][k]=0.;
1.269     brouard  16482:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   16483:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  16484:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  16485:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   16486:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  16487:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  16488:          for(k=1;k<=ncovcombmax;k++)
                   16489:            mobaverages[i][j][k]=0.;
1.219     brouard  16490:       mobaverage=mobaverages;
                   16491:       if (mobilav!=0) {
1.235     brouard  16492:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  16493:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  16494:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   16495:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   16496:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   16497:        }
1.269     brouard  16498:       } else if (mobilavproj !=0) {
1.235     brouard  16499:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  16500:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  16501:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   16502:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   16503:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   16504:        }
1.269     brouard  16505:       }else{
                   16506:        printf("Internal error moving average\n");
                   16507:        fflush(stdout);
                   16508:        exit(1);
1.219     brouard  16509:       }
                   16510:     }/* end if moving average */
1.227     brouard  16511:     
1.126     brouard  16512:     /*---------- Forecasting ------------------*/
1.296     brouard  16513:     if(prevfcast==1){ 
                   16514:       /*   /\*    if(stepm ==1){*\/ */
                   16515:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   16516:       /*This done previously after freqsummary.*/
                   16517:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   16518:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   16519:       
                   16520:       /* } else if (prvforecast==2){ */
                   16521:       /*   /\*    if(stepm ==1){*\/ */
                   16522:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   16523:       /* } */
                   16524:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   16525:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  16526:     }
1.269     brouard  16527: 
1.296     brouard  16528:     /* Prevbcasting */
                   16529:     if(prevbcast==1){
1.219     brouard  16530:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   16531:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   16532:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   16533: 
                   16534:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   16535: 
                   16536:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  16537: 
1.219     brouard  16538:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   16539:       fclose(ficresplb);
                   16540: 
1.222     brouard  16541:       hBijx(p, bage, fage, mobaverage);
                   16542:       fclose(ficrespijb);
1.219     brouard  16543: 
1.296     brouard  16544:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   16545:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   16546:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   16547:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   16548:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   16549:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   16550: 
                   16551:       
1.269     brouard  16552:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  16553: 
                   16554:       
1.269     brouard  16555:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  16556:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   16557:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   16558:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  16559:     }    /* end  Prevbcasting */
1.268     brouard  16560:  
1.186     brouard  16561:  
                   16562:     /* ------ Other prevalence ratios------------ */
1.126     brouard  16563: 
1.215     brouard  16564:     free_ivector(wav,1,imx);
                   16565:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   16566:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   16567:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  16568:                
                   16569:                
1.127     brouard  16570:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  16571:                
1.201     brouard  16572:     strcpy(filerese,"E_");
                   16573:     strcat(filerese,fileresu);
1.126     brouard  16574:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   16575:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   16576:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   16577:     }
1.208     brouard  16578:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   16579:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  16580: 
                   16581:     pstamp(ficreseij);
1.219     brouard  16582:                
1.351     brouard  16583:     /* i1=pow(2,cptcoveff); /\* Number of combination of dummy covariates *\/ */
                   16584:     /* if (cptcovn < 1){i1=1;} */
1.235     brouard  16585:     
1.351     brouard  16586:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   16587:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   16588:       /* if(i1 != 1 && TKresult[nres]!= k) */
                   16589:       /*       continue; */
1.219     brouard  16590:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  16591:       printf("\n#****** ");
1.351     brouard  16592:       for(j=1;j<=cptcovs;j++){
                   16593:       /* for(j=1;j<=cptcoveff;j++) { */
                   16594:        /* fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16595:        fprintf(ficreseij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   16596:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   16597:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.235     brouard  16598:       }
                   16599:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.337     brouard  16600:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   16601:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  16602:       }
                   16603:       fprintf(ficreseij,"******\n");
1.235     brouard  16604:       printf("******\n");
1.219     brouard  16605:       
                   16606:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   16607:       oldm=oldms;savm=savms;
1.330     brouard  16608:       /* 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  16609:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  16610:       
1.219     brouard  16611:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  16612:     }
                   16613:     fclose(ficreseij);
1.208     brouard  16614:     printf("done evsij\n");fflush(stdout);
                   16615:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  16616: 
1.218     brouard  16617:                
1.227     brouard  16618:     /*---------- State-specific expectancies and variances ------------*/
1.336     brouard  16619:     /* Should be moved in a function */                
1.201     brouard  16620:     strcpy(filerest,"T_");
                   16621:     strcat(filerest,fileresu);
1.127     brouard  16622:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   16623:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   16624:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   16625:     }
1.208     brouard  16626:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   16627:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  16628:     strcpy(fileresstde,"STDE_");
                   16629:     strcat(fileresstde,fileresu);
1.126     brouard  16630:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  16631:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   16632:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  16633:     }
1.227     brouard  16634:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   16635:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  16636: 
1.201     brouard  16637:     strcpy(filerescve,"CVE_");
                   16638:     strcat(filerescve,fileresu);
1.126     brouard  16639:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  16640:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   16641:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  16642:     }
1.227     brouard  16643:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   16644:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  16645: 
1.201     brouard  16646:     strcpy(fileresv,"V_");
                   16647:     strcat(fileresv,fileresu);
1.126     brouard  16648:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   16649:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   16650:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   16651:     }
1.227     brouard  16652:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   16653:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  16654: 
1.235     brouard  16655:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   16656:     if (cptcovn < 1){i1=1;}
                   16657:     
1.334     brouard  16658:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   16659:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   16660:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   16661:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   16662:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   16663:       /* */
                   16664:       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  16665:        continue;
1.359     brouard  16666:       printf("\n# model=1+age+%s \n#****** Result for:", model);  /* HERE model is empty */
                   16667:       fprintf(ficrest,"\n# model=1+age+%s \n#****** Result for:", model);
                   16668:       fprintf(ficlog,"\n# model=1+age+%s \n#****** Result for:", model);
1.334     brouard  16669:       /* It might not be a good idea to mix dummies and quantitative */
                   16670:       /* 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 *\/ */
                   16671:       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 */
                   16672:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   16673:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   16674:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   16675:         * (V5 is quanti) V4 and V3 are dummies
                   16676:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   16677:         *                                                              l=1 l=2
                   16678:         *                                                           k=1  1   1   0   0
                   16679:         *                                                           k=2  2   1   1   0
                   16680:         *                                                           k=3 [1] [2]  0   1
                   16681:         *                                                           k=4  2   2   1   1
                   16682:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   16683:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   16684:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   16685:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   16686:         */
                   16687:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   16688:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   16689: /* We give up with the combinations!! */
1.342     brouard  16690:        /* if(debugILK) */
                   16691:        /*   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  16692: 
                   16693:        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  16694:          /* 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] */
                   16695:          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  */
                   16696:          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  */
                   16697:          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  16698:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   16699:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   16700:          }else{
                   16701:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   16702:          }
                   16703:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16704:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16705:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   16706:          /* For each selected (single) quantitative value */
1.337     brouard  16707:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   16708:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   16709:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
1.334     brouard  16710:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   16711:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   16712:          }else{
                   16713:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   16714:          }
                   16715:        }else{
                   16716:          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 */
                   16717:          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 */
                   16718:          exit(1);
                   16719:        }
1.335     brouard  16720:       } /* End loop for each variable in the resultline */
1.334     brouard  16721:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   16722:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   16723:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   16724:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   16725:       /* }      */
1.208     brouard  16726:       fprintf(ficrest,"******\n");
1.227     brouard  16727:       fprintf(ficlog,"******\n");
                   16728:       printf("******\n");
1.208     brouard  16729:       
                   16730:       fprintf(ficresstdeij,"\n#****** ");
                   16731:       fprintf(ficrescveij,"\n#****** ");
1.337     brouard  16732:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
                   16733:       /* But it won't be sorted and depends on how the resultline is ordered */
1.225     brouard  16734:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  16735:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   16736:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16737:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16738:       }
                   16739:       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  16740:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   16741:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  16742:       }        
1.208     brouard  16743:       fprintf(ficresstdeij,"******\n");
                   16744:       fprintf(ficrescveij,"******\n");
                   16745:       
                   16746:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  16747:       /* pstamp(ficresvij); */
1.225     brouard  16748:       for(j=1;j<=cptcoveff;j++) 
1.335     brouard  16749:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   16750:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  16751:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  16752:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
1.337     brouard  16753:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  16754:       }        
1.208     brouard  16755:       fprintf(ficresvij,"******\n");
                   16756:       
                   16757:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   16758:       oldm=oldms;savm=savms;
1.235     brouard  16759:       printf(" cvevsij ");
                   16760:       fprintf(ficlog, " cvevsij ");
                   16761:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  16762:       printf(" end cvevsij \n ");
                   16763:       fprintf(ficlog, " end cvevsij \n ");
                   16764:       
                   16765:       /*
                   16766:        */
                   16767:       /* goto endfree; */
                   16768:       
                   16769:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   16770:       pstamp(ficrest);
                   16771:       
1.269     brouard  16772:       epj=vector(1,nlstate+1);
1.208     brouard  16773:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  16774:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   16775:        cptcod= 0; /* To be deleted */
1.360   ! brouard  16776:        printf("varevsij vpopbased=%d popbased=%d \n",vpopbased,popbased);
        !          16777:        fprintf(ficlog, "varevsij vpopbased=%d popbased=%d \n",vpopbased,popbased);
1.235     brouard  16778:        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  16779:        fprintf(ficrest,"# Total life expectancy with std error and decomposition into time to be expected in each state\n\
        !          16780: #  (these are weighted average of eij where weights are ");
1.227     brouard  16781:        if(vpopbased==1)
1.360   ! brouard  16782:          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  16783:        else
1.360   ! brouard  16784:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each state) \n");
        !          16785:        fprintf(ficrest,"# with proportions of time spent in each state with standard error (on the right of the table.\n ");
1.335     brouard  16786:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  16787:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
1.360   ! brouard  16788:        for (i=1;i<=nlstate;i++) fprintf(ficrest," %% e.%d/e.. (std) ",i);
1.227     brouard  16789:        fprintf(ficrest,"\n");
                   16790:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  16791:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   16792:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  16793:        for(age=bage; age <=fage ;age++){
1.235     brouard  16794:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  16795:          if (vpopbased==1) {
                   16796:            if(mobilav ==0){
                   16797:              for(i=1; i<=nlstate;i++)
                   16798:                prlim[i][i]=probs[(int)age][i][k];
                   16799:            }else{ /* mobilav */ 
                   16800:              for(i=1; i<=nlstate;i++)
                   16801:                prlim[i][i]=mobaverage[(int)age][i][k];
                   16802:            }
                   16803:          }
1.219     brouard  16804:          
1.227     brouard  16805:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   16806:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   16807:          /* printf(" age %4.0f ",age); */
                   16808:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   16809:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   16810:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   16811:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   16812:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   16813:            }
                   16814:            epj[nlstate+1] +=epj[j];
                   16815:          }
                   16816:          /* printf(" age %4.0f \n",age); */
1.219     brouard  16817:          
1.227     brouard  16818:          for(i=1, vepp=0.;i <=nlstate;i++)
                   16819:            for(j=1;j <=nlstate;j++)
                   16820:              vepp += vareij[i][j][(int)age];
                   16821:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
1.360   ! brouard  16822:          /* vareij[j][i] is the variance of epj */
1.227     brouard  16823:          for(j=1;j <=nlstate;j++){
                   16824:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   16825:          }
1.360   ! brouard  16826:          /* And proportion of time spent in state j */
        !          16827:          /* $$ 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}]$$ */
        !          16828:          /* \sigma^2_x/\mu_y^2 +\sigma^2_y \mu^2x/\mu_y^4 */
        !          16829:          /*\mu_x = epj[j], \sigma^2_x = vareij[j][j][(int)age] and \mu_y=epj[nlstate+1], \sigma^2_y=vepp */
        !          16830:          /* vareij[j][j][(int)age]/epj[nlstate+1]^2 + vepp/epj[nlstata+1]^4 */
        !          16831:          for(j=1;j <=nlstate;j++){
        !          16832:            /* 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] )); */
        !          16833:            fprintf(ficrest," %7.3f (%7.3f)", epj[j]/epj[nlstate+1], sqrt( vareij[j][j][(int)age]/epj[nlstate+1]/epj[nlstate+1] + vepp/epj[nlstate+1]/epj[nlstate+1]/epj[nlstate+1]/epj[nlstate+1] ));
        !          16834:          }
1.227     brouard  16835:          fprintf(ficrest,"\n");
                   16836:        }
1.208     brouard  16837:       } /* End vpopbased */
1.269     brouard  16838:       free_vector(epj,1,nlstate+1);
1.208     brouard  16839:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   16840:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  16841:       printf("done selection\n");fflush(stdout);
                   16842:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  16843:       
1.335     brouard  16844:     } /* End k selection or end covariate selection for nres */
1.227     brouard  16845: 
                   16846:     printf("done State-specific expectancies\n");fflush(stdout);
                   16847:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   16848: 
1.335     brouard  16849:     /* variance-covariance of forward period prevalence */
1.269     brouard  16850:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  16851: 
1.227     brouard  16852:     
1.290     brouard  16853:     free_vector(weight,firstobs,lastobs);
1.351     brouard  16854:     free_imatrix(Tvardk,0,NCOVMAX,1,2);
1.227     brouard  16855:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  16856:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   16857:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   16858:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   16859:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  16860:     free_ivector(tab,1,NCOVMAX);
                   16861:     fclose(ficresstdeij);
                   16862:     fclose(ficrescveij);
                   16863:     fclose(ficresvij);
                   16864:     fclose(ficrest);
                   16865:     fclose(ficpar);
                   16866:     
                   16867:     
1.126     brouard  16868:     /*---------- End : free ----------------*/
1.219     brouard  16869:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  16870:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   16871:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  16872:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   16873:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  16874:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  16875:   /* endfree:*/
1.359     brouard  16876:   if(mle!=-3) free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
1.227     brouard  16877:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   16878:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   16879:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.341     brouard  16880:   /* if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs); */
                   16881:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);
1.290     brouard  16882:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   16883:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   16884:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  16885:   free_matrix(matcov,1,npar,1,npar);
                   16886:   free_matrix(hess,1,npar,1,npar);
                   16887:   /*free_vector(delti,1,npar);*/
                   16888:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   16889:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  16890:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  16891:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   16892:   
                   16893:   free_ivector(ncodemax,1,NCOVMAX);
                   16894:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   16895:   free_ivector(Dummy,-1,NCOVMAX);
                   16896:   free_ivector(Fixed,-1,NCOVMAX);
1.349     brouard  16897:   free_ivector(DummyV,-1,NCOVMAX);
                   16898:   free_ivector(FixedV,-1,NCOVMAX);
1.227     brouard  16899:   free_ivector(Typevar,-1,NCOVMAX);
                   16900:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  16901:   free_ivector(TvarsQ,1,NCOVMAX);
                   16902:   free_ivector(TvarsQind,1,NCOVMAX);
                   16903:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  16904:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  16905:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  16906:   free_ivector(TvarFD,1,NCOVMAX);
                   16907:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  16908:   free_ivector(TvarF,1,NCOVMAX);
                   16909:   free_ivector(TvarFind,1,NCOVMAX);
                   16910:   free_ivector(TvarV,1,NCOVMAX);
                   16911:   free_ivector(TvarVind,1,NCOVMAX);
                   16912:   free_ivector(TvarA,1,NCOVMAX);
                   16913:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  16914:   free_ivector(TvarFQ,1,NCOVMAX);
                   16915:   free_ivector(TvarFQind,1,NCOVMAX);
                   16916:   free_ivector(TvarVD,1,NCOVMAX);
                   16917:   free_ivector(TvarVDind,1,NCOVMAX);
                   16918:   free_ivector(TvarVQ,1,NCOVMAX);
                   16919:   free_ivector(TvarVQind,1,NCOVMAX);
1.349     brouard  16920:   free_ivector(TvarAVVA,1,NCOVMAX);
                   16921:   free_ivector(TvarAVVAind,1,NCOVMAX);
                   16922:   free_ivector(TvarVVA,1,NCOVMAX);
                   16923:   free_ivector(TvarVVAind,1,NCOVMAX);
1.339     brouard  16924:   free_ivector(TvarVV,1,NCOVMAX);
                   16925:   free_ivector(TvarVVind,1,NCOVMAX);
                   16926:   
1.230     brouard  16927:   free_ivector(Tvarsel,1,NCOVMAX);
                   16928:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  16929:   free_ivector(Tposprod,1,NCOVMAX);
                   16930:   free_ivector(Tprod,1,NCOVMAX);
                   16931:   free_ivector(Tvaraff,1,NCOVMAX);
1.338     brouard  16932:   free_ivector(invalidvarcomb,0,ncovcombmax);
1.227     brouard  16933:   free_ivector(Tage,1,NCOVMAX);
                   16934:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  16935:   free_ivector(TmodelInvind,1,NCOVMAX);
                   16936:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  16937: 
1.359     brouard  16938:   /* free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /\* Could be elsewhere ?*\/ */
1.332     brouard  16939: 
1.227     brouard  16940:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   16941:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  16942:   fflush(fichtm);
                   16943:   fflush(ficgp);
                   16944:   
1.227     brouard  16945:   
1.126     brouard  16946:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  16947:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   16948:     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  16949:   }else{
                   16950:     printf("End of Imach\n");
                   16951:     fprintf(ficlog,"End of Imach\n");
                   16952:   }
                   16953:   printf("See log file on %s\n",filelog);
                   16954:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  16955:   /*(void) gettimeofday(&end_time,&tzp);*/
                   16956:   rend_time = time(NULL);  
                   16957:   end_time = *localtime(&rend_time);
                   16958:   /* tml = *localtime(&end_time.tm_sec); */
                   16959:   strcpy(strtend,asctime(&end_time));
1.126     brouard  16960:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   16961:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  16962:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  16963:   
1.157     brouard  16964:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   16965:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   16966:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  16967:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   16968: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   16969:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   16970:   fclose(fichtm);
                   16971:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   16972:   fclose(fichtmcov);
                   16973:   fclose(ficgp);
                   16974:   fclose(ficlog);
                   16975:   /*------ End -----------*/
1.227     brouard  16976:   
1.281     brouard  16977: 
                   16978: /* Executes gnuplot */
1.227     brouard  16979:   
                   16980:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  16981: #ifdef WIN32
1.227     brouard  16982:   if (_chdir(pathcd) != 0)
                   16983:     printf("Can't move to directory %s!\n",path);
                   16984:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  16985: #else
1.227     brouard  16986:     if(chdir(pathcd) != 0)
                   16987:       printf("Can't move to directory %s!\n", path);
                   16988:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  16989: #endif 
1.126     brouard  16990:     printf("Current directory %s!\n",pathcd);
                   16991:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   16992:   sprintf(plotcmd,"gnuplot");
1.157     brouard  16993: #ifdef _WIN32
1.126     brouard  16994:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   16995: #endif
                   16996:   if(!stat(plotcmd,&info)){
1.158     brouard  16997:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  16998:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  16999:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  17000:     }else
                   17001:       strcpy(pplotcmd,plotcmd);
1.157     brouard  17002: #ifdef __unix
1.126     brouard  17003:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   17004:     if(!stat(plotcmd,&info)){
1.158     brouard  17005:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  17006:     }else
                   17007:       strcpy(pplotcmd,plotcmd);
                   17008: #endif
                   17009:   }else
                   17010:     strcpy(pplotcmd,plotcmd);
                   17011:   
                   17012:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  17013:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  17014:   strcpy(pplotcmd,plotcmd);
1.227     brouard  17015:   
1.126     brouard  17016:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  17017:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  17018:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  17019:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  17020:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  17021:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  17022:       strcpy(plotcmd,pplotcmd);
                   17023:     }
1.126     brouard  17024:   }
1.158     brouard  17025:   printf(" Successful, please wait...");
1.126     brouard  17026:   while (z[0] != 'q') {
                   17027:     /* chdir(path); */
1.154     brouard  17028:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  17029:     scanf("%s",z);
                   17030: /*     if (z[0] == 'c') system("./imach"); */
                   17031:     if (z[0] == 'e') {
1.158     brouard  17032: #ifdef __APPLE__
1.152     brouard  17033:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  17034: #elif __linux
                   17035:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  17036: #else
1.152     brouard  17037:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  17038: #endif
                   17039:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   17040:       system(pplotcmd);
1.126     brouard  17041:     }
                   17042:     else if (z[0] == 'g') system(plotcmd);
                   17043:     else if (z[0] == 'q') exit(0);
                   17044:   }
1.227     brouard  17045: end:
1.126     brouard  17046:   while (z[0] != 'q') {
1.195     brouard  17047:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  17048:     scanf("%s",z);
                   17049:   }
1.283     brouard  17050:   printf("End\n");
1.282     brouard  17051:   exit(0);
1.126     brouard  17052: }

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