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

1.354   ! brouard     1: /* $Id: imach.c,v 1.353 2023/05/08 18:48:22 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.354   ! brouard     4:   Revision 1.353  2023/05/08 18:48:22  brouard
        !             5:   *** empty log message ***
        !             6: 
1.353     brouard     7:   Revision 1.352  2023/04/29 10:46:21  brouard
                      8:   *** empty log message ***
                      9: 
1.352     brouard    10:   Revision 1.351  2023/04/29 10:43:47  brouard
                     11:   Summary: 099r45
                     12: 
1.351     brouard    13:   Revision 1.350  2023/04/24 11:38:06  brouard
                     14:   *** empty log message ***
                     15: 
1.350     brouard    16:   Revision 1.349  2023/01/31 09:19:37  brouard
                     17:   Summary: Improvements in models with age*Vn*Vm
                     18: 
1.348     brouard    19:   Revision 1.347  2022/09/18 14:36:44  brouard
                     20:   Summary: version 0.99r42
                     21: 
1.347     brouard    22:   Revision 1.346  2022/09/16 13:52:36  brouard
                     23:   * src/imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     24: 
1.346     brouard    25:   Revision 1.345  2022/09/16 13:40:11  brouard
                     26:   Summary: Version 0.99r41
                     27: 
                     28:   * imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     29: 
1.345     brouard    30:   Revision 1.344  2022/09/14 19:33:30  brouard
                     31:   Summary: version 0.99r40
                     32: 
                     33:   * imach.c (Module): Fixing names of variables in T_ (thanks to Feinuo)
                     34: 
1.344     brouard    35:   Revision 1.343  2022/09/14 14:22:16  brouard
                     36:   Summary: version 0.99r39
                     37: 
                     38:   * imach.c (Module): Version 0.99r39 with colored dummy covariates
                     39:   (fixed or time varying), using new last columns of
                     40:   ILK_parameter.txt file.
                     41: 
1.343     brouard    42:   Revision 1.342  2022/09/11 19:54:09  brouard
                     43:   Summary: 0.99r38
                     44: 
                     45:   * imach.c (Module): Adding timevarying products of any kinds,
                     46:   should work before shifting cotvar from ncovcol+nqv columns in
                     47:   order to have a correspondance between the column of cotvar and
                     48:   the id of column.
                     49:   (Module): Some cleaning and adding covariates in ILK.txt
                     50: 
1.342     brouard    51:   Revision 1.341  2022/09/11 07:58:42  brouard
                     52:   Summary: Version 0.99r38
                     53: 
                     54:   After adding change in cotvar.
                     55: 
1.341     brouard    56:   Revision 1.340  2022/09/11 07:53:11  brouard
                     57:   Summary: Version imach 0.99r37
                     58: 
                     59:   * imach.c (Module): Adding timevarying products of any kinds,
                     60:   should work before shifting cotvar from ncovcol+nqv columns in
                     61:   order to have a correspondance between the column of cotvar and
                     62:   the id of column.
                     63: 
1.340     brouard    64:   Revision 1.339  2022/09/09 17:55:22  brouard
                     65:   Summary: version 0.99r37
                     66: 
                     67:   * imach.c (Module): Many improvements for fixing products of fixed
                     68:   timevarying as well as fixed * fixed, and test with quantitative
                     69:   covariate.
                     70: 
1.339     brouard    71:   Revision 1.338  2022/09/04 17:40:33  brouard
                     72:   Summary: 0.99r36
                     73: 
                     74:   * imach.c (Module): Now the easy runs i.e. without result or
                     75:   model=1+age only did not work. The defautl combination should be 1
                     76:   and not 0 because everything hasn't been tranformed yet.
                     77: 
1.338     brouard    78:   Revision 1.337  2022/09/02 14:26:02  brouard
                     79:   Summary: version 0.99r35
                     80: 
                     81:   * src/imach.c: Version 0.99r35 because it outputs same results with
                     82:   1+age+V1+V1*age for females and 1+age for females only
                     83:   (education=1 noweight)
                     84: 
1.337     brouard    85:   Revision 1.336  2022/08/31 09:52:36  brouard
                     86:   *** empty log message ***
                     87: 
1.336     brouard    88:   Revision 1.335  2022/08/31 08:23:16  brouard
                     89:   Summary: improvements...
                     90: 
1.335     brouard    91:   Revision 1.334  2022/08/25 09:08:41  brouard
                     92:   Summary: In progress for quantitative
                     93: 
1.334     brouard    94:   Revision 1.333  2022/08/21 09:10:30  brouard
                     95:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     96:   reassigning covariates: my first idea was that people will always
                     97:   use the first covariate V1 into the model but in fact they are
                     98:   producing data with many covariates and can use an equation model
                     99:   with some of the covariate; it means that in a model V2+V3 instead
                    100:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    101:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    102:   the equation model is restricted to two variables only (V2, V3)
                    103:   and the combination for V2 should be codtabm(k,1) instead of
                    104:   (codtabm(k,2), and the code should be
                    105:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    106:   made. All of these should be simplified once a day like we did in
                    107:   hpxij() for example by using precov[nres] which is computed in
                    108:   decoderesult for each nres of each resultline. Loop should be done
                    109:   on the equation model globally by distinguishing only product with
                    110:   age (which are changing with age) and no more on type of
                    111:   covariates, single dummies, single covariates.
                    112: 
1.333     brouard   113:   Revision 1.332  2022/08/21 09:06:25  brouard
                    114:   Summary: Version 0.99r33
                    115: 
                    116:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                    117:   reassigning covariates: my first idea was that people will always
                    118:   use the first covariate V1 into the model but in fact they are
                    119:   producing data with many covariates and can use an equation model
                    120:   with some of the covariate; it means that in a model V2+V3 instead
                    121:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    122:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    123:   the equation model is restricted to two variables only (V2, V3)
                    124:   and the combination for V2 should be codtabm(k,1) instead of
                    125:   (codtabm(k,2), and the code should be
                    126:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    127:   made. All of these should be simplified once a day like we did in
                    128:   hpxij() for example by using precov[nres] which is computed in
                    129:   decoderesult for each nres of each resultline. Loop should be done
                    130:   on the equation model globally by distinguishing only product with
                    131:   age (which are changing with age) and no more on type of
                    132:   covariates, single dummies, single covariates.
                    133: 
1.332     brouard   134:   Revision 1.331  2022/08/07 05:40:09  brouard
                    135:   *** empty log message ***
                    136: 
1.331     brouard   137:   Revision 1.330  2022/08/06 07:18:25  brouard
                    138:   Summary: last 0.99r31
                    139: 
                    140:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                    141: 
1.330     brouard   142:   Revision 1.329  2022/08/03 17:29:54  brouard
                    143:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                    144: 
1.329     brouard   145:   Revision 1.328  2022/07/27 17:40:48  brouard
                    146:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                    147: 
1.328     brouard   148:   Revision 1.327  2022/07/27 14:47:35  brouard
                    149:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                    150: 
1.327     brouard   151:   Revision 1.326  2022/07/26 17:33:55  brouard
                    152:   Summary: some test with nres=1
                    153: 
1.326     brouard   154:   Revision 1.325  2022/07/25 14:27:23  brouard
                    155:   Summary: r30
                    156: 
                    157:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                    158:   coredumped, revealed by Feiuno, thank you.
                    159: 
1.325     brouard   160:   Revision 1.324  2022/07/23 17:44:26  brouard
                    161:   *** empty log message ***
                    162: 
1.324     brouard   163:   Revision 1.323  2022/07/22 12:30:08  brouard
                    164:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    165: 
1.323     brouard   166:   Revision 1.322  2022/07/22 12:27:48  brouard
                    167:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    168: 
1.322     brouard   169:   Revision 1.321  2022/07/22 12:04:24  brouard
                    170:   Summary: r28
                    171: 
                    172:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    173: 
1.321     brouard   174:   Revision 1.320  2022/06/02 05:10:11  brouard
                    175:   *** empty log message ***
                    176: 
1.320     brouard   177:   Revision 1.319  2022/06/02 04:45:11  brouard
                    178:   * imach.c (Module): Adding the Wald tests from the log to the main
                    179:   htm for better display of the maximum likelihood estimators.
                    180: 
1.319     brouard   181:   Revision 1.318  2022/05/24 08:10:59  brouard
                    182:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                    183:   of confidencce intervals with product in the equation modelC
                    184: 
1.318     brouard   185:   Revision 1.317  2022/05/15 15:06:23  brouard
                    186:   * imach.c (Module):  Some minor improvements
                    187: 
1.317     brouard   188:   Revision 1.316  2022/05/11 15:11:31  brouard
                    189:   Summary: r27
                    190: 
1.316     brouard   191:   Revision 1.315  2022/05/11 15:06:32  brouard
                    192:   *** empty log message ***
                    193: 
1.315     brouard   194:   Revision 1.314  2022/04/13 17:43:09  brouard
                    195:   * imach.c (Module): Adding link to text data files
                    196: 
1.314     brouard   197:   Revision 1.313  2022/04/11 15:57:42  brouard
                    198:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    199: 
1.313     brouard   200:   Revision 1.312  2022/04/05 21:24:39  brouard
                    201:   *** empty log message ***
                    202: 
1.312     brouard   203:   Revision 1.311  2022/04/05 21:03:51  brouard
                    204:   Summary: Fixed quantitative covariates
                    205: 
                    206:          Fixed covariates (dummy or quantitative)
                    207:        with missing values have never been allowed but are ERRORS and
                    208:        program quits. Standard deviations of fixed covariates were
                    209:        wrongly computed. Mean and standard deviations of time varying
                    210:        covariates are still not computed.
                    211: 
1.311     brouard   212:   Revision 1.310  2022/03/17 08:45:53  brouard
                    213:   Summary: 99r25
                    214: 
                    215:   Improving detection of errors: result lines should be compatible with
                    216:   the model.
                    217: 
1.310     brouard   218:   Revision 1.309  2021/05/20 12:39:14  brouard
                    219:   Summary: Version 0.99r24
                    220: 
1.309     brouard   221:   Revision 1.308  2021/03/31 13:11:57  brouard
                    222:   Summary: Version 0.99r23
                    223: 
                    224: 
                    225:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    226: 
1.308     brouard   227:   Revision 1.307  2021/03/08 18:11:32  brouard
                    228:   Summary: 0.99r22 fixed bug on result:
                    229: 
1.307     brouard   230:   Revision 1.306  2021/02/20 15:44:02  brouard
                    231:   Summary: Version 0.99r21
                    232: 
                    233:   * imach.c (Module): Fix bug on quitting after result lines!
                    234:   (Module): Version 0.99r21
                    235: 
1.306     brouard   236:   Revision 1.305  2021/02/20 15:28:30  brouard
                    237:   * imach.c (Module): Fix bug on quitting after result lines!
                    238: 
1.305     brouard   239:   Revision 1.304  2021/02/12 11:34:20  brouard
                    240:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    241: 
1.304     brouard   242:   Revision 1.303  2021/02/11 19:50:15  brouard
                    243:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    244: 
1.303     brouard   245:   Revision 1.302  2020/02/22 21:00:05  brouard
                    246:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    247:   and life table from the data without any state)
                    248: 
1.302     brouard   249:   Revision 1.301  2019/06/04 13:51:20  brouard
                    250:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    251: 
1.301     brouard   252:   Revision 1.300  2019/05/22 19:09:45  brouard
                    253:   Summary: version 0.99r19 of May 2019
                    254: 
1.300     brouard   255:   Revision 1.299  2019/05/22 18:37:08  brouard
                    256:   Summary: Cleaned 0.99r19
                    257: 
1.299     brouard   258:   Revision 1.298  2019/05/22 18:19:56  brouard
                    259:   *** empty log message ***
                    260: 
1.298     brouard   261:   Revision 1.297  2019/05/22 17:56:10  brouard
                    262:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    263: 
1.297     brouard   264:   Revision 1.296  2019/05/20 13:03:18  brouard
                    265:   Summary: Projection syntax simplified
                    266: 
                    267: 
                    268:   We can now start projections, forward or backward, from the mean date
                    269:   of inteviews up to or down to a number of years of projection:
                    270:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    271:   or
                    272:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    273:   or
                    274:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    275:   or
                    276:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    277: 
1.296     brouard   278:   Revision 1.295  2019/05/18 09:52:50  brouard
                    279:   Summary: doxygen tex bug
                    280: 
1.295     brouard   281:   Revision 1.294  2019/05/16 14:54:33  brouard
                    282:   Summary: There was some wrong lines added
                    283: 
1.294     brouard   284:   Revision 1.293  2019/05/09 15:17:34  brouard
                    285:   *** empty log message ***
                    286: 
1.293     brouard   287:   Revision 1.292  2019/05/09 14:17:20  brouard
                    288:   Summary: Some updates
                    289: 
1.292     brouard   290:   Revision 1.291  2019/05/09 13:44:18  brouard
                    291:   Summary: Before ncovmax
                    292: 
1.291     brouard   293:   Revision 1.290  2019/05/09 13:39:37  brouard
                    294:   Summary: 0.99r18 unlimited number of individuals
                    295: 
                    296:   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.
                    297: 
1.290     brouard   298:   Revision 1.289  2018/12/13 09:16:26  brouard
                    299:   Summary: Bug for young ages (<-30) will be in r17
                    300: 
1.289     brouard   301:   Revision 1.288  2018/05/02 20:58:27  brouard
                    302:   Summary: Some bugs fixed
                    303: 
1.288     brouard   304:   Revision 1.287  2018/05/01 17:57:25  brouard
                    305:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    306: 
1.287     brouard   307:   Revision 1.286  2018/04/27 14:27:04  brouard
                    308:   Summary: some minor bugs
                    309: 
1.286     brouard   310:   Revision 1.285  2018/04/21 21:02:16  brouard
                    311:   Summary: Some bugs fixed, valgrind tested
                    312: 
1.285     brouard   313:   Revision 1.284  2018/04/20 05:22:13  brouard
                    314:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    315: 
1.284     brouard   316:   Revision 1.283  2018/04/19 14:49:16  brouard
                    317:   Summary: Some minor bugs fixed
                    318: 
1.283     brouard   319:   Revision 1.282  2018/02/27 22:50:02  brouard
                    320:   *** empty log message ***
                    321: 
1.282     brouard   322:   Revision 1.281  2018/02/27 19:25:23  brouard
                    323:   Summary: Adding second argument for quitting
                    324: 
1.281     brouard   325:   Revision 1.280  2018/02/21 07:58:13  brouard
                    326:   Summary: 0.99r15
                    327: 
                    328:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    329: 
1.280     brouard   330:   Revision 1.279  2017/07/20 13:35:01  brouard
                    331:   Summary: temporary working
                    332: 
1.279     brouard   333:   Revision 1.278  2017/07/19 14:09:02  brouard
                    334:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    335: 
1.278     brouard   336:   Revision 1.277  2017/07/17 08:53:49  brouard
                    337:   Summary: BOM files can be read now
                    338: 
1.277     brouard   339:   Revision 1.276  2017/06/30 15:48:31  brouard
                    340:   Summary: Graphs improvements
                    341: 
1.276     brouard   342:   Revision 1.275  2017/06/30 13:39:33  brouard
                    343:   Summary: Saito's color
                    344: 
1.275     brouard   345:   Revision 1.274  2017/06/29 09:47:08  brouard
                    346:   Summary: Version 0.99r14
                    347: 
1.274     brouard   348:   Revision 1.273  2017/06/27 11:06:02  brouard
                    349:   Summary: More documentation on projections
                    350: 
1.273     brouard   351:   Revision 1.272  2017/06/27 10:22:40  brouard
                    352:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    353: 
1.272     brouard   354:   Revision 1.271  2017/06/27 10:17:50  brouard
                    355:   Summary: Some bug with rint
                    356: 
1.271     brouard   357:   Revision 1.270  2017/05/24 05:45:29  brouard
                    358:   *** empty log message ***
                    359: 
1.270     brouard   360:   Revision 1.269  2017/05/23 08:39:25  brouard
                    361:   Summary: Code into subroutine, cleanings
                    362: 
1.269     brouard   363:   Revision 1.268  2017/05/18 20:09:32  brouard
                    364:   Summary: backprojection and confidence intervals of backprevalence
                    365: 
1.268     brouard   366:   Revision 1.267  2017/05/13 10:25:05  brouard
                    367:   Summary: temporary save for backprojection
                    368: 
1.267     brouard   369:   Revision 1.266  2017/05/13 07:26:12  brouard
                    370:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    371: 
1.266     brouard   372:   Revision 1.265  2017/04/26 16:22:11  brouard
                    373:   Summary: imach 0.99r13 Some bugs fixed
                    374: 
1.265     brouard   375:   Revision 1.264  2017/04/26 06:01:29  brouard
                    376:   Summary: Labels in graphs
                    377: 
1.264     brouard   378:   Revision 1.263  2017/04/24 15:23:15  brouard
                    379:   Summary: to save
                    380: 
1.263     brouard   381:   Revision 1.262  2017/04/18 16:48:12  brouard
                    382:   *** empty log message ***
                    383: 
1.262     brouard   384:   Revision 1.261  2017/04/05 10:14:09  brouard
                    385:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    386: 
1.261     brouard   387:   Revision 1.260  2017/04/04 17:46:59  brouard
                    388:   Summary: Gnuplot indexations fixed (humm)
                    389: 
1.260     brouard   390:   Revision 1.259  2017/04/04 13:01:16  brouard
                    391:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    392: 
1.259     brouard   393:   Revision 1.258  2017/04/03 10:17:47  brouard
                    394:   Summary: Version 0.99r12
                    395: 
                    396:   Some cleanings, conformed with updated documentation.
                    397: 
1.258     brouard   398:   Revision 1.257  2017/03/29 16:53:30  brouard
                    399:   Summary: Temp
                    400: 
1.257     brouard   401:   Revision 1.256  2017/03/27 05:50:23  brouard
                    402:   Summary: Temporary
                    403: 
1.256     brouard   404:   Revision 1.255  2017/03/08 16:02:28  brouard
                    405:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    406: 
1.255     brouard   407:   Revision 1.254  2017/03/08 07:13:00  brouard
                    408:   Summary: Fixing data parameter line
                    409: 
1.254     brouard   410:   Revision 1.253  2016/12/15 11:59:41  brouard
                    411:   Summary: 0.99 in progress
                    412: 
1.253     brouard   413:   Revision 1.252  2016/09/15 21:15:37  brouard
                    414:   *** empty log message ***
                    415: 
1.252     brouard   416:   Revision 1.251  2016/09/15 15:01:13  brouard
                    417:   Summary: not working
                    418: 
1.251     brouard   419:   Revision 1.250  2016/09/08 16:07:27  brouard
                    420:   Summary: continue
                    421: 
1.250     brouard   422:   Revision 1.249  2016/09/07 17:14:18  brouard
                    423:   Summary: Starting values from frequencies
                    424: 
1.249     brouard   425:   Revision 1.248  2016/09/07 14:10:18  brouard
                    426:   *** empty log message ***
                    427: 
1.248     brouard   428:   Revision 1.247  2016/09/02 11:11:21  brouard
                    429:   *** empty log message ***
                    430: 
1.247     brouard   431:   Revision 1.246  2016/09/02 08:49:22  brouard
                    432:   *** empty log message ***
                    433: 
1.246     brouard   434:   Revision 1.245  2016/09/02 07:25:01  brouard
                    435:   *** empty log message ***
                    436: 
1.245     brouard   437:   Revision 1.244  2016/09/02 07:17:34  brouard
                    438:   *** empty log message ***
                    439: 
1.244     brouard   440:   Revision 1.243  2016/09/02 06:45:35  brouard
                    441:   *** empty log message ***
                    442: 
1.243     brouard   443:   Revision 1.242  2016/08/30 15:01:20  brouard
                    444:   Summary: Fixing a lots
                    445: 
1.242     brouard   446:   Revision 1.241  2016/08/29 17:17:25  brouard
                    447:   Summary: gnuplot problem in Back projection to fix
                    448: 
1.241     brouard   449:   Revision 1.240  2016/08/29 07:53:18  brouard
                    450:   Summary: Better
                    451: 
1.240     brouard   452:   Revision 1.239  2016/08/26 15:51:03  brouard
                    453:   Summary: Improvement in Powell output in order to copy and paste
                    454: 
                    455:   Author:
                    456: 
1.239     brouard   457:   Revision 1.238  2016/08/26 14:23:35  brouard
                    458:   Summary: Starting tests of 0.99
                    459: 
1.238     brouard   460:   Revision 1.237  2016/08/26 09:20:19  brouard
                    461:   Summary: to valgrind
                    462: 
1.237     brouard   463:   Revision 1.236  2016/08/25 10:50:18  brouard
                    464:   *** empty log message ***
                    465: 
1.236     brouard   466:   Revision 1.235  2016/08/25 06:59:23  brouard
                    467:   *** empty log message ***
                    468: 
1.235     brouard   469:   Revision 1.234  2016/08/23 16:51:20  brouard
                    470:   *** empty log message ***
                    471: 
1.234     brouard   472:   Revision 1.233  2016/08/23 07:40:50  brouard
                    473:   Summary: not working
                    474: 
1.233     brouard   475:   Revision 1.232  2016/08/22 14:20:21  brouard
                    476:   Summary: not working
                    477: 
1.232     brouard   478:   Revision 1.231  2016/08/22 07:17:15  brouard
                    479:   Summary: not working
                    480: 
1.231     brouard   481:   Revision 1.230  2016/08/22 06:55:53  brouard
                    482:   Summary: Not working
                    483: 
1.230     brouard   484:   Revision 1.229  2016/07/23 09:45:53  brouard
                    485:   Summary: Completing for func too
                    486: 
1.229     brouard   487:   Revision 1.228  2016/07/22 17:45:30  brouard
                    488:   Summary: Fixing some arrays, still debugging
                    489: 
1.227     brouard   490:   Revision 1.226  2016/07/12 18:42:34  brouard
                    491:   Summary: temp
                    492: 
1.226     brouard   493:   Revision 1.225  2016/07/12 08:40:03  brouard
                    494:   Summary: saving but not running
                    495: 
1.225     brouard   496:   Revision 1.224  2016/07/01 13:16:01  brouard
                    497:   Summary: Fixes
                    498: 
1.224     brouard   499:   Revision 1.223  2016/02/19 09:23:35  brouard
                    500:   Summary: temporary
                    501: 
1.223     brouard   502:   Revision 1.222  2016/02/17 08:14:50  brouard
                    503:   Summary: Probably last 0.98 stable version 0.98r6
                    504: 
1.222     brouard   505:   Revision 1.221  2016/02/15 23:35:36  brouard
                    506:   Summary: minor bug
                    507: 
1.220     brouard   508:   Revision 1.219  2016/02/15 00:48:12  brouard
                    509:   *** empty log message ***
                    510: 
1.219     brouard   511:   Revision 1.218  2016/02/12 11:29:23  brouard
                    512:   Summary: 0.99 Back projections
                    513: 
1.218     brouard   514:   Revision 1.217  2015/12/23 17:18:31  brouard
                    515:   Summary: Experimental backcast
                    516: 
1.217     brouard   517:   Revision 1.216  2015/12/18 17:32:11  brouard
                    518:   Summary: 0.98r4 Warning and status=-2
                    519: 
                    520:   Version 0.98r4 is now:
                    521:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    522:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    523:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    524: 
1.216     brouard   525:   Revision 1.215  2015/12/16 08:52:24  brouard
                    526:   Summary: 0.98r4 working
                    527: 
1.215     brouard   528:   Revision 1.214  2015/12/16 06:57:54  brouard
                    529:   Summary: temporary not working
                    530: 
1.214     brouard   531:   Revision 1.213  2015/12/11 18:22:17  brouard
                    532:   Summary: 0.98r4
                    533: 
1.213     brouard   534:   Revision 1.212  2015/11/21 12:47:24  brouard
                    535:   Summary: minor typo
                    536: 
1.212     brouard   537:   Revision 1.211  2015/11/21 12:41:11  brouard
                    538:   Summary: 0.98r3 with some graph of projected cross-sectional
                    539: 
                    540:   Author: Nicolas Brouard
                    541: 
1.211     brouard   542:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   543:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   544:   Summary: Adding ftolpl parameter
                    545:   Author: N Brouard
                    546: 
                    547:   We had difficulties to get smoothed confidence intervals. It was due
                    548:   to the period prevalence which wasn't computed accurately. The inner
                    549:   parameter ftolpl is now an outer parameter of the .imach parameter
                    550:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    551:   computation are long.
                    552: 
1.209     brouard   553:   Revision 1.208  2015/11/17 14:31:57  brouard
                    554:   Summary: temporary
                    555: 
1.208     brouard   556:   Revision 1.207  2015/10/27 17:36:57  brouard
                    557:   *** empty log message ***
                    558: 
1.207     brouard   559:   Revision 1.206  2015/10/24 07:14:11  brouard
                    560:   *** empty log message ***
                    561: 
1.206     brouard   562:   Revision 1.205  2015/10/23 15:50:53  brouard
                    563:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    564: 
1.205     brouard   565:   Revision 1.204  2015/10/01 16:20:26  brouard
                    566:   Summary: Some new graphs of contribution to likelihood
                    567: 
1.204     brouard   568:   Revision 1.203  2015/09/30 17:45:14  brouard
                    569:   Summary: looking at better estimation of the hessian
                    570: 
                    571:   Also a better criteria for convergence to the period prevalence And
                    572:   therefore adding the number of years needed to converge. (The
                    573:   prevalence in any alive state shold sum to one
                    574: 
1.203     brouard   575:   Revision 1.202  2015/09/22 19:45:16  brouard
                    576:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    577: 
1.202     brouard   578:   Revision 1.201  2015/09/15 17:34:58  brouard
                    579:   Summary: 0.98r0
                    580: 
                    581:   - Some new graphs like suvival functions
                    582:   - Some bugs fixed like model=1+age+V2.
                    583: 
1.201     brouard   584:   Revision 1.200  2015/09/09 16:53:55  brouard
                    585:   Summary: Big bug thanks to Flavia
                    586: 
                    587:   Even model=1+age+V2. did not work anymore
                    588: 
1.200     brouard   589:   Revision 1.199  2015/09/07 14:09:23  brouard
                    590:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    591: 
1.199     brouard   592:   Revision 1.198  2015/09/03 07:14:39  brouard
                    593:   Summary: 0.98q5 Flavia
                    594: 
1.198     brouard   595:   Revision 1.197  2015/09/01 18:24:39  brouard
                    596:   *** empty log message ***
                    597: 
1.197     brouard   598:   Revision 1.196  2015/08/18 23:17:52  brouard
                    599:   Summary: 0.98q5
                    600: 
1.196     brouard   601:   Revision 1.195  2015/08/18 16:28:39  brouard
                    602:   Summary: Adding a hack for testing purpose
                    603: 
                    604:   After reading the title, ftol and model lines, if the comment line has
                    605:   a q, starting with #q, the answer at the end of the run is quit. It
                    606:   permits to run test files in batch with ctest. The former workaround was
                    607:   $ echo q | imach foo.imach
                    608: 
1.195     brouard   609:   Revision 1.194  2015/08/18 13:32:00  brouard
                    610:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    611: 
1.194     brouard   612:   Revision 1.193  2015/08/04 07:17:42  brouard
                    613:   Summary: 0.98q4
                    614: 
1.193     brouard   615:   Revision 1.192  2015/07/16 16:49:02  brouard
                    616:   Summary: Fixing some outputs
                    617: 
1.192     brouard   618:   Revision 1.191  2015/07/14 10:00:33  brouard
                    619:   Summary: Some fixes
                    620: 
1.191     brouard   621:   Revision 1.190  2015/05/05 08:51:13  brouard
                    622:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    623: 
                    624:   Fix 1+age+.
                    625: 
1.190     brouard   626:   Revision 1.189  2015/04/30 14:45:16  brouard
                    627:   Summary: 0.98q2
                    628: 
1.189     brouard   629:   Revision 1.188  2015/04/30 08:27:53  brouard
                    630:   *** empty log message ***
                    631: 
1.188     brouard   632:   Revision 1.187  2015/04/29 09:11:15  brouard
                    633:   *** empty log message ***
                    634: 
1.187     brouard   635:   Revision 1.186  2015/04/23 12:01:52  brouard
                    636:   Summary: V1*age is working now, version 0.98q1
                    637: 
                    638:   Some codes had been disabled in order to simplify and Vn*age was
                    639:   working in the optimization phase, ie, giving correct MLE parameters,
                    640:   but, as usual, outputs were not correct and program core dumped.
                    641: 
1.186     brouard   642:   Revision 1.185  2015/03/11 13:26:42  brouard
                    643:   Summary: Inclusion of compile and links command line for Intel Compiler
                    644: 
1.185     brouard   645:   Revision 1.184  2015/03/11 11:52:39  brouard
                    646:   Summary: Back from Windows 8. Intel Compiler
                    647: 
1.184     brouard   648:   Revision 1.183  2015/03/10 20:34:32  brouard
                    649:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    650: 
                    651:   We use directest instead of original Powell test; probably no
                    652:   incidence on the results, but better justifications;
                    653:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    654:   wrong results.
                    655: 
1.183     brouard   656:   Revision 1.182  2015/02/12 08:19:57  brouard
                    657:   Summary: Trying to keep directest which seems simpler and more general
                    658:   Author: Nicolas Brouard
                    659: 
1.182     brouard   660:   Revision 1.181  2015/02/11 23:22:24  brouard
                    661:   Summary: Comments on Powell added
                    662: 
                    663:   Author:
                    664: 
1.181     brouard   665:   Revision 1.180  2015/02/11 17:33:45  brouard
                    666:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    667: 
1.180     brouard   668:   Revision 1.179  2015/01/04 09:57:06  brouard
                    669:   Summary: back to OS/X
                    670: 
1.179     brouard   671:   Revision 1.178  2015/01/04 09:35:48  brouard
                    672:   *** empty log message ***
                    673: 
1.178     brouard   674:   Revision 1.177  2015/01/03 18:40:56  brouard
                    675:   Summary: Still testing ilc32 on OSX
                    676: 
1.177     brouard   677:   Revision 1.176  2015/01/03 16:45:04  brouard
                    678:   *** empty log message ***
                    679: 
1.176     brouard   680:   Revision 1.175  2015/01/03 16:33:42  brouard
                    681:   *** empty log message ***
                    682: 
1.175     brouard   683:   Revision 1.174  2015/01/03 16:15:49  brouard
                    684:   Summary: Still in cross-compilation
                    685: 
1.174     brouard   686:   Revision 1.173  2015/01/03 12:06:26  brouard
                    687:   Summary: trying to detect cross-compilation
                    688: 
1.173     brouard   689:   Revision 1.172  2014/12/27 12:07:47  brouard
                    690:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    691: 
1.172     brouard   692:   Revision 1.171  2014/12/23 13:26:59  brouard
                    693:   Summary: Back from Visual C
                    694: 
                    695:   Still problem with utsname.h on Windows
                    696: 
1.171     brouard   697:   Revision 1.170  2014/12/23 11:17:12  brouard
                    698:   Summary: Cleaning some \%% back to %%
                    699: 
                    700:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    701: 
1.170     brouard   702:   Revision 1.169  2014/12/22 23:08:31  brouard
                    703:   Summary: 0.98p
                    704: 
                    705:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    706: 
1.169     brouard   707:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   708:   Summary: update
1.169     brouard   709: 
1.168     brouard   710:   Revision 1.167  2014/12/22 13:50:56  brouard
                    711:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    712: 
                    713:   Testing on Linux 64
                    714: 
1.167     brouard   715:   Revision 1.166  2014/12/22 11:40:47  brouard
                    716:   *** empty log message ***
                    717: 
1.166     brouard   718:   Revision 1.165  2014/12/16 11:20:36  brouard
                    719:   Summary: After compiling on Visual C
                    720: 
                    721:   * imach.c (Module): Merging 1.61 to 1.162
                    722: 
1.165     brouard   723:   Revision 1.164  2014/12/16 10:52:11  brouard
                    724:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    725: 
                    726:   * imach.c (Module): Merging 1.61 to 1.162
                    727: 
1.164     brouard   728:   Revision 1.163  2014/12/16 10:30:11  brouard
                    729:   * imach.c (Module): Merging 1.61 to 1.162
                    730: 
1.163     brouard   731:   Revision 1.162  2014/09/25 11:43:39  brouard
                    732:   Summary: temporary backup 0.99!
                    733: 
1.162     brouard   734:   Revision 1.1  2014/09/16 11:06:58  brouard
                    735:   Summary: With some code (wrong) for nlopt
                    736: 
                    737:   Author:
                    738: 
                    739:   Revision 1.161  2014/09/15 20:41:41  brouard
                    740:   Summary: Problem with macro SQR on Intel compiler
                    741: 
1.161     brouard   742:   Revision 1.160  2014/09/02 09:24:05  brouard
                    743:   *** empty log message ***
                    744: 
1.160     brouard   745:   Revision 1.159  2014/09/01 10:34:10  brouard
                    746:   Summary: WIN32
                    747:   Author: Brouard
                    748: 
1.159     brouard   749:   Revision 1.158  2014/08/27 17:11:51  brouard
                    750:   *** empty log message ***
                    751: 
1.158     brouard   752:   Revision 1.157  2014/08/27 16:26:55  brouard
                    753:   Summary: Preparing windows Visual studio version
                    754:   Author: Brouard
                    755: 
                    756:   In order to compile on Visual studio, time.h is now correct and time_t
                    757:   and tm struct should be used. difftime should be used but sometimes I
                    758:   just make the differences in raw time format (time(&now).
                    759:   Trying to suppress #ifdef LINUX
                    760:   Add xdg-open for __linux in order to open default browser.
                    761: 
1.157     brouard   762:   Revision 1.156  2014/08/25 20:10:10  brouard
                    763:   *** empty log message ***
                    764: 
1.156     brouard   765:   Revision 1.155  2014/08/25 18:32:34  brouard
                    766:   Summary: New compile, minor changes
                    767:   Author: Brouard
                    768: 
1.155     brouard   769:   Revision 1.154  2014/06/20 17:32:08  brouard
                    770:   Summary: Outputs now all graphs of convergence to period prevalence
                    771: 
1.154     brouard   772:   Revision 1.153  2014/06/20 16:45:46  brouard
                    773:   Summary: If 3 live state, convergence to period prevalence on same graph
                    774:   Author: Brouard
                    775: 
1.153     brouard   776:   Revision 1.152  2014/06/18 17:54:09  brouard
                    777:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    778: 
1.152     brouard   779:   Revision 1.151  2014/06/18 16:43:30  brouard
                    780:   *** empty log message ***
                    781: 
1.151     brouard   782:   Revision 1.150  2014/06/18 16:42:35  brouard
                    783:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    784:   Author: brouard
                    785: 
1.150     brouard   786:   Revision 1.149  2014/06/18 15:51:14  brouard
                    787:   Summary: Some fixes in parameter files errors
                    788:   Author: Nicolas Brouard
                    789: 
1.149     brouard   790:   Revision 1.148  2014/06/17 17:38:48  brouard
                    791:   Summary: Nothing new
                    792:   Author: Brouard
                    793: 
                    794:   Just a new packaging for OS/X version 0.98nS
                    795: 
1.148     brouard   796:   Revision 1.147  2014/06/16 10:33:11  brouard
                    797:   *** empty log message ***
                    798: 
1.147     brouard   799:   Revision 1.146  2014/06/16 10:20:28  brouard
                    800:   Summary: Merge
                    801:   Author: Brouard
                    802: 
                    803:   Merge, before building revised version.
                    804: 
1.146     brouard   805:   Revision 1.145  2014/06/10 21:23:15  brouard
                    806:   Summary: Debugging with valgrind
                    807:   Author: Nicolas Brouard
                    808: 
                    809:   Lot of changes in order to output the results with some covariates
                    810:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    811:   improve the code.
                    812:   No more memory valgrind error but a lot has to be done in order to
                    813:   continue the work of splitting the code into subroutines.
                    814:   Also, decodemodel has been improved. Tricode is still not
                    815:   optimal. nbcode should be improved. Documentation has been added in
                    816:   the source code.
                    817: 
1.144     brouard   818:   Revision 1.143  2014/01/26 09:45:38  brouard
                    819:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    820: 
                    821:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    822:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    823: 
1.143     brouard   824:   Revision 1.142  2014/01/26 03:57:36  brouard
                    825:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    826: 
                    827:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    828: 
1.142     brouard   829:   Revision 1.141  2014/01/26 02:42:01  brouard
                    830:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    831: 
1.141     brouard   832:   Revision 1.140  2011/09/02 10:37:54  brouard
                    833:   Summary: times.h is ok with mingw32 now.
                    834: 
1.140     brouard   835:   Revision 1.139  2010/06/14 07:50:17  brouard
                    836:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    837:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    838: 
1.139     brouard   839:   Revision 1.138  2010/04/30 18:19:40  brouard
                    840:   *** empty log message ***
                    841: 
1.138     brouard   842:   Revision 1.137  2010/04/29 18:11:38  brouard
                    843:   (Module): Checking covariates for more complex models
                    844:   than V1+V2. A lot of change to be done. Unstable.
                    845: 
1.137     brouard   846:   Revision 1.136  2010/04/26 20:30:53  brouard
                    847:   (Module): merging some libgsl code. Fixing computation
                    848:   of likelione (using inter/intrapolation if mle = 0) in order to
                    849:   get same likelihood as if mle=1.
                    850:   Some cleaning of code and comments added.
                    851: 
1.136     brouard   852:   Revision 1.135  2009/10/29 15:33:14  brouard
                    853:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    854: 
1.135     brouard   855:   Revision 1.134  2009/10/29 13:18:53  brouard
                    856:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    857: 
1.134     brouard   858:   Revision 1.133  2009/07/06 10:21:25  brouard
                    859:   just nforces
                    860: 
1.133     brouard   861:   Revision 1.132  2009/07/06 08:22:05  brouard
                    862:   Many tings
                    863: 
1.132     brouard   864:   Revision 1.131  2009/06/20 16:22:47  brouard
                    865:   Some dimensions resccaled
                    866: 
1.131     brouard   867:   Revision 1.130  2009/05/26 06:44:34  brouard
                    868:   (Module): Max Covariate is now set to 20 instead of 8. A
                    869:   lot of cleaning with variables initialized to 0. Trying to make
                    870:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    871: 
1.130     brouard   872:   Revision 1.129  2007/08/31 13:49:27  lievre
                    873:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    874: 
1.129     lievre    875:   Revision 1.128  2006/06/30 13:02:05  brouard
                    876:   (Module): Clarifications on computing e.j
                    877: 
1.128     brouard   878:   Revision 1.127  2006/04/28 18:11:50  brouard
                    879:   (Module): Yes the sum of survivors was wrong since
                    880:   imach-114 because nhstepm was no more computed in the age
                    881:   loop. Now we define nhstepma in the age loop.
                    882:   (Module): In order to speed up (in case of numerous covariates) we
                    883:   compute health expectancies (without variances) in a first step
                    884:   and then all the health expectancies with variances or standard
                    885:   deviation (needs data from the Hessian matrices) which slows the
                    886:   computation.
                    887:   In the future we should be able to stop the program is only health
                    888:   expectancies and graph are needed without standard deviations.
                    889: 
1.127     brouard   890:   Revision 1.126  2006/04/28 17:23:28  brouard
                    891:   (Module): Yes the sum of survivors was wrong since
                    892:   imach-114 because nhstepm was no more computed in the age
                    893:   loop. Now we define nhstepma in the age loop.
                    894:   Version 0.98h
                    895: 
1.126     brouard   896:   Revision 1.125  2006/04/04 15:20:31  lievre
                    897:   Errors in calculation of health expectancies. Age was not initialized.
                    898:   Forecasting file added.
                    899: 
                    900:   Revision 1.124  2006/03/22 17:13:53  lievre
                    901:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    902:   The log-likelihood is printed in the log file
                    903: 
                    904:   Revision 1.123  2006/03/20 10:52:43  brouard
                    905:   * imach.c (Module): <title> changed, corresponds to .htm file
                    906:   name. <head> headers where missing.
                    907: 
                    908:   * imach.c (Module): Weights can have a decimal point as for
                    909:   English (a comma might work with a correct LC_NUMERIC environment,
                    910:   otherwise the weight is truncated).
                    911:   Modification of warning when the covariates values are not 0 or
                    912:   1.
                    913:   Version 0.98g
                    914: 
                    915:   Revision 1.122  2006/03/20 09:45:41  brouard
                    916:   (Module): Weights can have a decimal point as for
                    917:   English (a comma might work with a correct LC_NUMERIC environment,
                    918:   otherwise the weight is truncated).
                    919:   Modification of warning when the covariates values are not 0 or
                    920:   1.
                    921:   Version 0.98g
                    922: 
                    923:   Revision 1.121  2006/03/16 17:45:01  lievre
                    924:   * imach.c (Module): Comments concerning covariates added
                    925: 
                    926:   * imach.c (Module): refinements in the computation of lli if
                    927:   status=-2 in order to have more reliable computation if stepm is
                    928:   not 1 month. Version 0.98f
                    929: 
                    930:   Revision 1.120  2006/03/16 15:10:38  lievre
                    931:   (Module): refinements in the computation of lli if
                    932:   status=-2 in order to have more reliable computation if stepm is
                    933:   not 1 month. Version 0.98f
                    934: 
                    935:   Revision 1.119  2006/03/15 17:42:26  brouard
                    936:   (Module): Bug if status = -2, the loglikelihood was
                    937:   computed as likelihood omitting the logarithm. Version O.98e
                    938: 
                    939:   Revision 1.118  2006/03/14 18:20:07  brouard
                    940:   (Module): varevsij Comments added explaining the second
                    941:   table of variances if popbased=1 .
                    942:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    943:   (Module): Function pstamp added
                    944:   (Module): Version 0.98d
                    945: 
                    946:   Revision 1.117  2006/03/14 17:16:22  brouard
                    947:   (Module): varevsij Comments added explaining the second
                    948:   table of variances if popbased=1 .
                    949:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    950:   (Module): Function pstamp added
                    951:   (Module): Version 0.98d
                    952: 
                    953:   Revision 1.116  2006/03/06 10:29:27  brouard
                    954:   (Module): Variance-covariance wrong links and
                    955:   varian-covariance of ej. is needed (Saito).
                    956: 
                    957:   Revision 1.115  2006/02/27 12:17:45  brouard
                    958:   (Module): One freematrix added in mlikeli! 0.98c
                    959: 
                    960:   Revision 1.114  2006/02/26 12:57:58  brouard
                    961:   (Module): Some improvements in processing parameter
                    962:   filename with strsep.
                    963: 
                    964:   Revision 1.113  2006/02/24 14:20:24  brouard
                    965:   (Module): Memory leaks checks with valgrind and:
                    966:   datafile was not closed, some imatrix were not freed and on matrix
                    967:   allocation too.
                    968: 
                    969:   Revision 1.112  2006/01/30 09:55:26  brouard
                    970:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    971: 
                    972:   Revision 1.111  2006/01/25 20:38:18  brouard
                    973:   (Module): Lots of cleaning and bugs added (Gompertz)
                    974:   (Module): Comments can be added in data file. Missing date values
                    975:   can be a simple dot '.'.
                    976: 
                    977:   Revision 1.110  2006/01/25 00:51:50  brouard
                    978:   (Module): Lots of cleaning and bugs added (Gompertz)
                    979: 
                    980:   Revision 1.109  2006/01/24 19:37:15  brouard
                    981:   (Module): Comments (lines starting with a #) are allowed in data.
                    982: 
                    983:   Revision 1.108  2006/01/19 18:05:42  lievre
                    984:   Gnuplot problem appeared...
                    985:   To be fixed
                    986: 
                    987:   Revision 1.107  2006/01/19 16:20:37  brouard
                    988:   Test existence of gnuplot in imach path
                    989: 
                    990:   Revision 1.106  2006/01/19 13:24:36  brouard
                    991:   Some cleaning and links added in html output
                    992: 
                    993:   Revision 1.105  2006/01/05 20:23:19  lievre
                    994:   *** empty log message ***
                    995: 
                    996:   Revision 1.104  2005/09/30 16:11:43  lievre
                    997:   (Module): sump fixed, loop imx fixed, and simplifications.
                    998:   (Module): If the status is missing at the last wave but we know
                    999:   that the person is alive, then we can code his/her status as -2
                   1000:   (instead of missing=-1 in earlier versions) and his/her
                   1001:   contributions to the likelihood is 1 - Prob of dying from last
                   1002:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                   1003:   the healthy state at last known wave). Version is 0.98
                   1004: 
                   1005:   Revision 1.103  2005/09/30 15:54:49  lievre
                   1006:   (Module): sump fixed, loop imx fixed, and simplifications.
                   1007: 
                   1008:   Revision 1.102  2004/09/15 17:31:30  brouard
                   1009:   Add the possibility to read data file including tab characters.
                   1010: 
                   1011:   Revision 1.101  2004/09/15 10:38:38  brouard
                   1012:   Fix on curr_time
                   1013: 
                   1014:   Revision 1.100  2004/07/12 18:29:06  brouard
                   1015:   Add version for Mac OS X. Just define UNIX in Makefile
                   1016: 
                   1017:   Revision 1.99  2004/06/05 08:57:40  brouard
                   1018:   *** empty log message ***
                   1019: 
                   1020:   Revision 1.98  2004/05/16 15:05:56  brouard
                   1021:   New version 0.97 . First attempt to estimate force of mortality
                   1022:   directly from the data i.e. without the need of knowing the health
                   1023:   state at each age, but using a Gompertz model: log u =a + b*age .
                   1024:   This is the basic analysis of mortality and should be done before any
                   1025:   other analysis, in order to test if the mortality estimated from the
                   1026:   cross-longitudinal survey is different from the mortality estimated
                   1027:   from other sources like vital statistic data.
                   1028: 
                   1029:   The same imach parameter file can be used but the option for mle should be -3.
                   1030: 
1.324     brouard  1031:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard  1032:   former routines in order to include the new code within the former code.
                   1033: 
                   1034:   The output is very simple: only an estimate of the intercept and of
                   1035:   the slope with 95% confident intervals.
                   1036: 
                   1037:   Current limitations:
                   1038:   A) Even if you enter covariates, i.e. with the
                   1039:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                   1040:   B) There is no computation of Life Expectancy nor Life Table.
                   1041: 
                   1042:   Revision 1.97  2004/02/20 13:25:42  lievre
                   1043:   Version 0.96d. Population forecasting command line is (temporarily)
                   1044:   suppressed.
                   1045: 
                   1046:   Revision 1.96  2003/07/15 15:38:55  brouard
                   1047:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                   1048:   rewritten within the same printf. Workaround: many printfs.
                   1049: 
                   1050:   Revision 1.95  2003/07/08 07:54:34  brouard
                   1051:   * imach.c (Repository):
                   1052:   (Repository): Using imachwizard code to output a more meaningful covariance
                   1053:   matrix (cov(a12,c31) instead of numbers.
                   1054: 
                   1055:   Revision 1.94  2003/06/27 13:00:02  brouard
                   1056:   Just cleaning
                   1057: 
                   1058:   Revision 1.93  2003/06/25 16:33:55  brouard
                   1059:   (Module): On windows (cygwin) function asctime_r doesn't
                   1060:   exist so I changed back to asctime which exists.
                   1061:   (Module): Version 0.96b
                   1062: 
                   1063:   Revision 1.92  2003/06/25 16:30:45  brouard
                   1064:   (Module): On windows (cygwin) function asctime_r doesn't
                   1065:   exist so I changed back to asctime which exists.
                   1066: 
                   1067:   Revision 1.91  2003/06/25 15:30:29  brouard
                   1068:   * imach.c (Repository): Duplicated warning errors corrected.
                   1069:   (Repository): Elapsed time after each iteration is now output. It
                   1070:   helps to forecast when convergence will be reached. Elapsed time
                   1071:   is stamped in powell.  We created a new html file for the graphs
                   1072:   concerning matrix of covariance. It has extension -cov.htm.
                   1073: 
                   1074:   Revision 1.90  2003/06/24 12:34:15  brouard
                   1075:   (Module): Some bugs corrected for windows. Also, when
                   1076:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1077:   of the covariance matrix to be input.
                   1078: 
                   1079:   Revision 1.89  2003/06/24 12:30:52  brouard
                   1080:   (Module): Some bugs corrected for windows. Also, when
                   1081:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1082:   of the covariance matrix to be input.
                   1083: 
                   1084:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1085:   * 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.
                   1086: 
                   1087:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1088:   Version 0.96
                   1089: 
                   1090:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1091:   (Module): Change position of html and gnuplot routines and added
                   1092:   routine fileappend.
                   1093: 
                   1094:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1095:   * imach.c (Repository): Check when date of death was earlier that
                   1096:   current date of interview. It may happen when the death was just
                   1097:   prior to the death. In this case, dh was negative and likelihood
                   1098:   was wrong (infinity). We still send an "Error" but patch by
                   1099:   assuming that the date of death was just one stepm after the
                   1100:   interview.
                   1101:   (Repository): Because some people have very long ID (first column)
                   1102:   we changed int to long in num[] and we added a new lvector for
                   1103:   memory allocation. But we also truncated to 8 characters (left
                   1104:   truncation)
                   1105:   (Repository): No more line truncation errors.
                   1106: 
                   1107:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1108:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1109:   place. It differs from routine "prevalence" which may be called
                   1110:   many times. Probs is memory consuming and must be used with
                   1111:   parcimony.
                   1112:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1113: 
                   1114:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1115:   *** empty log message ***
                   1116: 
                   1117:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1118:   Add log in  imach.c and  fullversion number is now printed.
                   1119: 
                   1120: */
                   1121: /*
                   1122:    Interpolated Markov Chain
                   1123: 
                   1124:   Short summary of the programme:
                   1125:   
1.227     brouard  1126:   This program computes Healthy Life Expectancies or State-specific
                   1127:   (if states aren't health statuses) Expectancies from
                   1128:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1129: 
                   1130:   -1- a first survey ("cross") where individuals from different ages
                   1131:   are interviewed on their health status or degree of disability (in
                   1132:   the case of a health survey which is our main interest)
                   1133: 
                   1134:   -2- at least a second wave of interviews ("longitudinal") which
                   1135:   measure each change (if any) in individual health status.  Health
                   1136:   expectancies are computed from the time spent in each health state
                   1137:   according to a model. More health states you consider, more time is
                   1138:   necessary to reach the Maximum Likelihood of the parameters involved
                   1139:   in the model.  The simplest model is the multinomial logistic model
                   1140:   where pij is the probability to be observed in state j at the second
                   1141:   wave conditional to be observed in state i at the first
                   1142:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1143:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1144:   have a more complex model than "constant and age", you should modify
                   1145:   the program where the markup *Covariates have to be included here
                   1146:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1147:   convergence.
                   1148: 
                   1149:   The advantage of this computer programme, compared to a simple
                   1150:   multinomial logistic model, is clear when the delay between waves is not
                   1151:   identical for each individual. Also, if a individual missed an
                   1152:   intermediate interview, the information is lost, but taken into
                   1153:   account using an interpolation or extrapolation.  
                   1154: 
                   1155:   hPijx is the probability to be observed in state i at age x+h
                   1156:   conditional to the observed state i at age x. The delay 'h' can be
                   1157:   split into an exact number (nh*stepm) of unobserved intermediate
                   1158:   states. This elementary transition (by month, quarter,
                   1159:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1160:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1161:   and the contribution of each individual to the likelihood is simply
                   1162:   hPijx.
                   1163: 
                   1164:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1165:   of the life expectancies. It also computes the period (stable) prevalence.
                   1166: 
                   1167: Back prevalence and projections:
1.227     brouard  1168: 
                   1169:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1170:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1171:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1172:    mobilavproj)
                   1173: 
                   1174:     Computes the back prevalence limit for any combination of
                   1175:     covariate values k at any age between ageminpar and agemaxpar and
                   1176:     returns it in **bprlim. In the loops,
                   1177: 
                   1178:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1179:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1180: 
                   1181:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1182:    Computes for any combination of covariates k and any age between bage and fage 
                   1183:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1184:                        oldm=oldms;savm=savms;
1.227     brouard  1185: 
1.267     brouard  1186:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1187:      Computes the transition matrix starting at age 'age' over
                   1188:      'nhstepm*hstepm*stepm' months (i.e. until
                   1189:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1190:      nhstepm*hstepm matrices. 
                   1191: 
                   1192:      Returns p3mat[i][j][h] after calling
                   1193:      p3mat[i][j][h]=matprod2(newm,
                   1194:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1195:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1196:      oldm);
1.226     brouard  1197: 
                   1198: Important routines
                   1199: 
                   1200: - func (or funcone), computes logit (pij) distinguishing
                   1201:   o fixed variables (single or product dummies or quantitative);
                   1202:   o varying variables by:
                   1203:    (1) wave (single, product dummies, quantitative), 
                   1204:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1205:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1206:        % varying dummy (not done) or quantitative (not done);
                   1207: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1208:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1209: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1210:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1211:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1212: 
1.226     brouard  1213: 
                   1214:   
1.324     brouard  1215:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1216:            Institut national d'études démographiques, Paris.
1.126     brouard  1217:   This software have been partly granted by Euro-REVES, a concerted action
                   1218:   from the European Union.
                   1219:   It is copyrighted identically to a GNU software product, ie programme and
                   1220:   software can be distributed freely for non commercial use. Latest version
                   1221:   can be accessed at http://euroreves.ined.fr/imach .
                   1222: 
                   1223:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1224:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1225:   
                   1226:   **********************************************************************/
                   1227: /*
                   1228:   main
                   1229:   read parameterfile
                   1230:   read datafile
                   1231:   concatwav
                   1232:   freqsummary
                   1233:   if (mle >= 1)
                   1234:     mlikeli
                   1235:   print results files
                   1236:   if mle==1 
                   1237:      computes hessian
                   1238:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1239:       begin-prev-date,...
                   1240:   open gnuplot file
                   1241:   open html file
1.145     brouard  1242:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1243:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1244:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1245:     freexexit2 possible for memory heap.
                   1246: 
                   1247:   h Pij x                         | pij_nom  ficrestpij
                   1248:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1249:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1250:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1251: 
                   1252:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1253:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1254:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1255:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1256:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1257: 
1.126     brouard  1258:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1259:   health expectancies
                   1260:   Variance-covariance of DFLE
                   1261:   prevalence()
                   1262:    movingaverage()
                   1263:   varevsij() 
                   1264:   if popbased==1 varevsij(,popbased)
                   1265:   total life expectancies
                   1266:   Variance of period (stable) prevalence
                   1267:  end
                   1268: */
                   1269: 
1.187     brouard  1270: /* #define DEBUG */
                   1271: /* #define DEBUGBRENT */
1.203     brouard  1272: /* #define DEBUGLINMIN */
                   1273: /* #define DEBUGHESS */
                   1274: #define DEBUGHESSIJ
1.224     brouard  1275: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1276: #define POWELL /* Instead of NLOPT */
1.224     brouard  1277: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1278: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1279: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1280: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.126     brouard  1281: 
                   1282: #include <math.h>
                   1283: #include <stdio.h>
                   1284: #include <stdlib.h>
                   1285: #include <string.h>
1.226     brouard  1286: #include <ctype.h>
1.159     brouard  1287: 
                   1288: #ifdef _WIN32
                   1289: #include <io.h>
1.172     brouard  1290: #include <windows.h>
                   1291: #include <tchar.h>
1.159     brouard  1292: #else
1.126     brouard  1293: #include <unistd.h>
1.159     brouard  1294: #endif
1.126     brouard  1295: 
                   1296: #include <limits.h>
                   1297: #include <sys/types.h>
1.171     brouard  1298: 
                   1299: #if defined(__GNUC__)
                   1300: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1301: #endif
                   1302: 
1.126     brouard  1303: #include <sys/stat.h>
                   1304: #include <errno.h>
1.159     brouard  1305: /* extern int errno; */
1.126     brouard  1306: 
1.157     brouard  1307: /* #ifdef LINUX */
                   1308: /* #include <time.h> */
                   1309: /* #include "timeval.h" */
                   1310: /* #else */
                   1311: /* #include <sys/time.h> */
                   1312: /* #endif */
                   1313: 
1.126     brouard  1314: #include <time.h>
                   1315: 
1.136     brouard  1316: #ifdef GSL
                   1317: #include <gsl/gsl_errno.h>
                   1318: #include <gsl/gsl_multimin.h>
                   1319: #endif
                   1320: 
1.167     brouard  1321: 
1.162     brouard  1322: #ifdef NLOPT
                   1323: #include <nlopt.h>
                   1324: typedef struct {
                   1325:   double (* function)(double [] );
                   1326: } myfunc_data ;
                   1327: #endif
                   1328: 
1.126     brouard  1329: /* #include <libintl.h> */
                   1330: /* #define _(String) gettext (String) */
                   1331: 
1.349     brouard  1332: #define MAXLINE 16384 /* Was 256 and 1024 and 2048. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1333: 
                   1334: #define GNUPLOTPROGRAM "gnuplot"
1.343     brouard  1335: #define GNUPLOTVERSION 5.1
                   1336: double gnuplotversion=GNUPLOTVERSION;
1.126     brouard  1337: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1338: #define FILENAMELENGTH 256
1.126     brouard  1339: 
                   1340: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1341: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1342: 
1.349     brouard  1343: #define MAXPARM 216 /**< Maximum number of parameters for the optimization was 128 */
1.144     brouard  1344: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1345: 
                   1346: #define NINTERVMAX 8
1.144     brouard  1347: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1348: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1349: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1350: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1351: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1352: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1353: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1354: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1355: /* #define AGESUP 130 */
1.288     brouard  1356: /* #define AGESUP 150 */
                   1357: #define AGESUP 200
1.268     brouard  1358: #define AGEINF 0
1.218     brouard  1359: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1360: #define AGEBASE 40
1.194     brouard  1361: #define AGEOVERFLOW 1.e20
1.164     brouard  1362: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1363: #ifdef _WIN32
                   1364: #define DIRSEPARATOR '\\'
                   1365: #define CHARSEPARATOR "\\"
                   1366: #define ODIRSEPARATOR '/'
                   1367: #else
1.126     brouard  1368: #define DIRSEPARATOR '/'
                   1369: #define CHARSEPARATOR "/"
                   1370: #define ODIRSEPARATOR '\\'
                   1371: #endif
                   1372: 
1.354   ! brouard  1373: /* $Id: imach.c,v 1.353 2023/05/08 18:48:22 brouard Exp $ */
1.126     brouard  1374: /* $State: Exp $ */
1.196     brouard  1375: #include "version.h"
                   1376: char version[]=__IMACH_VERSION__;
1.352     brouard  1377: char copyright[]="April 2023,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015-2020, Nihon University 2021-202, INED 2000-2022";
1.354   ! brouard  1378: char fullversion[]="$Revision: 1.353 $ $Date: 2023/05/08 18:48:22 $"; 
1.126     brouard  1379: char strstart[80];
                   1380: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1381: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.342     brouard  1382: int debugILK=0; /* debugILK is set by a #d in a comment line */
1.187     brouard  1383: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1384: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1385: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
1.335     brouard  1386: 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  1387: 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  1388: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1389: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1390: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
1.349     brouard  1391: int cptcovprodage=0; /**< Number of fixed covariates with age: V3*age or V2*V3*age 1 */
                   1392: int cptcovprodvage=0; /**< Number of varying covariates with age: V7*age or V7*V6*age */
                   1393: int cptcovdageprod=0; /**< Number of doubleproducts with age, since 0.99r44 only: age*Vn*Vm for gnuplot printing*/
1.145     brouard  1394: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335     brouard  1395: 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  1396: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1397: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.339     brouard  1398: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
1.349     brouard  1399: 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 */
                   1400: 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 */
                   1401: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (single or product, dummy or quantitative) in the model */
                   1402: 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  1403: int nsd=0; /**< Total number of single dummy variables (output) */
                   1404: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1405: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1406: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1407: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1408: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1409: int cptcov=0; /* Working variable */
1.334     brouard  1410: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1411: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1412: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1413: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1414: int nlstate=2; /* Number of live states */
                   1415: int ndeath=1; /* Number of dead states */
1.130     brouard  1416: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.339     brouard  1417: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
                   1418: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
1.126     brouard  1419: int popbased=0;
                   1420: 
                   1421: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1422: int maxwav=0; /* Maxim number of waves */
                   1423: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1424: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1425: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1426:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1427: int mle=1, weightopt=0;
1.126     brouard  1428: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1429: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1430: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1431:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1432: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1433: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1434: 
1.130     brouard  1435: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1436: double **matprod2(); /* test */
1.126     brouard  1437: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1438: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1439: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1440: 
1.136     brouard  1441: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1442: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1443: FILE *ficlog, *ficrespow;
1.130     brouard  1444: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1445: double fretone; /* Only one call to likelihood */
1.130     brouard  1446: long ipmx=0; /* Number of contributions */
1.126     brouard  1447: double sw; /* Sum of weights */
                   1448: char filerespow[FILENAMELENGTH];
                   1449: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1450: FILE *ficresilk;
                   1451: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1452: FILE *ficresprobmorprev;
                   1453: FILE *fichtm, *fichtmcov; /* Html File */
                   1454: FILE *ficreseij;
                   1455: char filerese[FILENAMELENGTH];
                   1456: FILE *ficresstdeij;
                   1457: char fileresstde[FILENAMELENGTH];
                   1458: FILE *ficrescveij;
                   1459: char filerescve[FILENAMELENGTH];
                   1460: FILE  *ficresvij;
                   1461: char fileresv[FILENAMELENGTH];
1.269     brouard  1462: 
1.126     brouard  1463: char title[MAXLINE];
1.234     brouard  1464: char model[MAXLINE]; /**< The model line */
1.217     brouard  1465: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1466: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1467: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1468: char command[FILENAMELENGTH];
                   1469: int  outcmd=0;
                   1470: 
1.217     brouard  1471: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1472: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1473: char filelog[FILENAMELENGTH]; /* Log file */
                   1474: char filerest[FILENAMELENGTH];
                   1475: char fileregp[FILENAMELENGTH];
                   1476: char popfile[FILENAMELENGTH];
                   1477: 
                   1478: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1479: 
1.157     brouard  1480: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1481: /* struct timezone tzp; */
                   1482: /* extern int gettimeofday(); */
                   1483: struct tm tml, *gmtime(), *localtime();
                   1484: 
                   1485: extern time_t time();
                   1486: 
                   1487: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1488: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
1.349     brouard  1489: time_t   rlast_btime; /* raw time */
1.157     brouard  1490: struct tm tm;
                   1491: 
1.126     brouard  1492: char strcurr[80], strfor[80];
                   1493: 
                   1494: char *endptr;
                   1495: long lval;
                   1496: double dval;
                   1497: 
                   1498: #define NR_END 1
                   1499: #define FREE_ARG char*
                   1500: #define FTOL 1.0e-10
                   1501: 
                   1502: #define NRANSI 
1.240     brouard  1503: #define ITMAX 200
                   1504: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1505: 
                   1506: #define TOL 2.0e-4 
                   1507: 
                   1508: #define CGOLD 0.3819660 
                   1509: #define ZEPS 1.0e-10 
                   1510: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1511: 
                   1512: #define GOLD 1.618034 
                   1513: #define GLIMIT 100.0 
                   1514: #define TINY 1.0e-20 
                   1515: 
                   1516: static double maxarg1,maxarg2;
                   1517: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1518: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1519:   
                   1520: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1521: #define rint(a) floor(a+0.5)
1.166     brouard  1522: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1523: #define mytinydouble 1.0e-16
1.166     brouard  1524: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1525: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1526: /* static double dsqrarg; */
                   1527: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1528: static double sqrarg;
                   1529: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1530: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1531: int agegomp= AGEGOMP;
                   1532: 
                   1533: int imx; 
                   1534: int stepm=1;
                   1535: /* Stepm, step in month: minimum step interpolation*/
                   1536: 
                   1537: int estepm;
                   1538: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1539: 
                   1540: int m,nb;
                   1541: long *num;
1.197     brouard  1542: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1543: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1544:                   covariate for which somebody answered excluding 
                   1545:                   undefined. Usually 2: 0 and 1. */
                   1546: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1547:                             covariate for which somebody answered including 
                   1548:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1549: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1550: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1551: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1552: 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  1553: double *ageexmed,*agecens;
                   1554: double dateintmean=0;
1.296     brouard  1555:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1556:   double anprojf, mprojf, jprojf;
1.126     brouard  1557: 
1.296     brouard  1558:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1559:   double anbackf, mbackf, jbackf;
                   1560:   double jintmean,mintmean,aintmean;  
1.126     brouard  1561: double *weight;
                   1562: int **s; /* Status */
1.141     brouard  1563: double *agedc;
1.145     brouard  1564: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1565:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1566:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1567: double **coqvar; /* Fixed quantitative covariate nqv */
1.341     brouard  1568: double ***cotvar; /* Time varying covariate start at ncovcol + nqv + (1 to ntv) */
1.225     brouard  1569: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1570: double  idx; 
                   1571: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1572: /* Some documentation */
                   1573:       /*   Design original data
                   1574:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1575:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1576:        *                                                             ntv=3     nqtv=1
1.330     brouard  1577:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1578:        * For time varying covariate, quanti or dummies
                   1579:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
1.341     brouard  1580:        *       cotvar[wav][ncovcol+nqv+ iv(1 to nqtv)][i]= [(1 to nqtv)][i]=(V12) quanti
1.319     brouard  1581:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1582:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1583:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1584:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1585:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1586:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1587:        */
                   1588: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1589: /* 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
                   1590:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1591:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1592: */
1.349     brouard  1593: /*           V5+V4+ V3+V4*V3 +V5*age+V2 +V1*V2+V1*age+V1+V4*V3*age */
                   1594: /*    kmodel  1  2   3    4     5     6    7     8     9    10 */
                   1595: /*Typevar[k]=  0  0   0   2     1    0    2     1     0    3 *//*0 for simple covariate (dummy, quantitative,*/
                   1596:                                                                /* fixed or varying), 1 for age product, 2 for*/
                   1597:                                                                /* product without age, 3 for age and double product   */
                   1598: /*Dummy[k]=    1  0   0   1     3    1    1     2     0     3  *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1599:                                                                 /*(single or product without age), 2 dummy*/
                   1600:                                                                /* with age product, 3 quant with age product*/
                   1601: /*Tvar[k]=     5  4   3   6     5    2    7     1     1     6 */
                   1602: /*    nsd         1   2                               3 */ /* Counting single dummies covar fixed or tv */
                   1603: /*TnsdVar[Tvar]   1   2                               3 */ 
                   1604: /*Tvaraff[nsd]    4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1605: /*TvarsD[nsd]     4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1606: /*TvarsDind[nsd]  2   3                               9 */ /* position K of single dummy cova */
                   1607: /*    nsq      1                     2                  */ /* Counting single quantit tv */
                   1608: /* TvarsQ[k]   5                     2                  */ /* Number of single quantitative cova */
                   1609: /* TvarsQind   1                     6                  */ /* position K of single quantitative cova */
                   1610: /* Tprod[i]=k             1               2             */ /* Position in model of the ith prod without age */
                   1611: /* cptcovage                    1               2         3 */ /* Counting cov*age in the model equation */
                   1612: /* Tage[cptcovage]=k            5               8         10 */ /* Position in the model of ith cov*age */
1.350     brouard  1613: /* 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"*/
                   1614: /*  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  1615: /*  p Tvard[2][1]@21 = {7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0 <repeats 11 times>} */
1.350     brouard  1616: /* 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}*/
                   1617: /* 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  1618: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2               */ /* Position in model of the ith prod without age */
1.330     brouard  1619: /* 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  1620: /* 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  1621: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1622: /* Type                    */
                   1623: /* V         1  2  3  4  5 */
                   1624: /*           F  F  V  V  V */
                   1625: /*           D  Q  D  D  Q */
                   1626: /*                         */
                   1627: int *TvarsD;
1.330     brouard  1628: int *TnsdVar;
1.234     brouard  1629: int *TvarsDind;
                   1630: int *TvarsQ;
                   1631: int *TvarsQind;
                   1632: 
1.318     brouard  1633: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1634: int nresult=0;
1.258     brouard  1635: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1636: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1637: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1638: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1639: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1640: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1641: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1642: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1643: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1644: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1645: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1646: 
                   1647: /* 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
                   1648:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1649:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1650: */
1.234     brouard  1651: /* 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  1652: 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 */
                   1653: 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 */
                   1654: 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 */
                   1655: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1656: 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 */
                   1657: 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  1658: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1659: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1660: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1661: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1662: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1663: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1664: 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 */
                   1665: 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  1666: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1667: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
1.349     brouard  1668: int *TvarVVA; /* We count ncovvt time varying covariates (single or products with age) and put their name into TvarVVA */
                   1669: int *TvarVVAind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1670: int *TvarAVVA; /* We count ALL ncovta time varying covariates (single or products with age) and put their name into TvarVVA */
                   1671: int *TvarAVVAind; /* We count ALL ncovta time varying covariates (single or products without age) and put their name into TvarVV */
1.339     brouard  1672:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  1673:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age */
                   1674:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   1675:       /* TvarVV={3,1,3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */        
                   1676:       /* 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  1677: int *Tvarsel; /**< Selected covariates for output */
                   1678: double *Tvalsel; /**< Selected modality value of covariate for output */
1.349     brouard  1679: 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  1680: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1681: 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  1682: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1683: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1684: int *Tage;
1.227     brouard  1685: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1686: 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  1687: 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*/ 
                   1688: 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  1689: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1690: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1691: int **Tvard;
1.330     brouard  1692: int **Tvardk;
1.227     brouard  1693: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1694: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1695: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1696:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1697:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1698: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1699: double *lsurv, *lpop, *tpop;
                   1700: 
1.231     brouard  1701: #define FD 1; /* Fixed dummy covariate */
                   1702: #define FQ 2; /* Fixed quantitative covariate */
                   1703: #define FP 3; /* Fixed product covariate */
                   1704: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1705: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1706: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1707: #define VD 10; /* Varying dummy covariate */
                   1708: #define VQ 11; /* Varying quantitative covariate */
                   1709: #define VP 12; /* Varying product covariate */
                   1710: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1711: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1712: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1713: #define APFD 16; /* Age product * fixed dummy covariate */
                   1714: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1715: #define APVD 18; /* Age product * varying dummy covariate */
                   1716: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1717: 
                   1718: #define FTYPE 1; /* Fixed covariate */
                   1719: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1720: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1721: 
                   1722: struct kmodel{
                   1723:        int maintype; /* main type */
                   1724:        int subtype; /* subtype */
                   1725: };
                   1726: struct kmodel modell[NCOVMAX];
                   1727: 
1.143     brouard  1728: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1729: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1730: 
                   1731: /**************** split *************************/
                   1732: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1733: {
                   1734:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1735:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1736:   */ 
                   1737:   char *ss;                            /* pointer */
1.186     brouard  1738:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1739: 
                   1740:   l1 = strlen(path );                  /* length of path */
                   1741:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1742:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1743:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1744:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1745:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1746:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1747:     /* get current working directory */
                   1748:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1749: #ifdef WIN32
                   1750:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1751: #else
                   1752:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1753: #endif
1.126     brouard  1754:       return( GLOCK_ERROR_GETCWD );
                   1755:     }
                   1756:     /* got dirc from getcwd*/
                   1757:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1758:   } else {                             /* strip directory from path */
1.126     brouard  1759:     ss++;                              /* after this, the filename */
                   1760:     l2 = strlen( ss );                 /* length of filename */
                   1761:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1762:     strcpy( name, ss );                /* save file name */
                   1763:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1764:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1765:     printf(" DIRC2 = %s \n",dirc);
                   1766:   }
                   1767:   /* We add a separator at the end of dirc if not exists */
                   1768:   l1 = strlen( dirc );                 /* length of directory */
                   1769:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1770:     dirc[l1] =  DIRSEPARATOR;
                   1771:     dirc[l1+1] = 0; 
                   1772:     printf(" DIRC3 = %s \n",dirc);
                   1773:   }
                   1774:   ss = strrchr( name, '.' );           /* find last / */
                   1775:   if (ss >0){
                   1776:     ss++;
                   1777:     strcpy(ext,ss);                    /* save extension */
                   1778:     l1= strlen( name);
                   1779:     l2= strlen(ss)+1;
                   1780:     strncpy( finame, name, l1-l2);
                   1781:     finame[l1-l2]= 0;
                   1782:   }
                   1783: 
                   1784:   return( 0 );                         /* we're done */
                   1785: }
                   1786: 
                   1787: 
                   1788: /******************************************/
                   1789: 
                   1790: void replace_back_to_slash(char *s, char*t)
                   1791: {
                   1792:   int i;
                   1793:   int lg=0;
                   1794:   i=0;
                   1795:   lg=strlen(t);
                   1796:   for(i=0; i<= lg; i++) {
                   1797:     (s[i] = t[i]);
                   1798:     if (t[i]== '\\') s[i]='/';
                   1799:   }
                   1800: }
                   1801: 
1.132     brouard  1802: char *trimbb(char *out, char *in)
1.137     brouard  1803: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1804:   char *s;
                   1805:   s=out;
                   1806:   while (*in != '\0'){
1.137     brouard  1807:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1808:       in++;
                   1809:     }
                   1810:     *out++ = *in++;
                   1811:   }
                   1812:   *out='\0';
                   1813:   return s;
                   1814: }
                   1815: 
1.351     brouard  1816: char *trimbtab(char *out, char *in)
                   1817: { /* Trim  blanks or tabs in line but keeps first blanks if line starts with blanks */
                   1818:   char *s;
                   1819:   s=out;
                   1820:   while (*in != '\0'){
                   1821:     while( (*in == ' ' || *in == '\t')){ /* && *(in+1) != '\0'){*/
                   1822:       in++;
                   1823:     }
                   1824:     *out++ = *in++;
                   1825:   }
                   1826:   *out='\0';
                   1827:   return s;
                   1828: }
                   1829: 
1.187     brouard  1830: /* char *substrchaine(char *out, char *in, char *chain) */
                   1831: /* { */
                   1832: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1833: /*   char *s, *t; */
                   1834: /*   t=in;s=out; */
                   1835: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1836: /*     *out++ = *in++; */
                   1837: /*   } */
                   1838: 
                   1839: /*   /\* *in matches *chain *\/ */
                   1840: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1841: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1842: /*   } */
                   1843: /*   in--; chain--; */
                   1844: /*   while ( (*in != '\0')){ */
                   1845: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1846: /*     *out++ = *in++; */
                   1847: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1848: /*   } */
                   1849: /*   *out='\0'; */
                   1850: /*   out=s; */
                   1851: /*   return out; */
                   1852: /* } */
                   1853: char *substrchaine(char *out, char *in, char *chain)
                   1854: {
                   1855:   /* Substract chain 'chain' from 'in', return and output 'out' */
1.349     brouard  1856:   /* in="V1+V1*age+age*age+V2", chain="+age*age" out="V1+V1*age+V2" */
1.187     brouard  1857: 
                   1858:   char *strloc;
                   1859: 
1.349     brouard  1860:   strcpy (out, in);                   /* out="V1+V1*age+age*age+V2" */
                   1861:   strloc = strstr(out, chain); /* strloc points to out at "+age*age+V2"  */
                   1862:   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  1863:   if(strloc != NULL){ 
1.349     brouard  1864:     /* will affect out */ /* strloc+strlen(chain)=|+V2 = "V1+V1*age+age*age|+V2" */ /* Will also work in Unicodek */
                   1865:     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)*/
                   1866:     /* equivalent to strcpy (strloc, strloc +strlen(chain)) if no overlap; Copies from "+V2" to V1+V1*age+ */
1.187     brouard  1867:   }
1.349     brouard  1868:   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  1869:   return out;
                   1870: }
                   1871: 
                   1872: 
1.145     brouard  1873: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1874: {
1.187     brouard  1875:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.349     brouard  1876:      and alocc starts after first occurence of char 'occ' : ex cutl(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1877:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1878:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1879:   */
1.160     brouard  1880:   char *s, *t;
1.145     brouard  1881:   t=in;s=in;
                   1882:   while ((*in != occ) && (*in != '\0')){
                   1883:     *alocc++ = *in++;
                   1884:   }
                   1885:   if( *in == occ){
                   1886:     *(alocc)='\0';
                   1887:     s=++in;
                   1888:   }
                   1889:  
                   1890:   if (s == t) {/* occ not found */
                   1891:     *(alocc-(in-s))='\0';
                   1892:     in=s;
                   1893:   }
                   1894:   while ( *in != '\0'){
                   1895:     *blocc++ = *in++;
                   1896:   }
                   1897: 
                   1898:   *blocc='\0';
                   1899:   return t;
                   1900: }
1.137     brouard  1901: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1902: {
1.187     brouard  1903:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1904:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1905:      gives blocc="abcdef2ghi" and alocc="j".
                   1906:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1907:   */
                   1908:   char *s, *t;
                   1909:   t=in;s=in;
                   1910:   while (*in != '\0'){
                   1911:     while( *in == occ){
                   1912:       *blocc++ = *in++;
                   1913:       s=in;
                   1914:     }
                   1915:     *blocc++ = *in++;
                   1916:   }
                   1917:   if (s == t) /* occ not found */
                   1918:     *(blocc-(in-s))='\0';
                   1919:   else
                   1920:     *(blocc-(in-s)-1)='\0';
                   1921:   in=s;
                   1922:   while ( *in != '\0'){
                   1923:     *alocc++ = *in++;
                   1924:   }
                   1925: 
                   1926:   *alocc='\0';
                   1927:   return s;
                   1928: }
                   1929: 
1.126     brouard  1930: int nbocc(char *s, char occ)
                   1931: {
                   1932:   int i,j=0;
                   1933:   int lg=20;
                   1934:   i=0;
                   1935:   lg=strlen(s);
                   1936:   for(i=0; i<= lg; i++) {
1.234     brouard  1937:     if  (s[i] == occ ) j++;
1.126     brouard  1938:   }
                   1939:   return j;
                   1940: }
                   1941: 
1.349     brouard  1942: int nboccstr(char *textin, char *chain)
                   1943: {
                   1944:   /* Counts the number of occurence of "chain"  in string textin */
                   1945:   /*  in="+V7*V4+age*V2+age*V3+age*V4"  chain="age" */
                   1946:   char *strloc;
                   1947:   
                   1948:   int i,j=0;
                   1949: 
                   1950:   i=0;
                   1951: 
                   1952:   strloc=textin; /* strloc points to "^+V7*V4+age+..." in textin */
                   1953:   for(;;) {
                   1954:     strloc= strstr(strloc,chain); /* strloc points to first character of chain in textin if found. Example strloc points^ to "+V7*V4+^age" in textin  */
                   1955:     if(strloc != NULL){
                   1956:       strloc = strloc+strlen(chain); /* strloc points to "+V7*V4+age^" in textin */
                   1957:       j++;
                   1958:     }else
                   1959:       break;
                   1960:   }
                   1961:   return j;
                   1962:   
                   1963: }
1.137     brouard  1964: /* void cutv(char *u,char *v, char*t, char occ) */
                   1965: /* { */
                   1966: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1967: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1968: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1969: /*   int i,lg,j,p=0; */
                   1970: /*   i=0; */
                   1971: /*   lg=strlen(t); */
                   1972: /*   for(j=0; j<=lg-1; j++) { */
                   1973: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1974: /*   } */
1.126     brouard  1975: 
1.137     brouard  1976: /*   for(j=0; j<p; j++) { */
                   1977: /*     (u[j] = t[j]); */
                   1978: /*   } */
                   1979: /*      u[p]='\0'; */
1.126     brouard  1980: 
1.137     brouard  1981: /*    for(j=0; j<= lg; j++) { */
                   1982: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1983: /*   } */
                   1984: /* } */
1.126     brouard  1985: 
1.160     brouard  1986: #ifdef _WIN32
                   1987: char * strsep(char **pp, const char *delim)
                   1988: {
                   1989:   char *p, *q;
                   1990:          
                   1991:   if ((p = *pp) == NULL)
                   1992:     return 0;
                   1993:   if ((q = strpbrk (p, delim)) != NULL)
                   1994:   {
                   1995:     *pp = q + 1;
                   1996:     *q = '\0';
                   1997:   }
                   1998:   else
                   1999:     *pp = 0;
                   2000:   return p;
                   2001: }
                   2002: #endif
                   2003: 
1.126     brouard  2004: /********************** nrerror ********************/
                   2005: 
                   2006: void nrerror(char error_text[])
                   2007: {
                   2008:   fprintf(stderr,"ERREUR ...\n");
                   2009:   fprintf(stderr,"%s\n",error_text);
                   2010:   exit(EXIT_FAILURE);
                   2011: }
                   2012: /*********************** vector *******************/
                   2013: double *vector(int nl, int nh)
                   2014: {
                   2015:   double *v;
                   2016:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   2017:   if (!v) nrerror("allocation failure in vector");
                   2018:   return v-nl+NR_END;
                   2019: }
                   2020: 
                   2021: /************************ free vector ******************/
                   2022: void free_vector(double*v, int nl, int nh)
                   2023: {
                   2024:   free((FREE_ARG)(v+nl-NR_END));
                   2025: }
                   2026: 
                   2027: /************************ivector *******************************/
                   2028: int *ivector(long nl,long nh)
                   2029: {
                   2030:   int *v;
                   2031:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   2032:   if (!v) nrerror("allocation failure in ivector");
                   2033:   return v-nl+NR_END;
                   2034: }
                   2035: 
                   2036: /******************free ivector **************************/
                   2037: void free_ivector(int *v, long nl, long nh)
                   2038: {
                   2039:   free((FREE_ARG)(v+nl-NR_END));
                   2040: }
                   2041: 
                   2042: /************************lvector *******************************/
                   2043: long *lvector(long nl,long nh)
                   2044: {
                   2045:   long *v;
                   2046:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   2047:   if (!v) nrerror("allocation failure in ivector");
                   2048:   return v-nl+NR_END;
                   2049: }
                   2050: 
                   2051: /******************free lvector **************************/
                   2052: void free_lvector(long *v, long nl, long nh)
                   2053: {
                   2054:   free((FREE_ARG)(v+nl-NR_END));
                   2055: }
                   2056: 
                   2057: /******************* imatrix *******************************/
                   2058: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   2059:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   2060: { 
                   2061:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   2062:   int **m; 
                   2063:   
                   2064:   /* allocate pointers to rows */ 
                   2065:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   2066:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   2067:   m += NR_END; 
                   2068:   m -= nrl; 
                   2069:   
                   2070:   
                   2071:   /* allocate rows and set pointers to them */ 
                   2072:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   2073:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   2074:   m[nrl] += NR_END; 
                   2075:   m[nrl] -= ncl; 
                   2076:   
                   2077:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   2078:   
                   2079:   /* return pointer to array of pointers to rows */ 
                   2080:   return m; 
                   2081: } 
                   2082: 
                   2083: /****************** free_imatrix *************************/
                   2084: void free_imatrix(m,nrl,nrh,ncl,nch)
                   2085:       int **m;
                   2086:       long nch,ncl,nrh,nrl; 
                   2087:      /* free an int matrix allocated by imatrix() */ 
                   2088: { 
                   2089:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   2090:   free((FREE_ARG) (m+nrl-NR_END)); 
                   2091: } 
                   2092: 
                   2093: /******************* matrix *******************************/
                   2094: double **matrix(long nrl, long nrh, long ncl, long nch)
                   2095: {
                   2096:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   2097:   double **m;
                   2098: 
                   2099:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2100:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2101:   m += NR_END;
                   2102:   m -= nrl;
                   2103: 
                   2104:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2105:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2106:   m[nrl] += NR_END;
                   2107:   m[nrl] -= ncl;
                   2108: 
                   2109:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2110:   return m;
1.145     brouard  2111:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   2112: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   2113: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  2114:    */
                   2115: }
                   2116: 
                   2117: /*************************free matrix ************************/
                   2118: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   2119: {
                   2120:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2121:   free((FREE_ARG)(m+nrl-NR_END));
                   2122: }
                   2123: 
                   2124: /******************* ma3x *******************************/
                   2125: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   2126: {
                   2127:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   2128:   double ***m;
                   2129: 
                   2130:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2131:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2132:   m += NR_END;
                   2133:   m -= nrl;
                   2134: 
                   2135:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2136:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2137:   m[nrl] += NR_END;
                   2138:   m[nrl] -= ncl;
                   2139: 
                   2140:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2141: 
                   2142:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   2143:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2144:   m[nrl][ncl] += NR_END;
                   2145:   m[nrl][ncl] -= nll;
                   2146:   for (j=ncl+1; j<=nch; j++) 
                   2147:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2148:   
                   2149:   for (i=nrl+1; i<=nrh; i++) {
                   2150:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2151:     for (j=ncl+1; j<=nch; j++) 
                   2152:       m[i][j]=m[i][j-1]+nlay;
                   2153:   }
                   2154:   return m; 
                   2155:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2156:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2157:   */
                   2158: }
                   2159: 
                   2160: /*************************free ma3x ************************/
                   2161: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2162: {
                   2163:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2164:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2165:   free((FREE_ARG)(m+nrl-NR_END));
                   2166: }
                   2167: 
                   2168: /*************** function subdirf ***********/
                   2169: char *subdirf(char fileres[])
                   2170: {
                   2171:   /* Caution optionfilefiname is hidden */
                   2172:   strcpy(tmpout,optionfilefiname);
                   2173:   strcat(tmpout,"/"); /* Add to the right */
                   2174:   strcat(tmpout,fileres);
                   2175:   return tmpout;
                   2176: }
                   2177: 
                   2178: /*************** function subdirf2 ***********/
                   2179: char *subdirf2(char fileres[], char *preop)
                   2180: {
1.314     brouard  2181:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2182:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2183:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2184:   /* Caution optionfilefiname is hidden */
                   2185:   strcpy(tmpout,optionfilefiname);
                   2186:   strcat(tmpout,"/");
                   2187:   strcat(tmpout,preop);
                   2188:   strcat(tmpout,fileres);
                   2189:   return tmpout;
                   2190: }
                   2191: 
                   2192: /*************** function subdirf3 ***********/
                   2193: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2194: {
                   2195:   
                   2196:   /* Caution optionfilefiname is hidden */
                   2197:   strcpy(tmpout,optionfilefiname);
                   2198:   strcat(tmpout,"/");
                   2199:   strcat(tmpout,preop);
                   2200:   strcat(tmpout,preop2);
                   2201:   strcat(tmpout,fileres);
                   2202:   return tmpout;
                   2203: }
1.213     brouard  2204:  
                   2205: /*************** function subdirfext ***********/
                   2206: char *subdirfext(char fileres[], char *preop, char *postop)
                   2207: {
                   2208:   
                   2209:   strcpy(tmpout,preop);
                   2210:   strcat(tmpout,fileres);
                   2211:   strcat(tmpout,postop);
                   2212:   return tmpout;
                   2213: }
1.126     brouard  2214: 
1.213     brouard  2215: /*************** function subdirfext3 ***********/
                   2216: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2217: {
                   2218:   
                   2219:   /* Caution optionfilefiname is hidden */
                   2220:   strcpy(tmpout,optionfilefiname);
                   2221:   strcat(tmpout,"/");
                   2222:   strcat(tmpout,preop);
                   2223:   strcat(tmpout,fileres);
                   2224:   strcat(tmpout,postop);
                   2225:   return tmpout;
                   2226: }
                   2227:  
1.162     brouard  2228: char *asc_diff_time(long time_sec, char ascdiff[])
                   2229: {
                   2230:   long sec_left, days, hours, minutes;
                   2231:   days = (time_sec) / (60*60*24);
                   2232:   sec_left = (time_sec) % (60*60*24);
                   2233:   hours = (sec_left) / (60*60) ;
                   2234:   sec_left = (sec_left) %(60*60);
                   2235:   minutes = (sec_left) /60;
                   2236:   sec_left = (sec_left) % (60);
                   2237:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2238:   return ascdiff;
                   2239: }
                   2240: 
1.126     brouard  2241: /***************** f1dim *************************/
                   2242: extern int ncom; 
                   2243: extern double *pcom,*xicom;
                   2244: extern double (*nrfunc)(double []); 
                   2245:  
                   2246: double f1dim(double x) 
                   2247: { 
                   2248:   int j; 
                   2249:   double f;
                   2250:   double *xt; 
                   2251:  
                   2252:   xt=vector(1,ncom); 
                   2253:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2254:   f=(*nrfunc)(xt); 
                   2255:   free_vector(xt,1,ncom); 
                   2256:   return f; 
                   2257: } 
                   2258: 
                   2259: /*****************brent *************************/
                   2260: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2261: {
                   2262:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2263:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2264:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2265:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2266:    * returned function value. 
                   2267:   */
1.126     brouard  2268:   int iter; 
                   2269:   double a,b,d,etemp;
1.159     brouard  2270:   double fu=0,fv,fw,fx;
1.164     brouard  2271:   double ftemp=0.;
1.126     brouard  2272:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2273:   double e=0.0; 
                   2274:  
                   2275:   a=(ax < cx ? ax : cx); 
                   2276:   b=(ax > cx ? ax : cx); 
                   2277:   x=w=v=bx; 
                   2278:   fw=fv=fx=(*f)(x); 
                   2279:   for (iter=1;iter<=ITMAX;iter++) { 
                   2280:     xm=0.5*(a+b); 
                   2281:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2282:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2283:     printf(".");fflush(stdout);
                   2284:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2285: #ifdef DEBUGBRENT
1.126     brouard  2286:     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);
                   2287:     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);
                   2288:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2289: #endif
                   2290:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2291:       *xmin=x; 
                   2292:       return fx; 
                   2293:     } 
                   2294:     ftemp=fu;
                   2295:     if (fabs(e) > tol1) { 
                   2296:       r=(x-w)*(fx-fv); 
                   2297:       q=(x-v)*(fx-fw); 
                   2298:       p=(x-v)*q-(x-w)*r; 
                   2299:       q=2.0*(q-r); 
                   2300:       if (q > 0.0) p = -p; 
                   2301:       q=fabs(q); 
                   2302:       etemp=e; 
                   2303:       e=d; 
                   2304:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2305:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2306:       else { 
1.224     brouard  2307:                                d=p/q; 
                   2308:                                u=x+d; 
                   2309:                                if (u-a < tol2 || b-u < tol2) 
                   2310:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2311:       } 
                   2312:     } else { 
                   2313:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2314:     } 
                   2315:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2316:     fu=(*f)(u); 
                   2317:     if (fu <= fx) { 
                   2318:       if (u >= x) a=x; else b=x; 
                   2319:       SHFT(v,w,x,u) 
1.183     brouard  2320:       SHFT(fv,fw,fx,fu) 
                   2321:     } else { 
                   2322:       if (u < x) a=u; else b=u; 
                   2323:       if (fu <= fw || w == x) { 
1.224     brouard  2324:                                v=w; 
                   2325:                                w=u; 
                   2326:                                fv=fw; 
                   2327:                                fw=fu; 
1.183     brouard  2328:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2329:                                v=u; 
                   2330:                                fv=fu; 
1.183     brouard  2331:       } 
                   2332:     } 
1.126     brouard  2333:   } 
                   2334:   nrerror("Too many iterations in brent"); 
                   2335:   *xmin=x; 
                   2336:   return fx; 
                   2337: } 
                   2338: 
                   2339: /****************** mnbrak ***********************/
                   2340: 
                   2341: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2342:            double (*func)(double)) 
1.183     brouard  2343: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2344: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2345: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2346: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2347:    */
1.126     brouard  2348:   double ulim,u,r,q, dum;
                   2349:   double fu; 
1.187     brouard  2350: 
                   2351:   double scale=10.;
                   2352:   int iterscale=0;
                   2353: 
                   2354:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2355:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2356: 
                   2357: 
                   2358:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2359:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2360:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2361:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2362:   /* } */
                   2363: 
1.126     brouard  2364:   if (*fb > *fa) { 
                   2365:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2366:     SHFT(dum,*fb,*fa,dum) 
                   2367:   } 
1.126     brouard  2368:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2369:   *fc=(*func)(*cx); 
1.183     brouard  2370: #ifdef DEBUG
1.224     brouard  2371:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2372:   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  2373: #endif
1.224     brouard  2374:   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  2375:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2376:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2377:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2378:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2379:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2380:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2381:       fu=(*func)(u); 
1.163     brouard  2382: #ifdef DEBUG
                   2383:       /* f(x)=A(x-u)**2+f(u) */
                   2384:       double A, fparabu; 
                   2385:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2386:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2387:       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);
                   2388:       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  2389:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2390:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2391:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2392:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2393: #endif 
1.184     brouard  2394: #ifdef MNBRAKORIGINAL
1.183     brouard  2395: #else
1.191     brouard  2396: /*       if (fu > *fc) { */
                   2397: /* #ifdef DEBUG */
                   2398: /*       printf("mnbrak4  fu > fc \n"); */
                   2399: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2400: /* #endif */
                   2401: /*     /\* 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 *\\/  *\/ */
                   2402: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2403: /*     dum=u; /\* Shifting c and u *\/ */
                   2404: /*     u = *cx; */
                   2405: /*     *cx = dum; */
                   2406: /*     dum = fu; */
                   2407: /*     fu = *fc; */
                   2408: /*     *fc =dum; */
                   2409: /*       } else { /\* end *\/ */
                   2410: /* #ifdef DEBUG */
                   2411: /*       printf("mnbrak3  fu < fc \n"); */
                   2412: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2413: /* #endif */
                   2414: /*     dum=u; /\* Shifting c and u *\/ */
                   2415: /*     u = *cx; */
                   2416: /*     *cx = dum; */
                   2417: /*     dum = fu; */
                   2418: /*     fu = *fc; */
                   2419: /*     *fc =dum; */
                   2420: /*       } */
1.224     brouard  2421: #ifdef DEBUGMNBRAK
                   2422:                 double A, fparabu; 
                   2423:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2424:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2425:      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);
                   2426:      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  2427: #endif
1.191     brouard  2428:       dum=u; /* Shifting c and u */
                   2429:       u = *cx;
                   2430:       *cx = dum;
                   2431:       dum = fu;
                   2432:       fu = *fc;
                   2433:       *fc =dum;
1.183     brouard  2434: #endif
1.162     brouard  2435:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2436: #ifdef DEBUG
1.224     brouard  2437:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2438:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2439: #endif
1.126     brouard  2440:       fu=(*func)(u); 
                   2441:       if (fu < *fc) { 
1.183     brouard  2442: #ifdef DEBUG
1.224     brouard  2443:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2444:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2445: #endif
                   2446:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2447:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2448: #ifdef DEBUG
                   2449:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2450: #endif
                   2451:       } 
1.162     brouard  2452:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2453: #ifdef DEBUG
1.224     brouard  2454:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2455:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2456: #endif
1.126     brouard  2457:       u=ulim; 
                   2458:       fu=(*func)(u); 
1.183     brouard  2459:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2460: #ifdef DEBUG
1.224     brouard  2461:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2462:       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  2463: #endif
1.126     brouard  2464:       u=(*cx)+GOLD*(*cx-*bx); 
                   2465:       fu=(*func)(u); 
1.224     brouard  2466: #ifdef DEBUG
                   2467:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2468:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2469: #endif
1.183     brouard  2470:     } /* end tests */
1.126     brouard  2471:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2472:     SHFT(*fa,*fb,*fc,fu) 
                   2473: #ifdef DEBUG
1.224     brouard  2474:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2475:       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  2476: #endif
                   2477:   } /* 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  2478: } 
                   2479: 
                   2480: /*************** linmin ************************/
1.162     brouard  2481: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2482: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2483: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2484: the value of func at the returned location p . This is actually all accomplished by calling the
                   2485: routines mnbrak and brent .*/
1.126     brouard  2486: int ncom; 
                   2487: double *pcom,*xicom;
                   2488: double (*nrfunc)(double []); 
                   2489:  
1.224     brouard  2490: #ifdef LINMINORIGINAL
1.126     brouard  2491: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2492: #else
                   2493: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2494: #endif
1.126     brouard  2495: { 
                   2496:   double brent(double ax, double bx, double cx, 
                   2497:               double (*f)(double), double tol, double *xmin); 
                   2498:   double f1dim(double x); 
                   2499:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2500:              double *fc, double (*func)(double)); 
                   2501:   int j; 
                   2502:   double xx,xmin,bx,ax; 
                   2503:   double fx,fb,fa;
1.187     brouard  2504: 
1.203     brouard  2505: #ifdef LINMINORIGINAL
                   2506: #else
                   2507:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2508: #endif
                   2509:   
1.126     brouard  2510:   ncom=n; 
                   2511:   pcom=vector(1,n); 
                   2512:   xicom=vector(1,n); 
                   2513:   nrfunc=func; 
                   2514:   for (j=1;j<=n;j++) { 
                   2515:     pcom[j]=p[j]; 
1.202     brouard  2516:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2517:   } 
1.187     brouard  2518: 
1.203     brouard  2519: #ifdef LINMINORIGINAL
                   2520:   xx=1.;
                   2521: #else
                   2522:   axs=0.0;
                   2523:   xxs=1.;
                   2524:   do{
                   2525:     xx= xxs;
                   2526: #endif
1.187     brouard  2527:     ax=0.;
                   2528:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2529:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2530:     /* 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))   */
                   2531:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2532:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2533:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2534:     /* 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  2535: #ifdef LINMINORIGINAL
                   2536: #else
                   2537:     if (fx != fx){
1.224     brouard  2538:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2539:                        printf("|");
                   2540:                        fprintf(ficlog,"|");
1.203     brouard  2541: #ifdef DEBUGLINMIN
1.224     brouard  2542:                        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  2543: #endif
                   2544:     }
1.224     brouard  2545:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2546: #endif
                   2547:   
1.191     brouard  2548: #ifdef DEBUGLINMIN
                   2549:   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  2550:   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  2551: #endif
1.224     brouard  2552: #ifdef LINMINORIGINAL
                   2553: #else
1.317     brouard  2554:   if(fb == fx){ /* Flat function in the direction */
                   2555:     xmin=xx;
1.224     brouard  2556:     *flat=1;
1.317     brouard  2557:   }else{
1.224     brouard  2558:     *flat=0;
                   2559: #endif
                   2560:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2561:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2562:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2563:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2564:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2565:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2566: #ifdef DEBUG
1.224     brouard  2567:   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);
                   2568:   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);
                   2569: #endif
                   2570: #ifdef LINMINORIGINAL
                   2571: #else
                   2572:                        }
1.126     brouard  2573: #endif
1.191     brouard  2574: #ifdef DEBUGLINMIN
                   2575:   printf("linmin end ");
1.202     brouard  2576:   fprintf(ficlog,"linmin end ");
1.191     brouard  2577: #endif
1.126     brouard  2578:   for (j=1;j<=n;j++) { 
1.203     brouard  2579: #ifdef LINMINORIGINAL
                   2580:     xi[j] *= xmin; 
                   2581: #else
                   2582: #ifdef DEBUGLINMIN
                   2583:     if(xxs <1.0)
                   2584:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2585: #endif
                   2586:     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) */
                   2587: #ifdef DEBUGLINMIN
                   2588:     if(xxs <1.0)
                   2589:       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 );
                   2590: #endif
                   2591: #endif
1.187     brouard  2592:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2593:   } 
1.191     brouard  2594: #ifdef DEBUGLINMIN
1.203     brouard  2595:   printf("\n");
1.191     brouard  2596:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2597:   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  2598:   for (j=1;j<=n;j++) { 
1.202     brouard  2599:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2600:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2601:     if(j % ncovmodel == 0){
1.191     brouard  2602:       printf("\n");
1.202     brouard  2603:       fprintf(ficlog,"\n");
                   2604:     }
1.191     brouard  2605:   }
1.203     brouard  2606: #else
1.191     brouard  2607: #endif
1.126     brouard  2608:   free_vector(xicom,1,n); 
                   2609:   free_vector(pcom,1,n); 
                   2610: } 
                   2611: 
                   2612: 
                   2613: /*************** powell ************************/
1.162     brouard  2614: /*
1.317     brouard  2615: Minimization of a function func of n variables. Input consists in an initial starting point
                   2616: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2617: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2618: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2619: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2620: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2621:  */
1.224     brouard  2622: #ifdef LINMINORIGINAL
                   2623: #else
                   2624:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2625:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2626: #endif
1.126     brouard  2627: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2628:            double (*func)(double [])) 
                   2629: { 
1.224     brouard  2630: #ifdef LINMINORIGINAL
                   2631:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2632:              double (*func)(double [])); 
1.224     brouard  2633: #else 
1.241     brouard  2634:  void linmin(double p[], double xi[], int n, double *fret,
                   2635:             double (*func)(double []),int *flat); 
1.224     brouard  2636: #endif
1.239     brouard  2637:  int i,ibig,j,jk,k; 
1.126     brouard  2638:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2639:   double directest;
1.126     brouard  2640:   double fp,fptt;
                   2641:   double *xits;
                   2642:   int niterf, itmp;
1.349     brouard  2643:   int Bigter=0, nBigterf=1;
                   2644:   
1.126     brouard  2645:   pt=vector(1,n); 
                   2646:   ptt=vector(1,n); 
                   2647:   xit=vector(1,n); 
                   2648:   xits=vector(1,n); 
                   2649:   *fret=(*func)(p); 
                   2650:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.338     brouard  2651:   rcurr_time = time(NULL);
                   2652:   fp=(*fret); /* Initialisation */
1.126     brouard  2653:   for (*iter=1;;++(*iter)) { 
                   2654:     ibig=0; 
                   2655:     del=0.0; 
1.157     brouard  2656:     rlast_time=rcurr_time;
1.349     brouard  2657:     rlast_btime=rcurr_time;
1.157     brouard  2658:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2659:     rcurr_time = time(NULL);  
                   2660:     curr_time = *localtime(&rcurr_time);
1.337     brouard  2661:     /* 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); */
                   2662:     /* 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.349     brouard  2663:     Bigter=(*iter - *iter % ncovmodel)/ncovmodel +1; /* Big iteration, i.e on ncovmodel cycle */
                   2664:     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);
                   2665:     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);
                   2666:     fprintf(ficrespow,"%d %d %.12f %d",*iter,Bigter, *fret,curr_time.tm_sec-start_time.tm_sec);
1.324     brouard  2667:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2668:     for (i=1;i<=n;i++) {
1.126     brouard  2669:       fprintf(ficrespow," %.12lf", p[i]);
                   2670:     }
1.239     brouard  2671:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2672:     printf("\n#model=  1      +     age ");
                   2673:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2674:     if(nagesqr==1){
1.241     brouard  2675:        printf("  + age*age  ");
                   2676:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2677:     }
                   2678:     for(j=1;j <=ncovmodel-2;j++){
                   2679:       if(Typevar[j]==0) {
                   2680:        printf("  +      V%d  ",Tvar[j]);
                   2681:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2682:       }else if(Typevar[j]==1) {
                   2683:        printf("  +    V%d*age ",Tvar[j]);
                   2684:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2685:       }else if(Typevar[j]==2) {
                   2686:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2687:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  2688:       }else if(Typevar[j]==3) {
                   2689:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2690:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.239     brouard  2691:       }
                   2692:     }
1.126     brouard  2693:     printf("\n");
1.239     brouard  2694: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2695: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2696:     fprintf(ficlog,"\n");
1.239     brouard  2697:     for(i=1,jk=1; i <=nlstate; i++){
                   2698:       for(k=1; k <=(nlstate+ndeath); k++){
                   2699:        if (k != i) {
                   2700:          printf("%d%d ",i,k);
                   2701:          fprintf(ficlog,"%d%d ",i,k);
                   2702:          for(j=1; j <=ncovmodel; j++){
                   2703:            printf("%12.7f ",p[jk]);
                   2704:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2705:            jk++; 
                   2706:          }
                   2707:          printf("\n");
                   2708:          fprintf(ficlog,"\n");
                   2709:        }
                   2710:       }
                   2711:     }
1.241     brouard  2712:     if(*iter <=3 && *iter >1){
1.157     brouard  2713:       tml = *localtime(&rcurr_time);
                   2714:       strcpy(strcurr,asctime(&tml));
                   2715:       rforecast_time=rcurr_time; 
1.126     brouard  2716:       itmp = strlen(strcurr);
                   2717:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2718:        strcurr[itmp-1]='\0';
1.162     brouard  2719:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2720:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.349     brouard  2721:       for(nBigterf=1;nBigterf<=31;nBigterf+=10){
                   2722:        niterf=nBigterf*ncovmodel;
                   2723:        /* rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time); */
1.241     brouard  2724:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2725:        forecast_time = *localtime(&rforecast_time);
                   2726:        strcpy(strfor,asctime(&forecast_time));
                   2727:        itmp = strlen(strfor);
                   2728:        if(strfor[itmp-1]=='\n')
                   2729:          strfor[itmp-1]='\0';
1.349     brouard  2730:        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);
                   2731:        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  2732:       }
                   2733:     }
1.187     brouard  2734:     for (i=1;i<=n;i++) { /* For each direction i */
                   2735:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2736:       fptt=(*fret); 
                   2737: #ifdef DEBUG
1.203     brouard  2738:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2739:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2740: #endif
1.203     brouard  2741:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2742:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2743: #ifdef LINMINORIGINAL
1.188     brouard  2744:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2745: #else
                   2746:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2747:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2748: #endif
                   2749:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2750:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2751:                                /* because that direction will be replaced unless the gain del is small */
                   2752:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2753:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2754:                                /* with the new direction. */
                   2755:                                del=fabs(fptt-(*fret)); 
                   2756:                                ibig=i; 
1.126     brouard  2757:       } 
                   2758: #ifdef DEBUG
                   2759:       printf("%d %.12e",i,(*fret));
                   2760:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2761:       for (j=1;j<=n;j++) {
1.224     brouard  2762:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2763:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2764:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2765:       }
                   2766:       for(j=1;j<=n;j++) {
1.225     brouard  2767:                                printf(" p(%d)=%.12e",j,p[j]);
                   2768:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2769:       }
                   2770:       printf("\n");
                   2771:       fprintf(ficlog,"\n");
                   2772: #endif
1.187     brouard  2773:     } /* end loop on each direction i */
                   2774:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2775:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2776:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2777:     for(j=1;j<=n;j++) {
                   2778:       if(flatdir[j] >0){
                   2779:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2780:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2781:       }
1.319     brouard  2782:       /* printf("\n"); */
                   2783:       /* fprintf(ficlog,"\n"); */
                   2784:     }
1.243     brouard  2785:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2786:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2787:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2788:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2789:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2790:       /* decreased of more than 3.84  */
                   2791:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2792:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2793:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2794:                        
1.188     brouard  2795:       /* Starting the program with initial values given by a former maximization will simply change */
                   2796:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2797:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2798:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2799: #ifdef DEBUG
                   2800:       int k[2],l;
                   2801:       k[0]=1;
                   2802:       k[1]=-1;
                   2803:       printf("Max: %.12e",(*func)(p));
                   2804:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2805:       for (j=1;j<=n;j++) {
                   2806:        printf(" %.12e",p[j]);
                   2807:        fprintf(ficlog," %.12e",p[j]);
                   2808:       }
                   2809:       printf("\n");
                   2810:       fprintf(ficlog,"\n");
                   2811:       for(l=0;l<=1;l++) {
                   2812:        for (j=1;j<=n;j++) {
                   2813:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2814:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2815:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2816:        }
                   2817:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2818:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2819:       }
                   2820: #endif
                   2821: 
                   2822:       free_vector(xit,1,n); 
                   2823:       free_vector(xits,1,n); 
                   2824:       free_vector(ptt,1,n); 
                   2825:       free_vector(pt,1,n); 
                   2826:       return; 
1.192     brouard  2827:     } /* enough precision */ 
1.240     brouard  2828:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2829:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2830:       ptt[j]=2.0*p[j]-pt[j]; 
                   2831:       xit[j]=p[j]-pt[j]; 
                   2832:       pt[j]=p[j]; 
                   2833:     } 
1.181     brouard  2834:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2835: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2836:                if (*iter <=4) {
1.225     brouard  2837: #else
                   2838: #endif
1.224     brouard  2839: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2840: #else
1.161     brouard  2841:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2842: #endif
1.162     brouard  2843:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2844:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2845:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2846:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2847:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2848:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2849:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2850:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2851:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2852:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2853:       /* mu² and del² are equal when f3=f1 */
                   2854:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2855:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2856:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2857:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2858: #ifdef NRCORIGINAL
                   2859:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2860: #else
                   2861:       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  2862:       t= t- del*SQR(fp-fptt);
1.183     brouard  2863: #endif
1.202     brouard  2864:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2865: #ifdef DEBUG
1.181     brouard  2866:       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);
                   2867:       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  2868:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2869:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2870:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2871:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2872:       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);
                   2873:       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);
                   2874: #endif
1.183     brouard  2875: #ifdef POWELLORIGINAL
                   2876:       if (t < 0.0) { /* Then we use it for new direction */
                   2877: #else
1.182     brouard  2878:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2879:                                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  2880:         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  2881:         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  2882:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2883:       } 
1.181     brouard  2884:       if (directest < 0.0) { /* Then we use it for new direction */
                   2885: #endif
1.191     brouard  2886: #ifdef DEBUGLINMIN
1.234     brouard  2887:        printf("Before linmin in direction P%d-P0\n",n);
                   2888:        for (j=1;j<=n;j++) {
                   2889:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2890:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2891:          if(j % ncovmodel == 0){
                   2892:            printf("\n");
                   2893:            fprintf(ficlog,"\n");
                   2894:          }
                   2895:        }
1.224     brouard  2896: #endif
                   2897: #ifdef LINMINORIGINAL
1.234     brouard  2898:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2899: #else
1.234     brouard  2900:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2901:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2902: #endif
1.234     brouard  2903:        
1.191     brouard  2904: #ifdef DEBUGLINMIN
1.234     brouard  2905:        for (j=1;j<=n;j++) { 
                   2906:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2907:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2908:          if(j % ncovmodel == 0){
                   2909:            printf("\n");
                   2910:            fprintf(ficlog,"\n");
                   2911:          }
                   2912:        }
1.224     brouard  2913: #endif
1.234     brouard  2914:        for (j=1;j<=n;j++) { 
                   2915:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2916:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2917:        }
1.224     brouard  2918: #ifdef LINMINORIGINAL
                   2919: #else
1.234     brouard  2920:        for (j=1, flatd=0;j<=n;j++) {
                   2921:          if(flatdir[j]>0)
                   2922:            flatd++;
                   2923:        }
                   2924:        if(flatd >0){
1.255     brouard  2925:          printf("%d flat directions: ",flatd);
                   2926:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2927:          for (j=1;j<=n;j++) { 
                   2928:            if(flatdir[j]>0){
                   2929:              printf("%d ",j);
                   2930:              fprintf(ficlog,"%d ",j);
                   2931:            }
                   2932:          }
                   2933:          printf("\n");
                   2934:          fprintf(ficlog,"\n");
1.319     brouard  2935: #ifdef FLATSUP
                   2936:           free_vector(xit,1,n); 
                   2937:           free_vector(xits,1,n); 
                   2938:           free_vector(ptt,1,n); 
                   2939:           free_vector(pt,1,n); 
                   2940:           return;
                   2941: #endif
1.234     brouard  2942:        }
1.191     brouard  2943: #endif
1.234     brouard  2944:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2945:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2946:        
1.126     brouard  2947: #ifdef DEBUG
1.234     brouard  2948:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2949:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2950:        for(j=1;j<=n;j++){
                   2951:          printf(" %lf",xit[j]);
                   2952:          fprintf(ficlog," %lf",xit[j]);
                   2953:        }
                   2954:        printf("\n");
                   2955:        fprintf(ficlog,"\n");
1.126     brouard  2956: #endif
1.192     brouard  2957:       } /* end of t or directest negative */
1.224     brouard  2958: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2959: #else
1.234     brouard  2960:       } /* end if (fptt < fp)  */
1.192     brouard  2961: #endif
1.225     brouard  2962: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2963:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2964: #else
1.224     brouard  2965: #endif
1.234     brouard  2966:                } /* loop iteration */ 
1.126     brouard  2967: } 
1.234     brouard  2968:   
1.126     brouard  2969: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2970:   
1.235     brouard  2971:   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  2972:   {
1.338     brouard  2973:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
1.279     brouard  2974:      *   (and selected quantitative values in nres)
                   2975:      *  by left multiplying the unit
                   2976:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2977:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2978:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2979:      * or prevalence in state 1, prevalence in state 2, 0
                   2980:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2981:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2982:      * Output is prlim.
                   2983:      * Initial matrix pimij 
                   2984:      */
1.206     brouard  2985:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2986:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2987:   /*  0,                   0                  , 1} */
                   2988:   /*
                   2989:    * and after some iteration: */
                   2990:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2991:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2992:   /*  0,                   0                  , 1} */
                   2993:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2994:   /* {0.51571254859325999, 0.4842874514067399, */
                   2995:   /*  0.51326036147820708, 0.48673963852179264} */
                   2996:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2997:     
1.332     brouard  2998:     int i, ii,j,k, k1;
1.209     brouard  2999:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  3000:   /* double **matprod2(); */ /* test */
1.218     brouard  3001:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  3002:   double **newm;
1.209     brouard  3003:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  3004:   int ncvloop=0;
1.288     brouard  3005:   int first=0;
1.169     brouard  3006:   
1.209     brouard  3007:   min=vector(1,nlstate);
                   3008:   max=vector(1,nlstate);
                   3009:   meandiff=vector(1,nlstate);
                   3010: 
1.218     brouard  3011:        /* Starting with matrix unity */
1.126     brouard  3012:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3013:     for (j=1;j<=nlstate+ndeath;j++){
                   3014:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3015:     }
1.169     brouard  3016:   
                   3017:   cov[1]=1.;
                   3018:   
                   3019:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  3020:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  3021:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  3022:     ncvloop++;
1.126     brouard  3023:     newm=savm;
                   3024:     /* Covariates have to be included here again */
1.138     brouard  3025:     cov[2]=agefin;
1.319     brouard  3026:      if(nagesqr==1){
                   3027:       cov[3]= agefin*agefin;
                   3028:      }
1.332     brouard  3029:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3030:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3031:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3032:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3033:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3034:        }else{
                   3035:         cov[2+nagesqr+k1]=precov[nres][k1];
                   3036:        }
                   3037:      }/* End of loop on model equation */
                   3038:      
                   3039: /* Start of old code (replaced by a loop on position in the model equation */
                   3040:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   3041:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3042:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   3043:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   3044:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   3045:     /*    * k                  1        2      3    4      5      6     7        8 */
                   3046:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   3047:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   3048:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   3049:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   3050:     /*    *nsd=3                              (1)  (2)           (3) */
                   3051:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   3052:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   3053:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   3054:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   3055:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   3056:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   3057:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   3058:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   3059:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   3060:     /*    *TvarsDpType */
                   3061:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   3062:     /*    * nsd=1              (1)           (2) */
                   3063:     /*    *TvarsD[nsd]          3             2 */
                   3064:     /*    *TnsdVar           (3)=1          (2)=2 */
                   3065:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   3066:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   3067:     /*    *\/ */
                   3068:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   3069:     /*   /\* 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)); *\/ */
                   3070:     /* } */
                   3071:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   3072:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3073:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   3074:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3075:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   3076:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   3077:     /*   /\* 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]); *\/ */
                   3078:     /* } */
                   3079:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3080:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   3081:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3082:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   3083:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   3084:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3085:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   3086:     /*   } */
                   3087:     /*   /\* 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]); *\/ */
                   3088:     /* } */
                   3089:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3090:     /*   /\* 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]); *\/ */
                   3091:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3092:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3093:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3094:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3095:     /*         }else{ */
                   3096:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3097:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   3098:     /*         } */
                   3099:     /*   }else{ */
                   3100:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3101:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3102:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   3103:     /*         }else{ */
                   3104:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3105:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   3106:     /*         } */
                   3107:     /*   } */
                   3108:     /* } /\* End product without age *\/ */
                   3109: /* ENd of old code */
1.138     brouard  3110:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3111:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3112:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  3113:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3114:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  3115:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  3116:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  3117:     
1.126     brouard  3118:     savm=oldm;
                   3119:     oldm=newm;
1.209     brouard  3120: 
                   3121:     for(j=1; j<=nlstate; j++){
                   3122:       max[j]=0.;
                   3123:       min[j]=1.;
                   3124:     }
                   3125:     for(i=1;i<=nlstate;i++){
                   3126:       sumnew=0;
                   3127:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   3128:       for(j=1; j<=nlstate; j++){ 
                   3129:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   3130:        max[j]=FMAX(max[j],prlim[i][j]);
                   3131:        min[j]=FMIN(min[j],prlim[i][j]);
                   3132:       }
                   3133:     }
                   3134: 
1.126     brouard  3135:     maxmax=0.;
1.209     brouard  3136:     for(j=1; j<=nlstate; j++){
                   3137:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   3138:       maxmax=FMAX(maxmax,meandiff[j]);
                   3139:       /* 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  3140:     } /* j loop */
1.203     brouard  3141:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  3142:     /* 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  3143:     if(maxmax < ftolpl){
1.209     brouard  3144:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   3145:       free_vector(min,1,nlstate);
                   3146:       free_vector(max,1,nlstate);
                   3147:       free_vector(meandiff,1,nlstate);
1.126     brouard  3148:       return prlim;
                   3149:     }
1.288     brouard  3150:   } /* agefin loop */
1.208     brouard  3151:     /* After some age loop it doesn't converge */
1.288     brouard  3152:   if(!first){
                   3153:     first=1;
                   3154:     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  3155:     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);
                   3156:   }else if (first >=1 && first <10){
                   3157:     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);
                   3158:     first++;
                   3159:   }else if (first ==10){
                   3160:     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);
                   3161:     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");
                   3162:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   3163:     first++;
1.288     brouard  3164:   }
                   3165: 
1.209     brouard  3166:   /* 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); */
                   3167:   free_vector(min,1,nlstate);
                   3168:   free_vector(max,1,nlstate);
                   3169:   free_vector(meandiff,1,nlstate);
1.208     brouard  3170:   
1.169     brouard  3171:   return prlim; /* should not reach here */
1.126     brouard  3172: }
                   3173: 
1.217     brouard  3174: 
                   3175:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   3176: 
1.218     brouard  3177:  /* 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) */
                   3178:  /* 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  3179:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  3180: {
1.264     brouard  3181:   /* 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  3182:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   3183:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   3184:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   3185:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   3186:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   3187:   /* Initial matrix pimij */
                   3188:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3189:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3190:   /*  0,                   0                  , 1} */
                   3191:   /*
                   3192:    * and after some iteration: */
                   3193:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3194:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3195:   /*  0,                   0                  , 1} */
                   3196:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3197:   /* {0.51571254859325999, 0.4842874514067399, */
                   3198:   /*  0.51326036147820708, 0.48673963852179264} */
                   3199:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3200: 
1.332     brouard  3201:   int i, ii,j,k, k1;
1.247     brouard  3202:   int first=0;
1.217     brouard  3203:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3204:   /* double **matprod2(); */ /* test */
                   3205:   double **out, cov[NCOVMAX+1], **bmij();
                   3206:   double **newm;
1.218     brouard  3207:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   3208:   double        **oldm, **savm;  /* for use */
                   3209: 
1.217     brouard  3210:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3211:   int ncvloop=0;
                   3212:   
                   3213:   min=vector(1,nlstate);
                   3214:   max=vector(1,nlstate);
                   3215:   meandiff=vector(1,nlstate);
                   3216: 
1.266     brouard  3217:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   3218:   oldm=oldms; savm=savms;
                   3219:   
                   3220:   /* Starting with matrix unity */
                   3221:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3222:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  3223:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3224:     }
                   3225:   
                   3226:   cov[1]=1.;
                   3227:   
                   3228:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3229:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  3230:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  3231:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3232:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  3233:     ncvloop++;
1.218     brouard  3234:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   3235:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  3236:     /* Covariates have to be included here again */
                   3237:     cov[2]=agefin;
1.319     brouard  3238:     if(nagesqr==1){
1.217     brouard  3239:       cov[3]= agefin*agefin;;
1.319     brouard  3240:     }
1.332     brouard  3241:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3242:       if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3243:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  3244:       }else{
1.332     brouard  3245:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  3246:       }
1.332     brouard  3247:     }/* End of loop on model equation */
                   3248: 
                   3249: /* Old code */ 
                   3250: 
                   3251:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   3252:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3253:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   3254:     /*   /\* 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)); *\/ */
                   3255:     /* } */
                   3256:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   3257:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3258:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3259:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   3260:     /* /\* } *\/ */
                   3261:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3262:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3263:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3264:     /*   /\* 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]); *\/ */
                   3265:     /* } */
                   3266:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   3267:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   3268:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   3269:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3270:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3271:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   3272:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3273:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3274:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3275:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3276:     /*   } */
                   3277:     /*   /\* 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]); *\/ */
                   3278:     /* } */
                   3279:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3280:     /*   /\* 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]); *\/ */
                   3281:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3282:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3283:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3284:     /*         }else{ */
                   3285:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3286:     /*         } */
                   3287:     /*   }else{ */
                   3288:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3289:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3290:     /*         }else{ */
                   3291:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3292:     /*         } */
                   3293:     /*   } */
                   3294:     /* } */
1.217     brouard  3295:     
                   3296:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3297:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3298:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3299:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3300:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3301:                /* ij should be linked to the correct index of cov */
                   3302:                /* age and covariate values ij are in 'cov', but we need to pass
                   3303:                 * ij for the observed prevalence at age and status and covariate
                   3304:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3305:                 */
                   3306:     /* 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 *\/ */
                   3307:     /* 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 *\/ */
                   3308:     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  3309:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3310:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3311:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3312:     /*         printf("%d newm= ",i); */
                   3313:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3314:     /*           printf("%f ",newm[i][j]); */
                   3315:     /*         } */
                   3316:     /*         printf("oldm * "); */
                   3317:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3318:     /*           printf("%f ",oldm[i][j]); */
                   3319:     /*         } */
1.268     brouard  3320:     /*         printf(" bmmij "); */
1.266     brouard  3321:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3322:     /*           printf("%f ",pmmij[i][j]); */
                   3323:     /*         } */
                   3324:     /*         printf("\n"); */
                   3325:     /*   } */
                   3326:     /* } */
1.217     brouard  3327:     savm=oldm;
                   3328:     oldm=newm;
1.266     brouard  3329: 
1.217     brouard  3330:     for(j=1; j<=nlstate; j++){
                   3331:       max[j]=0.;
                   3332:       min[j]=1.;
                   3333:     }
                   3334:     for(j=1; j<=nlstate; j++){ 
                   3335:       for(i=1;i<=nlstate;i++){
1.234     brouard  3336:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3337:        bprlim[i][j]= newm[i][j];
                   3338:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3339:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3340:       }
                   3341:     }
1.218     brouard  3342:                
1.217     brouard  3343:     maxmax=0.;
                   3344:     for(i=1; i<=nlstate; i++){
1.318     brouard  3345:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3346:       maxmax=FMAX(maxmax,meandiff[i]);
                   3347:       /* 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  3348:     } /* i loop */
1.217     brouard  3349:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3350:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3351:     if(maxmax < ftolpl){
1.220     brouard  3352:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3353:       free_vector(min,1,nlstate);
                   3354:       free_vector(max,1,nlstate);
                   3355:       free_vector(meandiff,1,nlstate);
                   3356:       return bprlim;
                   3357:     }
1.288     brouard  3358:   } /* agefin loop */
1.217     brouard  3359:     /* After some age loop it doesn't converge */
1.288     brouard  3360:   if(!first){
1.247     brouard  3361:     first=1;
                   3362:     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\
                   3363: 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);
                   3364:   }
                   3365:   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  3366: 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);
                   3367:   /* 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); */
                   3368:   free_vector(min,1,nlstate);
                   3369:   free_vector(max,1,nlstate);
                   3370:   free_vector(meandiff,1,nlstate);
                   3371:   
                   3372:   return bprlim; /* should not reach here */
                   3373: }
                   3374: 
1.126     brouard  3375: /*************** transition probabilities ***************/ 
                   3376: 
                   3377: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3378: {
1.138     brouard  3379:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3380:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3381:      model to the ncovmodel covariates (including constant and age).
                   3382:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3383:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3384:      ncth covariate in the global vector x is given by the formula:
                   3385:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3386:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3387:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3388:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3389:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3390:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3391:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3392:   */
                   3393:   double s1, lnpijopii;
1.126     brouard  3394:   /*double t34;*/
1.164     brouard  3395:   int i,j, nc, ii, jj;
1.126     brouard  3396: 
1.223     brouard  3397:   for(i=1; i<= nlstate; i++){
                   3398:     for(j=1; j<i;j++){
                   3399:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3400:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3401:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3402:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3403:       }
                   3404:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3405:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3406:     }
                   3407:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3408:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3409:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3410:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3411:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3412:       }
                   3413:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3414:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3415:     }
                   3416:   }
1.218     brouard  3417:   
1.223     brouard  3418:   for(i=1; i<= nlstate; i++){
                   3419:     s1=0;
                   3420:     for(j=1; j<i; j++){
1.339     brouard  3421:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3422:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3423:     }
                   3424:     for(j=i+1; j<=nlstate+ndeath; j++){
1.339     brouard  3425:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3426:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3427:     }
                   3428:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3429:     ps[i][i]=1./(s1+1.);
                   3430:     /* Computing other pijs */
                   3431:     for(j=1; j<i; j++)
1.325     brouard  3432:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3433:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3434:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3435:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3436:   } /* end i */
1.218     brouard  3437:   
1.223     brouard  3438:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3439:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3440:       ps[ii][jj]=0;
                   3441:       ps[ii][ii]=1;
                   3442:     }
                   3443:   }
1.294     brouard  3444: 
                   3445: 
1.223     brouard  3446:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3447:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3448:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3449:   /*   } */
                   3450:   /*   printf("\n "); */
                   3451:   /* } */
                   3452:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3453:   /*
                   3454:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3455:                goto end;*/
1.266     brouard  3456:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3457: }
                   3458: 
1.218     brouard  3459: /*************** backward transition probabilities ***************/ 
                   3460: 
                   3461:  /* 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 ) */
                   3462: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3463:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3464: {
1.302     brouard  3465:   /* 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  3466:    * 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  3467:    */
1.218     brouard  3468:   int i, ii, j,k;
1.222     brouard  3469:   
                   3470:   double **out, **pmij();
                   3471:   double sumnew=0.;
1.218     brouard  3472:   double agefin;
1.292     brouard  3473:   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  3474:   double **dnewm, **dsavm, **doldm;
                   3475:   double **bbmij;
                   3476:   
1.218     brouard  3477:   doldm=ddoldms; /* global pointers */
1.222     brouard  3478:   dnewm=ddnewms;
                   3479:   dsavm=ddsavms;
1.318     brouard  3480: 
                   3481:   /* Debug */
                   3482:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3483:   agefin=cov[2];
1.268     brouard  3484:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3485:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3486:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3487:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3488: 
                   3489:   /* P_x */
1.325     brouard  3490:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3491:   /* outputs pmmij which is a stochastic matrix in row */
                   3492: 
                   3493:   /* Diag(w_x) */
1.292     brouard  3494:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3495:   sumnew=0.;
1.269     brouard  3496:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3497:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3498:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3499:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3500:   }
                   3501:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3502:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3503:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3504:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3505:     }
                   3506:   }else{
                   3507:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3508:       for (j=1;j<=nlstate+ndeath;j++)
                   3509:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3510:     }
                   3511:     /* if(sumnew <0.9){ */
                   3512:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3513:     /* } */
                   3514:   }
                   3515:   k3=0.0;  /* We put the last diagonal to 0 */
                   3516:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3517:       doldm[ii][ii]= k3;
                   3518:   }
                   3519:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3520:   
1.292     brouard  3521:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3522:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3523: 
1.292     brouard  3524:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3525:   /* 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  3526:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3527:     sumnew=0.;
1.222     brouard  3528:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3529:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3530:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3531:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3532:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3533:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3534:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3535:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3536:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3537:        /* }else */
1.268     brouard  3538:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3539:     } /*End ii */
                   3540:   } /* 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 */
                   3541: 
1.292     brouard  3542:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3543:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3544:   /* end bmij */
1.266     brouard  3545:   return ps; /*pointer is unchanged */
1.218     brouard  3546: }
1.217     brouard  3547: /*************** transition probabilities ***************/ 
                   3548: 
1.218     brouard  3549: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3550: {
                   3551:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3552:      computes the probability to be observed in state j being in state i by appying the
                   3553:      model to the ncovmodel covariates (including constant and age).
                   3554:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3555:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3556:      ncth covariate in the global vector x is given by the formula:
                   3557:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3558:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3559:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3560:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3561:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3562:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3563:   */
                   3564:   double s1, lnpijopii;
                   3565:   /*double t34;*/
                   3566:   int i,j, nc, ii, jj;
                   3567: 
1.234     brouard  3568:   for(i=1; i<= nlstate; i++){
                   3569:     for(j=1; j<i;j++){
                   3570:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3571:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3572:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3573:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3574:       }
                   3575:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3576:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3577:     }
                   3578:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3579:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3580:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3581:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3582:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3583:       }
                   3584:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3585:     }
                   3586:   }
                   3587:   
                   3588:   for(i=1; i<= nlstate; i++){
                   3589:     s1=0;
                   3590:     for(j=1; j<i; j++){
                   3591:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3592:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3593:     }
                   3594:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3595:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3596:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3597:     }
                   3598:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3599:     ps[i][i]=1./(s1+1.);
                   3600:     /* Computing other pijs */
                   3601:     for(j=1; j<i; j++)
                   3602:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3603:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3604:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3605:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3606:   } /* end i */
                   3607:   
                   3608:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3609:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3610:       ps[ii][jj]=0;
                   3611:       ps[ii][ii]=1;
                   3612:     }
                   3613:   }
1.296     brouard  3614:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3615:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3616:     s1=0.;
                   3617:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3618:       s1+=ps[ii][jj];
                   3619:     }
                   3620:     for(ii=1; ii<= nlstate; ii++){
                   3621:       ps[ii][jj]=ps[ii][jj]/s1;
                   3622:     }
                   3623:   }
                   3624:   /* Transposition */
                   3625:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3626:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3627:       s1=ps[ii][jj];
                   3628:       ps[ii][jj]=ps[jj][ii];
                   3629:       ps[jj][ii]=s1;
                   3630:     }
                   3631:   }
                   3632:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3633:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3634:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3635:   /*   } */
                   3636:   /*   printf("\n "); */
                   3637:   /* } */
                   3638:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3639:   /*
                   3640:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3641:     goto end;*/
                   3642:   return ps;
1.217     brouard  3643: }
                   3644: 
                   3645: 
1.126     brouard  3646: /**************** Product of 2 matrices ******************/
                   3647: 
1.145     brouard  3648: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3649: {
                   3650:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3651:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3652:   /* in, b, out are matrice of pointers which should have been initialized 
                   3653:      before: only the contents of out is modified. The function returns
                   3654:      a pointer to pointers identical to out */
1.145     brouard  3655:   int i, j, k;
1.126     brouard  3656:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3657:     for(k=ncolol; k<=ncoloh; k++){
                   3658:       out[i][k]=0.;
                   3659:       for(j=ncl; j<=nch; j++)
                   3660:        out[i][k] +=in[i][j]*b[j][k];
                   3661:     }
1.126     brouard  3662:   return out;
                   3663: }
                   3664: 
                   3665: 
                   3666: /************* Higher Matrix Product ***************/
                   3667: 
1.235     brouard  3668: 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  3669: {
1.336     brouard  3670:   /* Already optimized with precov.
                   3671:      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  3672:      'nhstepm*hstepm*stepm' months (i.e. until
                   3673:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3674:      nhstepm*hstepm matrices. 
                   3675:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3676:      (typically every 2 years instead of every month which is too big 
                   3677:      for the memory).
                   3678:      Model is determined by parameters x and covariates have to be 
                   3679:      included manually here. 
                   3680: 
                   3681:      */
                   3682: 
1.330     brouard  3683:   int i, j, d, h, k, k1;
1.131     brouard  3684:   double **out, cov[NCOVMAX+1];
1.126     brouard  3685:   double **newm;
1.187     brouard  3686:   double agexact;
1.214     brouard  3687:   double agebegin, ageend;
1.126     brouard  3688: 
                   3689:   /* Hstepm could be zero and should return the unit matrix */
                   3690:   for (i=1;i<=nlstate+ndeath;i++)
                   3691:     for (j=1;j<=nlstate+ndeath;j++){
                   3692:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3693:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3694:     }
                   3695:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3696:   for(h=1; h <=nhstepm; h++){
                   3697:     for(d=1; d <=hstepm; d++){
                   3698:       newm=savm;
                   3699:       /* Covariates have to be included here again */
                   3700:       cov[1]=1.;
1.214     brouard  3701:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3702:       cov[2]=agexact;
1.319     brouard  3703:       if(nagesqr==1){
1.227     brouard  3704:        cov[3]= agexact*agexact;
1.319     brouard  3705:       }
1.330     brouard  3706:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3707:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3708:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3709:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3710:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3711:        }else{
                   3712:          cov[2+nagesqr+k1]=precov[nres][k1];
                   3713:        }
                   3714:       }/* End of loop on model equation */
                   3715:        /* Old code */ 
                   3716: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   3717: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   3718: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   3719: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   3720: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   3721: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3722: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3723: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   3724: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   3725: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   3726: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   3727: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   3728: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   3729: /*       /\* 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]])); *\/ */
                   3730: /*       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); */
                   3731: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3732: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   3733: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   3734: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   3735: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   3736: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   3737: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3738: /*       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]]); */
                   3739: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3740: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   3741: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   3742: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   3743: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   3744: /*       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]); */
                   3745: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3746: 
                   3747: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   3748: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   3749: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   3750: /*       /\* *\/ */
1.330     brouard  3751: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3752: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3753: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  3754: /* /\*cptcovage=2                   1               2      *\/ */
                   3755: /* /\*Tage[k]=                      5               8      *\/  */
                   3756: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   3757: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   3758: /*       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]]); */
                   3759: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3760: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   3761: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   3762: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   3763: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   3764: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   3765: /*       /\*   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); *\/ */
                   3766: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   3767: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   3768: /*       /\* } *\/ */
                   3769: /*       /\* 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]); *\/ */
                   3770: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   3771: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   3772: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   3773: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   3774: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   3775: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   3776: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   3777: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   3778: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  3779:          
1.332     brouard  3780: /*       /\* 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])]); *\/ */
                   3781: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3782: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   3783: /*       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]]); */
                   3784: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3785: 
                   3786: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   3787: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   3788: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3789: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   3790: /*           /\* 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]])]; *\/ */
                   3791: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   3792: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   3793: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   3794: /*       /\*   } *\/ */
                   3795: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   3796: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   3797: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   3798: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3799: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   3800: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   3801: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3802: /*       /\*   } *\/ */
                   3803: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   3804: /*     }/\*end of products *\/ */
                   3805:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  3806:       /* for (k=1; k<=cptcovn;k++)  */
                   3807:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3808:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3809:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3810:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3811:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3812:       
                   3813:       
1.126     brouard  3814:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3815:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3816:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3817:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3818:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3819:       /* if((int)age == 70){ */
                   3820:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3821:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3822:       /*         printf("%d pmmij ",i); */
                   3823:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3824:       /*           printf("%f ",pmmij[i][j]); */
                   3825:       /*         } */
                   3826:       /*         printf(" oldm "); */
                   3827:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3828:       /*           printf("%f ",oldm[i][j]); */
                   3829:       /*         } */
                   3830:       /*         printf("\n"); */
                   3831:       /*       } */
                   3832:       /* } */
1.126     brouard  3833:       savm=oldm;
                   3834:       oldm=newm;
                   3835:     }
                   3836:     for(i=1; i<=nlstate+ndeath; i++)
                   3837:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3838:        po[i][j][h]=newm[i][j];
                   3839:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3840:       }
1.128     brouard  3841:     /*printf("h=%d ",h);*/
1.126     brouard  3842:   } /* end h */
1.267     brouard  3843:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3844:   return po;
                   3845: }
                   3846: 
1.217     brouard  3847: /************* Higher Back Matrix Product ***************/
1.218     brouard  3848: /* 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  3849: 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  3850: {
1.332     brouard  3851:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   3852:      computes the transition matrix starting at age 'age' over
1.217     brouard  3853:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3854:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3855:      nhstepm*hstepm matrices.
                   3856:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3857:      (typically every 2 years instead of every month which is too big
1.217     brouard  3858:      for the memory).
1.218     brouard  3859:      Model is determined by parameters x and covariates have to be
1.266     brouard  3860:      included manually here. Then we use a call to bmij(x and cov)
                   3861:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3862:   */
1.217     brouard  3863: 
1.332     brouard  3864:   int i, j, d, h, k, k1;
1.266     brouard  3865:   double **out, cov[NCOVMAX+1], **bmij();
                   3866:   double **newm, ***newmm;
1.217     brouard  3867:   double agexact;
                   3868:   double agebegin, ageend;
1.222     brouard  3869:   double **oldm, **savm;
1.217     brouard  3870: 
1.266     brouard  3871:   newmm=po; /* To be saved */
                   3872:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3873:   /* Hstepm could be zero and should return the unit matrix */
                   3874:   for (i=1;i<=nlstate+ndeath;i++)
                   3875:     for (j=1;j<=nlstate+ndeath;j++){
                   3876:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3877:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3878:     }
                   3879:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3880:   for(h=1; h <=nhstepm; h++){
                   3881:     for(d=1; d <=hstepm; d++){
                   3882:       newm=savm;
                   3883:       /* Covariates have to be included here again */
                   3884:       cov[1]=1.;
1.271     brouard  3885:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3886:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3887:         /* Debug */
                   3888:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3889:       cov[2]=agexact;
1.332     brouard  3890:       if(nagesqr==1){
1.222     brouard  3891:        cov[3]= agexact*agexact;
1.332     brouard  3892:       }
                   3893:       /** New code */
                   3894:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3895:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3896:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  3897:        }else{
1.332     brouard  3898:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  3899:        }
1.332     brouard  3900:       }/* End of loop on model equation */
                   3901:       /** End of new code */
                   3902:   /** This was old code */
                   3903:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   3904:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3905:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3906:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   3907:       /*   /\* 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)); *\/ */
                   3908:       /* } */
                   3909:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3910:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3911:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3912:       /*       /\* 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]); *\/ */
                   3913:       /* } */
                   3914:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   3915:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   3916:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3917:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3918:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3919:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   3920:       /*       } */
                   3921:       /*       /\* 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]); *\/ */
                   3922:       /* } */
                   3923:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   3924:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3925:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   3926:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3927:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   3928:       /*         }else{ */
                   3929:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3930:       /*         } */
                   3931:       /*       }else{ */
                   3932:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3933:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3934:       /*         }else{ */
                   3935:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3936:       /*         } */
                   3937:       /*       } */
                   3938:       /* }                      */
                   3939:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   3940:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   3941: /** End of old code */
                   3942:       
1.218     brouard  3943:       /* Careful transposed matrix */
1.266     brouard  3944:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3945:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3946:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3947:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3948:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3949:       /* if((int)age == 70){ */
                   3950:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3951:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3952:       /*         printf("%d pmmij ",i); */
                   3953:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3954:       /*           printf("%f ",pmmij[i][j]); */
                   3955:       /*         } */
                   3956:       /*         printf(" oldm "); */
                   3957:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3958:       /*           printf("%f ",oldm[i][j]); */
                   3959:       /*         } */
                   3960:       /*         printf("\n"); */
                   3961:       /*       } */
                   3962:       /* } */
                   3963:       savm=oldm;
                   3964:       oldm=newm;
                   3965:     }
                   3966:     for(i=1; i<=nlstate+ndeath; i++)
                   3967:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3968:        po[i][j][h]=newm[i][j];
1.268     brouard  3969:        /* if(h==nhstepm) */
                   3970:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3971:       }
1.268     brouard  3972:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3973:   } /* end h */
1.268     brouard  3974:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3975:   return po;
                   3976: }
                   3977: 
                   3978: 
1.162     brouard  3979: #ifdef NLOPT
                   3980:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3981:   double fret;
                   3982:   double *xt;
                   3983:   int j;
                   3984:   myfunc_data *d2 = (myfunc_data *) pd;
                   3985: /* xt = (p1-1); */
                   3986:   xt=vector(1,n); 
                   3987:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3988: 
                   3989:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3990:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3991:   printf("Function = %.12lf ",fret);
                   3992:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3993:   printf("\n");
                   3994:  free_vector(xt,1,n);
                   3995:   return fret;
                   3996: }
                   3997: #endif
1.126     brouard  3998: 
                   3999: /*************** log-likelihood *************/
                   4000: double func( double *x)
                   4001: {
1.336     brouard  4002:   int i, ii, j, k, mi, d, kk, kf=0;
1.226     brouard  4003:   int ioffset=0;
1.339     brouard  4004:   int ipos=0,iposold=0,ncovv=0;
                   4005: 
1.340     brouard  4006:   double cotvarv, cotvarvold;
1.226     brouard  4007:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   4008:   double **out;
                   4009:   double lli; /* Individual log likelihood */
                   4010:   int s1, s2;
1.228     brouard  4011:   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  4012: 
1.226     brouard  4013:   double bbh, survp;
                   4014:   double agexact;
1.336     brouard  4015:   double agebegin, ageend;
1.226     brouard  4016:   /*extern weight */
                   4017:   /* We are differentiating ll according to initial status */
                   4018:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4019:   /*for(i=1;i<imx;i++) 
                   4020:     printf(" %d\n",s[4][i]);
                   4021:   */
1.162     brouard  4022: 
1.226     brouard  4023:   ++countcallfunc;
1.162     brouard  4024: 
1.226     brouard  4025:   cov[1]=1.;
1.126     brouard  4026: 
1.226     brouard  4027:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4028:   ioffset=0;
1.226     brouard  4029:   if(mle==1){
                   4030:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4031:       /* Computes the values of the ncovmodel covariates of the model
                   4032:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4033:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4034:         to be observed in j being in i according to the model.
                   4035:       */
1.243     brouard  4036:       ioffset=2+nagesqr ;
1.233     brouard  4037:    /* Fixed */
1.345     brouard  4038:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummy or quant or prod */
1.319     brouard  4039:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   4040:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   4041:        /*  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  4042:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.336     brouard  4043:        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  4044:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  4045:       }
1.226     brouard  4046:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  4047:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  4048:         has been calculated etc */
                   4049:       /* For an individual i, wav[i] gives the number of effective waves */
                   4050:       /* We compute the contribution to Likelihood of each effective transition
                   4051:         mw[mi][i] is real wave of the mi th effectve wave */
                   4052:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4053:         s2=s[mw[mi+1][i]][i];
1.341     brouard  4054:         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  4055:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   4056:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   4057:       */
1.336     brouard  4058:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   4059:       /* Wave varying (but not age varying) */
1.339     brouard  4060:        /* 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*\/ */
                   4061:        /*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
                   4062:        /*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4063:        /* } */
1.340     brouard  4064:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
                   4065:          itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4066:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  4067:          if(FixedV[itv]!=0){ /* Not a fixed covariate */
1.341     brouard  4068:            cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* cotvar[wav][ncovcol+nqv+iv][i] */
1.340     brouard  4069:          }else{ /* fixed covariate */
1.345     brouard  4070:            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  4071:          }
1.339     brouard  4072:          if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  4073:            cotvarvold=cotvarv;
                   4074:          }else{ /* A second product */
                   4075:            cotvarv=cotvarv*cotvarvold;
1.339     brouard  4076:          }
                   4077:          iposold=ipos;
1.340     brouard  4078:          cov[ioffset+ipos]=cotvarv;
1.234     brouard  4079:        }
1.339     brouard  4080:        /* for products of time varying to be done */
1.234     brouard  4081:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4082:          for (j=1;j<=nlstate+ndeath;j++){
                   4083:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4084:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4085:          }
1.336     brouard  4086: 
                   4087:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4088:        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  4089:        for(d=0; d<dh[mi][i]; d++){
                   4090:          newm=savm;
                   4091:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4092:          cov[2]=agexact;
                   4093:          if(nagesqr==1)
                   4094:            cov[3]= agexact*agexact;  /* Should be changed here */
1.349     brouard  4095:          /* for (kk=1; kk<=cptcovage;kk++) { */
                   4096:          /*   if(!FixedV[Tvar[Tage[kk]]]) */
                   4097:          /*     cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /\* Tage[kk] gives the data-covariate associated with age *\/ */
                   4098:          /*   else */
                   4099:          /*     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) *\/  */
                   4100:          /* } */
                   4101:          for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   4102:            itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   4103:            ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4104:            if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4105:              cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   4106:            }else{ /* fixed covariate */
                   4107:              cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4108:            }
                   4109:            if(ipos!=iposold){ /* Not a product or first of a product */
                   4110:              cotvarvold=cotvarv;
                   4111:            }else{ /* A second product */
                   4112:              cotvarv=cotvarv*cotvarvold;
                   4113:            }
                   4114:            iposold=ipos;
                   4115:            cov[ioffset+ipos]=cotvarv*agexact;
                   4116:            /* For products */
1.234     brouard  4117:          }
1.349     brouard  4118:          
1.234     brouard  4119:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4120:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4121:          savm=oldm;
                   4122:          oldm=newm;
                   4123:        } /* end mult */
                   4124:        
                   4125:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4126:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4127:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4128:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4129:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4130:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4131:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4132:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  4133:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4134:                                 * -stepm/2 to stepm/2 .
                   4135:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4136:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4137:                                 */
1.234     brouard  4138:        s1=s[mw[mi][i]][i];
                   4139:        s2=s[mw[mi+1][i]][i];
                   4140:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4141:        /* bias bh is positive if real duration
                   4142:         * is higher than the multiple of stepm and negative otherwise.
                   4143:         */
                   4144:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   4145:        if( s2 > nlstate){ 
                   4146:          /* i.e. if s2 is a death state and if the date of death is known 
                   4147:             then the contribution to the likelihood is the probability to 
                   4148:             die between last step unit time and current  step unit time, 
                   4149:             which is also equal to probability to die before dh 
                   4150:             minus probability to die before dh-stepm . 
                   4151:             In version up to 0.92 likelihood was computed
                   4152:             as if date of death was unknown. Death was treated as any other
                   4153:             health state: the date of the interview describes the actual state
                   4154:             and not the date of a change in health state. The former idea was
                   4155:             to consider that at each interview the state was recorded
                   4156:             (healthy, disable or death) and IMaCh was corrected; but when we
                   4157:             introduced the exact date of death then we should have modified
                   4158:             the contribution of an exact death to the likelihood. This new
                   4159:             contribution is smaller and very dependent of the step unit
                   4160:             stepm. It is no more the probability to die between last interview
                   4161:             and month of death but the probability to survive from last
                   4162:             interview up to one month before death multiplied by the
                   4163:             probability to die within a month. Thanks to Chris
                   4164:             Jackson for correcting this bug.  Former versions increased
                   4165:             mortality artificially. The bad side is that we add another loop
                   4166:             which slows down the processing. The difference can be up to 10%
                   4167:             lower mortality.
                   4168:          */
                   4169:          /* If, at the beginning of the maximization mostly, the
                   4170:             cumulative probability or probability to be dead is
                   4171:             constant (ie = 1) over time d, the difference is equal to
                   4172:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   4173:             s1 at precedent wave, to be dead a month before current
                   4174:             wave is equal to probability, being at state s1 at
                   4175:             precedent wave, to be dead at mont of the current
                   4176:             wave. Then the observed probability (that this person died)
                   4177:             is null according to current estimated parameter. In fact,
                   4178:             it should be very low but not zero otherwise the log go to
                   4179:             infinity.
                   4180:          */
1.183     brouard  4181: /* #ifdef INFINITYORIGINAL */
                   4182: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4183: /* #else */
                   4184: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   4185: /*         lli=log(mytinydouble); */
                   4186: /*       else */
                   4187: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4188: /* #endif */
1.226     brouard  4189:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4190:          
1.226     brouard  4191:        } else if  ( s2==-1 ) { /* alive */
                   4192:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4193:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4194:          /*survp += out[s1][j]; */
                   4195:          lli= log(survp);
                   4196:        }
1.336     brouard  4197:        /* else if  (s2==-4) {  */
                   4198:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
                   4199:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4200:        /*   lli= log(survp);  */
                   4201:        /* }  */
                   4202:        /* else if  (s2==-5) {  */
                   4203:        /*   for (j=1,survp=0. ; j<=2; j++)   */
                   4204:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4205:        /*   lli= log(survp);  */
                   4206:        /* }  */
1.226     brouard  4207:        else{
                   4208:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4209:          /*  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 */
                   4210:        } 
                   4211:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   4212:        /*if(lli ==000.0)*/
1.340     brouard  4213:        /* 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  4214:        ipmx +=1;
                   4215:        sw += weight[i];
                   4216:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4217:        /* if (lli < log(mytinydouble)){ */
                   4218:        /*   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); */
                   4219:        /*   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]); */
                   4220:        /* } */
                   4221:       } /* end of wave */
                   4222:     } /* end of individual */
                   4223:   }  else if(mle==2){
                   4224:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  4225:       ioffset=2+nagesqr ;
                   4226:       for (k=1; k<=ncovf;k++)
                   4227:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  4228:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  4229:        for(k=1; k <= ncovv ; k++){
1.341     brouard  4230:          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  4231:        }
1.226     brouard  4232:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4233:          for (j=1;j<=nlstate+ndeath;j++){
                   4234:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4235:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4236:          }
                   4237:        for(d=0; d<=dh[mi][i]; d++){
                   4238:          newm=savm;
                   4239:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4240:          cov[2]=agexact;
                   4241:          if(nagesqr==1)
                   4242:            cov[3]= agexact*agexact;
                   4243:          for (kk=1; kk<=cptcovage;kk++) {
                   4244:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4245:          }
                   4246:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4247:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4248:          savm=oldm;
                   4249:          oldm=newm;
                   4250:        } /* end mult */
                   4251:       
                   4252:        s1=s[mw[mi][i]][i];
                   4253:        s2=s[mw[mi+1][i]][i];
                   4254:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4255:        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 */
                   4256:        ipmx +=1;
                   4257:        sw += weight[i];
                   4258:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4259:       } /* end of wave */
                   4260:     } /* end of individual */
                   4261:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   4262:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4263:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4264:       for(mi=1; mi<= wav[i]-1; mi++){
                   4265:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4266:          for (j=1;j<=nlstate+ndeath;j++){
                   4267:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4268:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4269:          }
                   4270:        for(d=0; d<dh[mi][i]; d++){
                   4271:          newm=savm;
                   4272:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4273:          cov[2]=agexact;
                   4274:          if(nagesqr==1)
                   4275:            cov[3]= agexact*agexact;
                   4276:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4277:            if(!FixedV[Tvar[Tage[kk]]])
                   4278:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4279:            else
1.341     brouard  4280:              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  4281:          }
                   4282:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4283:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4284:          savm=oldm;
                   4285:          oldm=newm;
                   4286:        } /* end mult */
                   4287:       
                   4288:        s1=s[mw[mi][i]][i];
                   4289:        s2=s[mw[mi+1][i]][i];
                   4290:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4291:        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 */
                   4292:        ipmx +=1;
                   4293:        sw += weight[i];
                   4294:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4295:       } /* end of wave */
                   4296:     } /* end of individual */
                   4297:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   4298:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4299:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4300:       for(mi=1; mi<= wav[i]-1; mi++){
                   4301:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4302:          for (j=1;j<=nlstate+ndeath;j++){
                   4303:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4304:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4305:          }
                   4306:        for(d=0; d<dh[mi][i]; d++){
                   4307:          newm=savm;
                   4308:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4309:          cov[2]=agexact;
                   4310:          if(nagesqr==1)
                   4311:            cov[3]= agexact*agexact;
                   4312:          for (kk=1; kk<=cptcovage;kk++) {
                   4313:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4314:          }
1.126     brouard  4315:        
1.226     brouard  4316:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4317:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4318:          savm=oldm;
                   4319:          oldm=newm;
                   4320:        } /* end mult */
                   4321:       
                   4322:        s1=s[mw[mi][i]][i];
                   4323:        s2=s[mw[mi+1][i]][i];
                   4324:        if( s2 > nlstate){ 
                   4325:          lli=log(out[s1][s2] - savm[s1][s2]);
                   4326:        } else if  ( s2==-1 ) { /* alive */
                   4327:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4328:            survp += out[s1][j];
                   4329:          lli= log(survp);
                   4330:        }else{
                   4331:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4332:        }
                   4333:        ipmx +=1;
                   4334:        sw += weight[i];
                   4335:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.343     brouard  4336:        /* 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  4337:       } /* end of wave */
                   4338:     } /* end of individual */
                   4339:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4340:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4341:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4342:       for(mi=1; mi<= wav[i]-1; mi++){
                   4343:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4344:          for (j=1;j<=nlstate+ndeath;j++){
                   4345:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4346:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4347:          }
                   4348:        for(d=0; d<dh[mi][i]; d++){
                   4349:          newm=savm;
                   4350:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4351:          cov[2]=agexact;
                   4352:          if(nagesqr==1)
                   4353:            cov[3]= agexact*agexact;
                   4354:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4355:            if(!FixedV[Tvar[Tage[kk]]])
                   4356:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4357:            else
1.341     brouard  4358:              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  4359:          }
1.126     brouard  4360:        
1.226     brouard  4361:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4362:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4363:          savm=oldm;
                   4364:          oldm=newm;
                   4365:        } /* end mult */
                   4366:       
                   4367:        s1=s[mw[mi][i]][i];
                   4368:        s2=s[mw[mi+1][i]][i];
                   4369:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4370:        ipmx +=1;
                   4371:        sw += weight[i];
                   4372:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4373:        /*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]);*/
                   4374:       } /* end of wave */
                   4375:     } /* end of individual */
                   4376:   } /* End of if */
                   4377:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4378:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4379:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4380:   return -l;
1.126     brouard  4381: }
                   4382: 
                   4383: /*************** log-likelihood *************/
                   4384: double funcone( double *x)
                   4385: {
1.228     brouard  4386:   /* Same as func but slower because of a lot of printf and if */
1.349     brouard  4387:   int i, ii, j, k, mi, d, kk, kv=0, kf=0;
1.228     brouard  4388:   int ioffset=0;
1.339     brouard  4389:   int ipos=0,iposold=0,ncovv=0;
                   4390: 
1.340     brouard  4391:   double cotvarv, cotvarvold;
1.131     brouard  4392:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  4393:   double **out;
                   4394:   double lli; /* Individual log likelihood */
                   4395:   double llt;
                   4396:   int s1, s2;
1.228     brouard  4397:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4398: 
1.126     brouard  4399:   double bbh, survp;
1.187     brouard  4400:   double agexact;
1.214     brouard  4401:   double agebegin, ageend;
1.126     brouard  4402:   /*extern weight */
                   4403:   /* We are differentiating ll according to initial status */
                   4404:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4405:   /*for(i=1;i<imx;i++) 
                   4406:     printf(" %d\n",s[4][i]);
                   4407:   */
                   4408:   cov[1]=1.;
                   4409: 
                   4410:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4411:   ioffset=0;
                   4412:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.336     brouard  4413:     /* Computes the values of the ncovmodel covariates of the model
                   4414:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4415:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4416:        to be observed in j being in i according to the model.
                   4417:     */
1.243     brouard  4418:     /* ioffset=2+nagesqr+cptcovage; */
                   4419:     ioffset=2+nagesqr;
1.232     brouard  4420:     /* Fixed */
1.224     brouard  4421:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4422:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.349     brouard  4423:     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  4424:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
                   4425:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
                   4426:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
1.335     brouard  4427:       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  4428: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4429: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4430: /*    cov[2+6]=covar[2][i]; V2  */
                   4431: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4432: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4433: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4434: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4435: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4436: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4437:     }
1.336     brouard  4438:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   4439:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   4440:         has been calculated etc */
                   4441:       /* For an individual i, wav[i] gives the number of effective waves */
                   4442:       /* We compute the contribution to Likelihood of each effective transition
                   4443:         mw[mi][i] is real wave of the mi th effectve wave */
                   4444:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4445:         s2=s[mw[mi+1][i]][i];
1.341     brouard  4446:         And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][ncovcol+nqv+iv][i]
1.336     brouard  4447:       */
                   4448:     /* This part may be useless now because everythin should be in covar */
1.232     brouard  4449:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4450:     /*   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?)*\/ */
                   4451:     /* } */
1.231     brouard  4452:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4453:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4454:     /* } */
1.225     brouard  4455:     
1.233     brouard  4456: 
                   4457:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.339     brouard  4458:       /* 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 */
                   4459:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
                   4460:       /*       /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
                   4461:       /*       cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4462:       /* } */
                   4463:       
                   4464:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   4465:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   4466:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   4467:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
                   4468:       /* We need the position of the time varying or product in the model */
                   4469:       /* 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 */            
                   4470:       /* TvarVV gives the variable name */
1.340     brouard  4471:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   4472:       *      k=         1   2     3     4         5        6        7       8        9
                   4473:       *  varying            1     2                                 3       4        5
                   4474:       *  ncovv              1     2                                3 4     5 6      7 8
1.343     brouard  4475:       * TvarVV[ncovv]      V3     5                                1 3     3 5      1 5
1.340     brouard  4476:       * TvarVVind           2     3                                7 7     8 8      9 9
                   4477:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
                   4478:       */
1.345     brouard  4479:       /* Other model ncovcol=5 nqv=0 ntv=3 nqtv=0 nlstate=3
1.349     brouard  4480:        * 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  4481:        * FixedV[ncovcol+qv+ntv+nqtv]       V5
1.349     brouard  4482:        * 3           V1  V2     V3    V4   V5 V6     V7  V8 V3*V2 V7*V2  V6*V3 V7*V3 V6*V4 V7*V4
                   4483:        *             0   0      0      0    0  1      1   1  0, 0, 1,1,   1, 0, 1, 0, 1, 0, 1, 0}
                   4484:        * 3           0   0      0      0    0  1      1   1  0,     1      1    1      1    1}
                   4485:        * model=          V2  +  V3  +  V4  +  V6  +  V7  +  V6*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4486:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4487:         *                +age*V6*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4488:        * model2=          V2  +  V3  +  V4  +  V6  +  V7  +  V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4489:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4490:         *                +age*V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4491:        * model3=          V2  +  V3  +  V4  +  V6  +  V7  + age*V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4492:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4493:         *                +V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4494:        * kmodel           1     2      3      4      5        6         7         8         9        10        11    
                   4495:        *                  12       13      14      15       16
                   4496:        *                    17        18         19        20         21
                   4497:        * Tvar[kmodel]     2     3      4      6      7        9        10        11        12        13        14
                   4498:        *                   2       3        4       6        7
                   4499:        *                     9         11          12        13         14            
                   4500:        * cptcovage=5+5 total of covariates with age 
                   4501:        * Tage[cptcovage] age*V2=12      13      14      15       16
                   4502:        *1                   17            18         19        20         21 gives the position in model of covariates associated with age
                   4503:        *3 Tage[cptcovage] age*V3*V2=6  
                   4504:        *3                age*V2=12         13      14      15       16
                   4505:        *3                age*V6*V3=18      19    20   21
                   4506:        * Tvar[Tage[cptcovage]]    Tvar[12]=2      3      4       6         Tvar[16]=7(age*V7)
                   4507:        *     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
                   4508:        * 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
                   4509:        * 3 Tvar[Tage[cptcovage]]    Tvar[6]=9      Tvar[12]=2      3     4       6         Tvar[16]=7(age*V7)
                   4510:        * 3     Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
                   4511:        * 3 Tage[cptcovage] age*V3*V2=6   age*V2=12 age*V3 13    14      15       16
                   4512:        *                    age*V6*V3=18         19        20         21 gives the position in model of covariates associated with age
                   4513:        * 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
                   4514:        * Tvar=                {2, 3, 4, 6, 7,
                   4515:        *                       9, 10, 11, 12, 13, 14,
                   4516:        *              Tvar[12]=2, 3, 4, 6, 7,
                   4517:        *              Tvar[17]=9, 11, 12, 13, 14}
                   4518:        * Typevar[1]@21 = {0, 0, 0, 0, 0,
                   4519:        *                  2, 2, 2, 2, 2, 2,
                   4520:        * 3                3, 2, 2, 2, 2, 2,
                   4521:        *                  1, 1, 1, 1, 1, 
                   4522:        *                  3, 3, 3, 3, 3}
                   4523:        * 3                 2, 3, 3, 3, 3}
                   4524:        * 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
                   4525:        * p Tprod[1]@21 {6, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   4526:        * 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}
                   4527:        * 3 Tprod[1]@21 {17, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   4528:        * cptcovprod=11 (6+5)
                   4529:        * FixedV[Tvar[Tage[cptcovage]]]]  FixedV[2]=0      FixedV[3]=0      0      1          (age*V7)Tvar[16]=1 FixedV[absolute] not [kmodel]
                   4530:        *   FixedV[Tvar[17]=FixedV[age*V6*V2]=FixedV[9]=1        1         1          1         1  
                   4531:        * 3 FixedV[Tvar[17]=FixedV[age*V3*V2]=FixedV[9]=0        [11]=1         1          1         1  
                   4532:        * FixedV[]          V1=0     V2=0   V3=0  v4=0    V5=0  V6=1    V7=1 v8=1  OK then model dependent
                   4533:        *                   9=1  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   4534:        * 3                 9=0  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   4535:        * cptcovdageprod=5  for gnuplot printing
                   4536:        * cptcovprodvage=6 
                   4537:        * ncova=15           1        2       3       4       5
                   4538:        *                      6 7        8 9      10 11        12 13     14 15
                   4539:        * TvarA              2        3       4       6       7
                   4540:        *                      6 2        6 7       7 3          6 4       7 4
                   4541:        * TvaAind             12 12      13 13     14 14      15 15       16 16        
1.345     brouard  4542:        * ncovf            1     2      3
1.349     brouard  4543:        *                                    V6       V7      V6*V2     V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   4544:        * ncovvt=14                            1      2        3 4       5 6       7 8       9 10     11 12     13 14     
                   4545:        * TvarVV[1]@14 = itv               {V6=6,     7, V6*V2=6, 2,     7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   4546:        * TvarVVind[1]@14=                    {4,     5,       6, 6,     7, 7,     8, 8,      9, 9,   10, 10,   11, 11}
                   4547:        * 3 ncovvt=12                        V6       V7      V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   4548:        * 3 TvarVV[1]@12 = itv                {6,     7, V7*V2=7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   4549:        * 3                                    1      2        3  4      5  6      7  8      9 10     11 12
                   4550:        * TvarVVind[1]@12=         {V6 is in k=4,     5,  7,(4isV2)=7,   8, 8,      9, 9,   10,10,    11,11}TvarVVind[12]=k=11
                   4551:        * TvarV              6, 7, 9, 10, 11, 12, 13, 14
                   4552:        * 3 cptcovprodvage=6
                   4553:        * 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
                   4554:        * 3 TvarAVVA[1]@15= itva 3 2    2      3    4        6       7        6 3         7 3         6 4         7 4 
                   4555:        * 3 ncovta             1 2      3      4    5        6       7        8 9       10 11       12 13        14 15
1.354   ! brouard  4556:        *?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  4557:        * TvarAVVAind[1]@15= V3 is in k=6 6 12  13   14      15      16       18 18       19,19,     20,20        21,21}TvarVVAind[]
                   4558:        * 3 ncovvta=10     +age*V6 + age*V7 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4559:        * 3 we want to compute =cotvar[mw[mi][i]][TvarVVA[ncovva]][i] at position TvarVVAind[ncovva]
                   4560:        * 3 TvarVVA[1]@10= itva   6       7        6 3         7 3         6 4         7 4 
                   4561:        * 3 ncovva                1       2        3 4         5 6         7 8         9 10
                   4562:        * TvarVVAind[1]@10= V6 is in k=4  5        8,8         9, 9,      10,10        11 11}TvarVVAind[]
                   4563:        * TvarVVAind[1]@10=       15       16     18,18        19,19,      20,20        21 21}TvarVVAind[]
                   4564:        * TvarVA              V3*V2=6 6 , 1, 2, 11, 12, 13, 14
1.345     brouard  4565:        * TvarFind[1]@14= {1,    2,     3,     0 <repeats 12 times>}
1.349     brouard  4566:        * Tvar[1]@21=     {2,    3,     4,    6,      7,      9,      10,        11,       12,      13,       14,
                   4567:        *                   2, 3, 4, 6, 7,
                   4568:        *                     6, 8, 9, 10, 11}
1.345     brouard  4569:        * TvarFind[itv]                        0      0       0
                   4570:        * FixedV[itv]                          1      1       1  0      1 0       1 0       1 0       0
1.354   ! brouard  4571:        *? FixedV[itv]                          1      1       1  0      1 0       1 0       1 0      1 0     1 0
1.345     brouard  4572:        * Tvar[TvarFind[ncovf]]=[1]=2 [2]=3 [4]=4
                   4573:        * Tvar[TvarFind[itv]]                [0]=?      ?ncovv 1 à ncovvt]
                   4574:        *   Not a fixed cotvar[mw][itv][i]     6       7      6  2      7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
1.349     brouard  4575:        *   fixed covar[itv]                  [6]     [7]    [6][2] 
1.345     brouard  4576:        */
                   4577: 
1.349     brouard  4578:       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 */
                   4579:        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  4580:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  4581:        /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4582:        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  4583:          /* printf("DEBUG ncovv=%d, Varying TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
1.345     brouard  4584:          cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
1.354   ! brouard  4585:          /* printf("DEBUG Varying cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
1.340     brouard  4586:        }else{ /* fixed covariate */
1.345     brouard  4587:          /* 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  4588:          /* printf("DEBUG ncovv=%d, Fixed TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
1.349     brouard  4589:          cotvarv=covar[itv][i];  /* Good: In V6*V3, 3 is fixed at position of the data */
1.354   ! brouard  4590:          /* printf("DEBUG Fixed cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
1.340     brouard  4591:        }
1.339     brouard  4592:        if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  4593:          cotvarvold=cotvarv;
                   4594:        }else{ /* A second product */
                   4595:          cotvarv=cotvarv*cotvarvold;
1.339     brouard  4596:        }
                   4597:        iposold=ipos;
1.340     brouard  4598:        cov[ioffset+ipos]=cotvarv;
1.354   ! brouard  4599:        /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
1.339     brouard  4600:        /* For products */
                   4601:       }
                   4602:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
                   4603:       /*       iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
                   4604:       /*       /\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
                   4605:       /*       /\*           1  2   3      4      5                         *\/ */
                   4606:       /*       /\*itv           1                                           *\/ */
                   4607:       /*       /\* TvarVInd[1]= 2                                           *\/ */
                   4608:       /*       /\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
                   4609:       /*       /\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
                   4610:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
                   4611:       /*       /\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
                   4612:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
                   4613:       /*       cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
                   4614:       /*       /\* 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]); *\/ */
                   4615:       /* } */
1.232     brouard  4616:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4617:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4618:       /*       /\* 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]); *\/ */
                   4619:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4620:       /* } */
1.126     brouard  4621:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4622:        for (j=1;j<=nlstate+ndeath;j++){
                   4623:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4624:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4625:        }
1.214     brouard  4626:       
                   4627:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4628:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4629:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4630:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4631:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4632:          and mw[mi+1][i]. dh depends on stepm.*/
                   4633:        newm=savm;
1.247     brouard  4634:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4635:        cov[2]=agexact;
                   4636:        if(nagesqr==1)
                   4637:          cov[3]= agexact*agexact;
1.349     brouard  4638:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   4639:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   4640:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4641:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4642:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4643:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4644:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   4645:          }else{ /* fixed covariate */
                   4646:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   4647:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4648:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4649:          }
                   4650:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4651:            cotvarvold=cotvarv;
                   4652:          }else{ /* A second product */
                   4653:            /* printf("DEBUG * \n"); */
                   4654:            cotvarv=cotvarv*cotvarvold;
                   4655:          }
                   4656:          iposold=ipos;
                   4657:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   4658:          cov[ioffset+ipos]=cotvarv*agexact;
                   4659:          /* For products */
1.242     brouard  4660:        }
1.349     brouard  4661: 
1.242     brouard  4662:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4663:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4664:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4665:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4666:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4667:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4668:        savm=oldm;
                   4669:        oldm=newm;
1.126     brouard  4670:       } /* end mult */
1.336     brouard  4671:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4672:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4673:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4674:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4675:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4676:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4677:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4678:         * probability in order to take into account the bias as a fraction of the way
                   4679:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4680:                                 * -stepm/2 to stepm/2 .
                   4681:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4682:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4683:                                 */
1.126     brouard  4684:       s1=s[mw[mi][i]][i];
                   4685:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4686:       /* if(s2==-1){ */
1.268     brouard  4687:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4688:       /*       /\* exit(1); *\/ */
                   4689:       /* } */
1.126     brouard  4690:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4691:       /* bias is positive if real duration
                   4692:        * is higher than the multiple of stepm and negative otherwise.
                   4693:        */
                   4694:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4695:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4696:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4697:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4698:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4699:        lli= log(survp);
1.126     brouard  4700:       }else if (mle==1){
1.242     brouard  4701:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4702:       } else if(mle==2){
1.242     brouard  4703:        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  4704:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4705:        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  4706:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4707:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4708:       } else{  /* mle=0 back to 1 */
1.242     brouard  4709:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4710:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4711:       } /* End of if */
                   4712:       ipmx +=1;
                   4713:       sw += weight[i];
                   4714:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.342     brouard  4715:       /* Printing covariates values for each contribution for checking */
1.343     brouard  4716:       /* 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  4717:       if(globpr){
1.246     brouard  4718:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4719:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4720:                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  4721:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.343     brouard  4722:        /*      printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
                   4723:        /* %11.6f %11.6f %11.6f ", \ */
                   4724:        /*              num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   4725:        /*              2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  4726:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4727:          llt +=ll[k]*gipmx/gsw;
                   4728:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335     brouard  4729:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  4730:        }
1.343     brouard  4731:        fprintf(ficresilk," %10.6f ", -llt);
1.335     brouard  4732:        /* printf(" %10.6f\n", -llt); */
1.342     brouard  4733:        /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
1.343     brouard  4734:        /* fprintf(ficresilk,"%09ld ", num[i]); */ /* not necessary */
                   4735:        for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
                   4736:          fprintf(ficresilk," %g",covar[Tvar[TvarFind[kf]]][i]);
                   4737:        }
                   4738:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
                   4739:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4740:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4741:            fprintf(ficresilk," %g",cov[ioffset+ipos]);
                   4742:            /* printf(" %g",cov[ioffset+ipos]); */
                   4743:          }else{
                   4744:            fprintf(ficresilk,"*");
                   4745:            /* printf("*"); */
1.342     brouard  4746:          }
1.343     brouard  4747:          iposold=ipos;
                   4748:        }
1.349     brouard  4749:        /* for (kk=1; kk<=cptcovage;kk++) { */
                   4750:        /*   if(!FixedV[Tvar[Tage[kk]]]){ */
                   4751:        /*     fprintf(ficresilk," %g*age",covar[Tvar[Tage[kk]]][i]); */
                   4752:        /*     /\* printf(" %g*age",covar[Tvar[Tage[kk]]][i]); *\/ */
                   4753:        /*   }else{ */
                   4754:        /*     fprintf(ficresilk," %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   4755:        /*     /\* printf(" %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\\/  *\/ */
                   4756:        /*   } */
                   4757:        /* } */
                   4758:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   4759:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   4760:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4761:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4762:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4763:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4764:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   4765:          }else{ /* fixed covariate */
                   4766:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   4767:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4768:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4769:          }
                   4770:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4771:            cotvarvold=cotvarv;
                   4772:          }else{ /* A second product */
                   4773:            /* printf("DEBUG * \n"); */
                   4774:            cotvarv=cotvarv*cotvarvold;
1.342     brouard  4775:          }
1.349     brouard  4776:          cotvarv=cotvarv*agexact;
                   4777:          fprintf(ficresilk," %g*age",cotvarv);
                   4778:          iposold=ipos;
                   4779:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   4780:          cov[ioffset+ipos]=cotvarv;
                   4781:          /* For products */
1.343     brouard  4782:        }
                   4783:        /* printf("\n"); */
1.342     brouard  4784:        /* } /\*  End debugILK *\/ */
                   4785:        fprintf(ficresilk,"\n");
                   4786:       } /* End if globpr */
1.335     brouard  4787:     } /* end of wave */
                   4788:   } /* end of individual */
                   4789:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  4790: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335     brouard  4791:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4792:   if(globpr==0){ /* First time we count the contributions and weights */
                   4793:     gipmx=ipmx;
                   4794:     gsw=sw;
                   4795:   }
1.343     brouard  4796:   return -l;
1.126     brouard  4797: }
                   4798: 
                   4799: 
                   4800: /*************** function likelione ***********/
1.292     brouard  4801: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4802: {
                   4803:   /* This routine should help understanding what is done with 
                   4804:      the selection of individuals/waves and
                   4805:      to check the exact contribution to the likelihood.
                   4806:      Plotting could be done.
1.342     brouard  4807:   */
                   4808:   void pstamp(FILE *ficres);
1.343     brouard  4809:   int k, kf, kk, kvar, ncovv, iposold, ipos;
1.126     brouard  4810: 
                   4811:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4812:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4813:     strcat(fileresilk,fileresu);
1.126     brouard  4814:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4815:       printf("Problem with resultfile: %s\n", fileresilk);
                   4816:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4817:     }
1.342     brouard  4818:     pstamp(ficresilk);fprintf(ficresilk,"# model=1+age+%s\n",model);
1.214     brouard  4819:     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");
                   4820:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4821:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4822:     for(k=1; k<=nlstate; k++) 
                   4823:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
1.342     brouard  4824:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total) ");
                   4825: 
                   4826:     /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
                   4827:       for(kf=1;kf <= ncovf; kf++){
                   4828:        fprintf(ficresilk,"V%d",Tvar[TvarFind[kf]]);
                   4829:        /* printf("V%d",Tvar[TvarFind[kf]]); */
                   4830:       }
                   4831:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){
1.343     brouard  4832:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
1.342     brouard  4833:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4834:          /* printf(" %d",ipos); */
                   4835:          fprintf(ficresilk," V%d",TvarVV[ncovv]);
                   4836:        }else{
                   4837:          /* printf("*"); */
                   4838:          fprintf(ficresilk,"*");
1.343     brouard  4839:        }
1.342     brouard  4840:        iposold=ipos;
                   4841:       }
                   4842:       for (kk=1; kk<=cptcovage;kk++) {
                   4843:        if(!FixedV[Tvar[Tage[kk]]]){
                   4844:          /* printf(" %d*age(Fixed)",Tvar[Tage[kk]]); */
                   4845:          fprintf(ficresilk," %d*age(Fixed)",Tvar[Tage[kk]]);
                   4846:        }else{
                   4847:          fprintf(ficresilk," %d*age(Varying)",Tvar[Tage[kk]]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   4848:          /* printf(" %d*age(Varying)",Tvar[Tage[kk]]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   4849:        }
                   4850:       }
                   4851:     /* } /\* End if debugILK *\/ */
                   4852:     /* printf("\n"); */
                   4853:     fprintf(ficresilk,"\n");
                   4854:   } /* End glogpri */
1.126     brouard  4855: 
1.292     brouard  4856:   *fretone=(*func)(p);
1.126     brouard  4857:   if(*globpri !=0){
                   4858:     fclose(ficresilk);
1.205     brouard  4859:     if (mle ==0)
                   4860:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4861:     else if(mle >=1)
                   4862:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4863:     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  4864:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4865:       
1.207     brouard  4866:     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  4867: <img src=\"%s-ori.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4868:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.343     brouard  4869: <img src=\"%s-dest.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
                   4870:     
                   4871:     for (k=1; k<= nlstate ; k++) {
                   4872:       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 \
                   4873: <img src=\"%s-p%dj.png\">\n",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4874:       for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.350     brouard  4875:         kvar=Tvar[TvarFind[kf]];  /* variable */
                   4876:         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]]);
                   4877:         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);
                   4878:         fprintf(fichtm,"<img src=\"%s-p%dj-%d.png\">",subdirf2(optionfilefiname,"ILK_"),k,Tvar[TvarFind[kf]]);
1.343     brouard  4879:       }
                   4880:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Loop on the time varying extended covariates (with extension of Vn*Vm */
                   4881:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   4882:        kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4883:        /* 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]); */
                   4884:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4885:          /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   4886:          /* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); */
                   4887:          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)  */
                   4888:            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> \
                   4889: <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);
                   4890:          } /* End only for dummies time varying (single?) */
                   4891:        }else{ /* Useless product */
                   4892:          /* printf("*"); */
                   4893:          /* fprintf(ficresilk,"*"); */ 
                   4894:        }
                   4895:        iposold=ipos;
                   4896:       } /* For each time varying covariate */
                   4897:     } /* End loop on states */
                   4898: 
                   4899: /*     if(debugILK){ */
                   4900: /*       for(kf=1; kf <= ncovf; kf++){ /\* For each simple dummy covariate of the model *\/ */
                   4901: /*     /\* kvar=Tvar[TvarFind[kf]]; *\/ /\* variable *\/ */
                   4902: /*     for (k=1; k<= nlstate ; k++) { */
                   4903: /*       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> \ */
                   4904: /* <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]]); */
                   4905: /*     } */
                   4906: /*       } */
                   4907: /*       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /\* Loop on the time varying extended covariates (with extension of Vn*Vm *\/ */
                   4908: /*     ipos=TvarVVind[ncovv]; /\* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate *\/ */
                   4909: /*     kvar=TvarVV[ncovv]; /\*  TvarVV={3, 1, 3} gives the name of each varying covariate *\/ */
                   4910: /*     /\* 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]); *\/ */
                   4911: /*     if(ipos!=iposold){ /\* Not a product or first of a product *\/ */
                   4912: /*       /\* fprintf(ficresilk," V%d",TvarVV[ncovv]); *\/ */
                   4913: /*       /\* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); *\/ */
                   4914: /*       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)  *\/ */
                   4915: /*         for (k=1; k<= nlstate ; k++) { */
                   4916: /*           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> \ */
                   4917: /* <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar); */
                   4918: /*         } /\* End state *\/ */
                   4919: /*       } /\* End only for dummies time varying (single?) *\/ */
                   4920: /*     }else{ /\* Useless product *\/ */
                   4921: /*       /\* printf("*"); *\/ */
                   4922: /*       /\* fprintf(ficresilk,"*"); *\/  */
                   4923: /*     } */
                   4924: /*     iposold=ipos; */
                   4925: /*       } /\* For each time varying covariate *\/ */
                   4926: /*     }/\* End debugILK *\/ */
1.207     brouard  4927:     fflush(fichtm);
1.343     brouard  4928:   }/* End globpri */
1.126     brouard  4929:   return;
                   4930: }
                   4931: 
                   4932: 
                   4933: /*********** Maximum Likelihood Estimation ***************/
                   4934: 
                   4935: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4936: {
1.319     brouard  4937:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4938:   double **xi;
                   4939:   double fret;
                   4940:   double fretone; /* Only one call to likelihood */
                   4941:   /*  char filerespow[FILENAMELENGTH];*/
1.354   ! brouard  4942:   
        !          4943:   double * p1; /* Shifted parameters from 0 instead of 1 */
1.162     brouard  4944: #ifdef NLOPT
                   4945:   int creturn;
                   4946:   nlopt_opt opt;
                   4947:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4948:   double *lb;
                   4949:   double minf; /* the minimum objective value, upon return */
1.354   ! brouard  4950: 
1.162     brouard  4951:   myfunc_data dinst, *d = &dinst;
                   4952: #endif
                   4953: 
                   4954: 
1.126     brouard  4955:   xi=matrix(1,npar,1,npar);
                   4956:   for (i=1;i<=npar;i++)
                   4957:     for (j=1;j<=npar;j++)
                   4958:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4959:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4960:   strcpy(filerespow,"POW_"); 
1.126     brouard  4961:   strcat(filerespow,fileres);
                   4962:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4963:     printf("Problem with resultfile: %s\n", filerespow);
                   4964:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4965:   }
                   4966:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4967:   for (i=1;i<=nlstate;i++)
                   4968:     for(j=1;j<=nlstate+ndeath;j++)
                   4969:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4970:   fprintf(ficrespow,"\n");
1.162     brouard  4971: #ifdef POWELL
1.319     brouard  4972: #ifdef LINMINORIGINAL
                   4973: #else /* LINMINORIGINAL */
                   4974:   
                   4975:   flatdir=ivector(1,npar); 
                   4976:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4977: #endif /*LINMINORIGINAL */
                   4978: 
                   4979: #ifdef FLATSUP
                   4980:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4981:   /* reorganizing p by suppressing flat directions */
                   4982:   for(i=1, jk=1; i <=nlstate; i++){
                   4983:     for(k=1; k <=(nlstate+ndeath); k++){
                   4984:       if (k != i) {
                   4985:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4986:         if(flatdir[jk]==1){
                   4987:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4988:         }
                   4989:         for(j=1; j <=ncovmodel; j++){
                   4990:           printf("%12.7f ",p[jk]);
                   4991:           jk++; 
                   4992:         }
                   4993:         printf("\n");
                   4994:       }
                   4995:     }
                   4996:   }
                   4997: /* skipping */
                   4998:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   4999:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   5000:     for(k=1; k <=(nlstate+ndeath); k++){
                   5001:       if (k != i) {
                   5002:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   5003:         if(flatdir[jk]==1){
                   5004:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   5005:           for(j=1; j <=ncovmodel;  jk++,j++){
                   5006:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   5007:             /*q[jjk]=p[jk];*/
                   5008:           }
                   5009:         }else{
                   5010:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   5011:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   5012:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   5013:             /*q[jjk]=p[jk];*/
                   5014:           }
                   5015:         }
                   5016:         printf("\n");
                   5017:       }
                   5018:       fflush(stdout);
                   5019:     }
                   5020:   }
                   5021:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   5022: #else  /* FLATSUP */
1.126     brouard  5023:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  5024: #endif  /* FLATSUP */
                   5025: 
                   5026: #ifdef LINMINORIGINAL
                   5027: #else
                   5028:       free_ivector(flatdir,1,npar); 
                   5029: #endif  /* LINMINORIGINAL*/
                   5030: #endif /* POWELL */
1.126     brouard  5031: 
1.162     brouard  5032: #ifdef NLOPT
                   5033: #ifdef NEWUOA
                   5034:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   5035: #else
                   5036:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   5037: #endif
                   5038:   lb=vector(0,npar-1);
                   5039:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   5040:   nlopt_set_lower_bounds(opt, lb);
                   5041:   nlopt_set_initial_step1(opt, 0.1);
                   5042:   
                   5043:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   5044:   d->function = func;
                   5045:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   5046:   nlopt_set_min_objective(opt, myfunc, d);
                   5047:   nlopt_set_xtol_rel(opt, ftol);
                   5048:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   5049:     printf("nlopt failed! %d\n",creturn); 
                   5050:   }
                   5051:   else {
                   5052:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   5053:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   5054:     iter=1; /* not equal */
                   5055:   }
                   5056:   nlopt_destroy(opt);
                   5057: #endif
1.319     brouard  5058: #ifdef FLATSUP
                   5059:   /* npared = npar -flatd/ncovmodel; */
                   5060:   /* xired= matrix(1,npared,1,npared); */
                   5061:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   5062:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   5063:   /* free_matrix(xire,1,npared,1,npared); */
                   5064: #else  /* FLATSUP */
                   5065: #endif /* FLATSUP */
1.126     brouard  5066:   free_matrix(xi,1,npar,1,npar);
                   5067:   fclose(ficrespow);
1.203     brouard  5068:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   5069:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  5070:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  5071: 
                   5072: }
                   5073: 
                   5074: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  5075: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  5076: {
                   5077:   double  **a,**y,*x,pd;
1.203     brouard  5078:   /* double **hess; */
1.164     brouard  5079:   int i, j;
1.126     brouard  5080:   int *indx;
                   5081: 
                   5082:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  5083:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  5084:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   5085:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   5086:   double gompertz(double p[]);
1.203     brouard  5087:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  5088: 
                   5089:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   5090:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   5091:   for (i=1;i<=npar;i++){
1.203     brouard  5092:     printf("%d-",i);fflush(stdout);
                   5093:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  5094:    
                   5095:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   5096:     
                   5097:     /*  printf(" %f ",p[i]);
                   5098:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   5099:   }
                   5100:   
                   5101:   for (i=1;i<=npar;i++) {
                   5102:     for (j=1;j<=npar;j++)  {
                   5103:       if (j>i) { 
1.203     brouard  5104:        printf(".%d-%d",i,j);fflush(stdout);
                   5105:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   5106:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  5107:        
                   5108:        hess[j][i]=hess[i][j];    
                   5109:        /*printf(" %lf ",hess[i][j]);*/
                   5110:       }
                   5111:     }
                   5112:   }
                   5113:   printf("\n");
                   5114:   fprintf(ficlog,"\n");
                   5115: 
                   5116:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   5117:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   5118:   
                   5119:   a=matrix(1,npar,1,npar);
                   5120:   y=matrix(1,npar,1,npar);
                   5121:   x=vector(1,npar);
                   5122:   indx=ivector(1,npar);
                   5123:   for (i=1;i<=npar;i++)
                   5124:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   5125:   ludcmp(a,npar,indx,&pd);
                   5126: 
                   5127:   for (j=1;j<=npar;j++) {
                   5128:     for (i=1;i<=npar;i++) x[i]=0;
                   5129:     x[j]=1;
                   5130:     lubksb(a,npar,indx,x);
                   5131:     for (i=1;i<=npar;i++){ 
                   5132:       matcov[i][j]=x[i];
                   5133:     }
                   5134:   }
                   5135: 
                   5136:   printf("\n#Hessian matrix#\n");
                   5137:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   5138:   for (i=1;i<=npar;i++) { 
                   5139:     for (j=1;j<=npar;j++) { 
1.203     brouard  5140:       printf("%.6e ",hess[i][j]);
                   5141:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  5142:     }
                   5143:     printf("\n");
                   5144:     fprintf(ficlog,"\n");
                   5145:   }
                   5146: 
1.203     brouard  5147:   /* printf("\n#Covariance matrix#\n"); */
                   5148:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   5149:   /* for (i=1;i<=npar;i++) {  */
                   5150:   /*   for (j=1;j<=npar;j++) {  */
                   5151:   /*     printf("%.6e ",matcov[i][j]); */
                   5152:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   5153:   /*   } */
                   5154:   /*   printf("\n"); */
                   5155:   /*   fprintf(ficlog,"\n"); */
                   5156:   /* } */
                   5157: 
1.126     brouard  5158:   /* Recompute Inverse */
1.203     brouard  5159:   /* for (i=1;i<=npar;i++) */
                   5160:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   5161:   /* ludcmp(a,npar,indx,&pd); */
                   5162: 
                   5163:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   5164: 
                   5165:   /* for (j=1;j<=npar;j++) { */
                   5166:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   5167:   /*   x[j]=1; */
                   5168:   /*   lubksb(a,npar,indx,x); */
                   5169:   /*   for (i=1;i<=npar;i++){  */
                   5170:   /*     y[i][j]=x[i]; */
                   5171:   /*     printf("%.3e ",y[i][j]); */
                   5172:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   5173:   /*   } */
                   5174:   /*   printf("\n"); */
                   5175:   /*   fprintf(ficlog,"\n"); */
                   5176:   /* } */
                   5177: 
                   5178:   /* Verifying the inverse matrix */
                   5179: #ifdef DEBUGHESS
                   5180:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  5181: 
1.203     brouard  5182:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   5183:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  5184: 
                   5185:   for (j=1;j<=npar;j++) {
                   5186:     for (i=1;i<=npar;i++){ 
1.203     brouard  5187:       printf("%.2f ",y[i][j]);
                   5188:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  5189:     }
                   5190:     printf("\n");
                   5191:     fprintf(ficlog,"\n");
                   5192:   }
1.203     brouard  5193: #endif
1.126     brouard  5194: 
                   5195:   free_matrix(a,1,npar,1,npar);
                   5196:   free_matrix(y,1,npar,1,npar);
                   5197:   free_vector(x,1,npar);
                   5198:   free_ivector(indx,1,npar);
1.203     brouard  5199:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  5200: 
                   5201: 
                   5202: }
                   5203: 
                   5204: /*************** hessian matrix ****************/
                   5205: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  5206: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  5207:   int i;
                   5208:   int l=1, lmax=20;
1.203     brouard  5209:   double k1,k2, res, fx;
1.132     brouard  5210:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  5211:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   5212:   int k=0,kmax=10;
                   5213:   double l1;
                   5214: 
                   5215:   fx=func(x);
                   5216:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  5217:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  5218:     l1=pow(10,l);
                   5219:     delts=delt;
                   5220:     for(k=1 ; k <kmax; k=k+1){
                   5221:       delt = delta*(l1*k);
                   5222:       p2[theta]=x[theta] +delt;
1.145     brouard  5223:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  5224:       p2[theta]=x[theta]-delt;
                   5225:       k2=func(p2)-fx;
                   5226:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  5227:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  5228:       
1.203     brouard  5229: #ifdef DEBUGHESSII
1.126     brouard  5230:       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);
                   5231:       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);
                   5232: #endif
                   5233:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   5234:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   5235:        k=kmax;
                   5236:       }
                   5237:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  5238:        k=kmax; l=lmax*10;
1.126     brouard  5239:       }
                   5240:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   5241:        delts=delt;
                   5242:       }
1.203     brouard  5243:     } /* End loop k */
1.126     brouard  5244:   }
                   5245:   delti[theta]=delts;
                   5246:   return res; 
                   5247:   
                   5248: }
                   5249: 
1.203     brouard  5250: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  5251: {
                   5252:   int i;
1.164     brouard  5253:   int l=1, lmax=20;
1.126     brouard  5254:   double k1,k2,k3,k4,res,fx;
1.132     brouard  5255:   double p2[MAXPARM+1];
1.203     brouard  5256:   int k, kmax=1;
                   5257:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  5258: 
                   5259:   int firstime=0;
1.203     brouard  5260:   
1.126     brouard  5261:   fx=func(x);
1.203     brouard  5262:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  5263:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  5264:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5265:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5266:     k1=func(p2)-fx;
                   5267:   
1.203     brouard  5268:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5269:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5270:     k2=func(p2)-fx;
                   5271:   
1.203     brouard  5272:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5273:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5274:     k3=func(p2)-fx;
                   5275:   
1.203     brouard  5276:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5277:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5278:     k4=func(p2)-fx;
1.203     brouard  5279:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   5280:     if(k1*k2*k3*k4 <0.){
1.208     brouard  5281:       firstime=1;
1.203     brouard  5282:       kmax=kmax+10;
1.208     brouard  5283:     }
                   5284:     if(kmax >=10 || firstime ==1){
1.354   ! brouard  5285:       /* What are the thetai and thetaj? thetai/ncovmodel thetai=(thetai-thetai%ncovmodel)/ncovmodel +thetai%ncovmodel=(line,pos)  */
1.246     brouard  5286:       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);
                   5287:       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  5288:       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);
                   5289:       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);
                   5290:     }
                   5291: #ifdef DEBUGHESSIJ
                   5292:     v1=hess[thetai][thetai];
                   5293:     v2=hess[thetaj][thetaj];
                   5294:     cv12=res;
                   5295:     /* Computing eigen value of Hessian matrix */
                   5296:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5297:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5298:     if ((lc2 <0) || (lc1 <0) ){
                   5299:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5300:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5301:       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);
                   5302:       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);
                   5303:     }
1.126     brouard  5304: #endif
                   5305:   }
                   5306:   return res;
                   5307: }
                   5308: 
1.203     brouard  5309:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   5310: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   5311: /* { */
                   5312: /*   int i; */
                   5313: /*   int l=1, lmax=20; */
                   5314: /*   double k1,k2,k3,k4,res,fx; */
                   5315: /*   double p2[MAXPARM+1]; */
                   5316: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   5317: /*   int k=0,kmax=10; */
                   5318: /*   double l1; */
                   5319:   
                   5320: /*   fx=func(x); */
                   5321: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   5322: /*     l1=pow(10,l); */
                   5323: /*     delts=delt; */
                   5324: /*     for(k=1 ; k <kmax; k=k+1){ */
                   5325: /*       delt = delti*(l1*k); */
                   5326: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   5327: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5328: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5329: /*       k1=func(p2)-fx; */
                   5330:       
                   5331: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5332: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5333: /*       k2=func(p2)-fx; */
                   5334:       
                   5335: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5336: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5337: /*       k3=func(p2)-fx; */
                   5338:       
                   5339: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5340: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5341: /*       k4=func(p2)-fx; */
                   5342: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   5343: /* #ifdef DEBUGHESSIJ */
                   5344: /*       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); */
                   5345: /*       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); */
                   5346: /* #endif */
                   5347: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   5348: /*     k=kmax; */
                   5349: /*       } */
                   5350: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   5351: /*     k=kmax; l=lmax*10; */
                   5352: /*       } */
                   5353: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   5354: /*     delts=delt; */
                   5355: /*       } */
                   5356: /*     } /\* End loop k *\/ */
                   5357: /*   } */
                   5358: /*   delti[theta]=delts; */
                   5359: /*   return res;  */
                   5360: /* } */
                   5361: 
                   5362: 
1.126     brouard  5363: /************** Inverse of matrix **************/
                   5364: void ludcmp(double **a, int n, int *indx, double *d) 
                   5365: { 
                   5366:   int i,imax,j,k; 
                   5367:   double big,dum,sum,temp; 
                   5368:   double *vv; 
                   5369:  
                   5370:   vv=vector(1,n); 
                   5371:   *d=1.0; 
                   5372:   for (i=1;i<=n;i++) { 
                   5373:     big=0.0; 
                   5374:     for (j=1;j<=n;j++) 
                   5375:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  5376:     if (big == 0.0){
                   5377:       printf(" Singular Hessian matrix at row %d:\n",i);
                   5378:       for (j=1;j<=n;j++) {
                   5379:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   5380:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   5381:       }
                   5382:       fflush(ficlog);
                   5383:       fclose(ficlog);
                   5384:       nrerror("Singular matrix in routine ludcmp"); 
                   5385:     }
1.126     brouard  5386:     vv[i]=1.0/big; 
                   5387:   } 
                   5388:   for (j=1;j<=n;j++) { 
                   5389:     for (i=1;i<j;i++) { 
                   5390:       sum=a[i][j]; 
                   5391:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   5392:       a[i][j]=sum; 
                   5393:     } 
                   5394:     big=0.0; 
                   5395:     for (i=j;i<=n;i++) { 
                   5396:       sum=a[i][j]; 
                   5397:       for (k=1;k<j;k++) 
                   5398:        sum -= a[i][k]*a[k][j]; 
                   5399:       a[i][j]=sum; 
                   5400:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   5401:        big=dum; 
                   5402:        imax=i; 
                   5403:       } 
                   5404:     } 
                   5405:     if (j != imax) { 
                   5406:       for (k=1;k<=n;k++) { 
                   5407:        dum=a[imax][k]; 
                   5408:        a[imax][k]=a[j][k]; 
                   5409:        a[j][k]=dum; 
                   5410:       } 
                   5411:       *d = -(*d); 
                   5412:       vv[imax]=vv[j]; 
                   5413:     } 
                   5414:     indx[j]=imax; 
                   5415:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   5416:     if (j != n) { 
                   5417:       dum=1.0/(a[j][j]); 
                   5418:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   5419:     } 
                   5420:   } 
                   5421:   free_vector(vv,1,n);  /* Doesn't work */
                   5422: ;
                   5423: } 
                   5424: 
                   5425: void lubksb(double **a, int n, int *indx, double b[]) 
                   5426: { 
                   5427:   int i,ii=0,ip,j; 
                   5428:   double sum; 
                   5429:  
                   5430:   for (i=1;i<=n;i++) { 
                   5431:     ip=indx[i]; 
                   5432:     sum=b[ip]; 
                   5433:     b[ip]=b[i]; 
                   5434:     if (ii) 
                   5435:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   5436:     else if (sum) ii=i; 
                   5437:     b[i]=sum; 
                   5438:   } 
                   5439:   for (i=n;i>=1;i--) { 
                   5440:     sum=b[i]; 
                   5441:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   5442:     b[i]=sum/a[i][i]; 
                   5443:   } 
                   5444: } 
                   5445: 
                   5446: void pstamp(FILE *fichier)
                   5447: {
1.196     brouard  5448:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  5449: }
                   5450: 
1.297     brouard  5451: void date2dmy(double date,double *day, double *month, double *year){
                   5452:   double yp=0., yp1=0., yp2=0.;
                   5453:   
                   5454:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   5455:                        fractional in yp1 */
                   5456:   *year=yp;
                   5457:   yp2=modf((yp1*12),&yp);
                   5458:   *month=yp;
                   5459:   yp1=modf((yp2*30.5),&yp);
                   5460:   *day=yp;
                   5461:   if(*day==0) *day=1;
                   5462:   if(*month==0) *month=1;
                   5463: }
                   5464: 
1.253     brouard  5465: 
                   5466: 
1.126     brouard  5467: /************ Frequencies ********************/
1.251     brouard  5468: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  5469:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   5470:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  5471: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  5472:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  5473:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  5474:   int iind=0, iage=0;
                   5475:   int mi; /* Effective wave */
                   5476:   int first;
                   5477:   double ***freq; /* Frequencies */
1.268     brouard  5478:   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 */
                   5479:   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  5480:   double *meanq, *stdq, *idq;
1.226     brouard  5481:   double **meanqt;
                   5482:   double *pp, **prop, *posprop, *pospropt;
                   5483:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   5484:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   5485:   double agebegin, ageend;
                   5486:     
                   5487:   pp=vector(1,nlstate);
1.251     brouard  5488:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  5489:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   5490:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   5491:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   5492:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  5493:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  5494:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  5495:   meanqt=matrix(1,lastpass,1,nqtveff);
                   5496:   strcpy(fileresp,"P_");
                   5497:   strcat(fileresp,fileresu);
                   5498:   /*strcat(fileresphtm,fileresu);*/
                   5499:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   5500:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   5501:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   5502:     exit(0);
                   5503:   }
1.240     brouard  5504:   
1.226     brouard  5505:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   5506:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   5507:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5508:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5509:     fflush(ficlog);
                   5510:     exit(70); 
                   5511:   }
                   5512:   else{
                   5513:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  5514: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  5515: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5516:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5517:   }
1.319     brouard  5518:   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  5519:   
1.226     brouard  5520:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   5521:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   5522:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5523:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5524:     fflush(ficlog);
                   5525:     exit(70); 
1.240     brouard  5526:   } else{
1.226     brouard  5527:     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  5528: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  5529: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5530:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5531:   }
1.319     brouard  5532:   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  5533:   
1.253     brouard  5534:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   5535:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  5536:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  5537:   j1=0;
1.126     brouard  5538:   
1.227     brouard  5539:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335     brouard  5540:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  5541:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  5542:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  5543:   
                   5544:   
1.226     brouard  5545:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   5546:      reference=low_education V1=0,V2=0
                   5547:      med_educ                V1=1 V2=0, 
                   5548:      high_educ               V1=0 V2=1
1.330     brouard  5549:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  5550:   */
1.249     brouard  5551:   dateintsum=0;
                   5552:   k2cpt=0;
                   5553: 
1.253     brouard  5554:   if(cptcoveff == 0 )
1.265     brouard  5555:     nl=1;  /* Constant and age model only */
1.253     brouard  5556:   else
                   5557:     nl=2;
1.265     brouard  5558: 
                   5559:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   5560:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335     brouard  5561:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  5562:    *     freq[s1][s2][iage] =0.
                   5563:    *     Loop on iind
                   5564:    *       ++freq[s1][s2][iage] weighted
                   5565:    *     end iind
                   5566:    *     if covariate and j!0
                   5567:    *       headers Variable on one line
                   5568:    *     endif cov j!=0
                   5569:    *     header of frequency table by age
                   5570:    *     Loop on age
                   5571:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   5572:    *       pos+=freq[s1][s2][iage] weighted
                   5573:    *       Loop on s1 initial state
                   5574:    *         fprintf(ficresp
                   5575:    *       end s1
                   5576:    *     end age
                   5577:    *     if j!=0 computes starting values
                   5578:    *     end compute starting values
                   5579:    *   end j1
                   5580:    * end nl 
                   5581:    */
1.253     brouard  5582:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   5583:     if(nj==1)
                   5584:       j=0;  /* First pass for the constant */
1.265     brouard  5585:     else{
1.335     brouard  5586:       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  5587:     }
1.251     brouard  5588:     first=1;
1.332     brouard  5589:     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  5590:       posproptt=0.;
1.330     brouard  5591:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  5592:        scanf("%d", i);*/
                   5593:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  5594:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  5595:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  5596:            freq[i][s2][m]=0;
1.251     brouard  5597:       
                   5598:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  5599:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  5600:          prop[i][m]=0;
                   5601:        posprop[i]=0;
                   5602:        pospropt[i]=0;
                   5603:       }
1.283     brouard  5604:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  5605:         idq[z1]=0.;
                   5606:         meanq[z1]=0.;
                   5607:         stdq[z1]=0.;
1.283     brouard  5608:       }
                   5609:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  5610:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  5611:       /*         meanqt[m][z1]=0.; */
                   5612:       /*       } */
                   5613:       /* }       */
1.251     brouard  5614:       /* dateintsum=0; */
                   5615:       /* k2cpt=0; */
                   5616:       
1.265     brouard  5617:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  5618:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   5619:        bool=1;
                   5620:        if(j !=0){
                   5621:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335     brouard  5622:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   5623:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  5624:                /* if(Tvaraff[z1] ==-20){ */
                   5625:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   5626:                /* }else  if(Tvaraff[z1] ==-10){ */
                   5627:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  5628:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335     brouard  5629:                /* 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); */
                   5630:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
1.338     brouard  5631:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  5632:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  5633:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  5634:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  5635:                  /* 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", */
                   5636:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   5637:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  5638:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   5639:                } /* Onlyf fixed */
                   5640:              } /* end z1 */
1.335     brouard  5641:            } /* cptcoveff > 0 */
1.251     brouard  5642:          } /* end any */
                   5643:        }/* end j==0 */
1.265     brouard  5644:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  5645:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  5646:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  5647:            m=mw[mi][iind];
                   5648:            if(j!=0){
                   5649:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335     brouard  5650:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  5651:                  if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  5652:                    /* iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /\* Good *\/ */
                   5653:                    iv= Tvar[Tmodelind[z1]]; /* Good *//* because cotvar starts now at first at ncovcol+nqv+ntv */ 
1.332     brouard  5654:                    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  5655:                                                                                      value is -1, we don't select. It differs from the 
                   5656:                                                                                      constant and age model which counts them. */
                   5657:                      bool=0; /* not selected */
                   5658:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  5659:                    /* i1=Tvaraff[z1]; */
                   5660:                    /* i2=TnsdVar[i1]; */
                   5661:                    /* i3=nbcode[i1][i2]; */
                   5662:                    /* i4=covar[i1][iind]; */
                   5663:                    /* if(i4 != i3){ */
                   5664:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  5665:                      bool=0;
                   5666:                    }
                   5667:                  }
                   5668:                }
                   5669:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   5670:            } /* end j==0 */
                   5671:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  5672:            if(bool==1){ /*Selected */
1.251     brouard  5673:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   5674:                 and mw[mi+1][iind]. dh depends on stepm. */
                   5675:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   5676:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   5677:              if(m >=firstpass && m <=lastpass){
                   5678:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   5679:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   5680:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   5681:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   5682:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   5683:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   5684:                if (m<lastpass) {
                   5685:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   5686:                  /*   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]); */
                   5687:                  if(s[m][iind]==-1)
                   5688:                    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.));
                   5689:                  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  5690:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   5691:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  5692:                      idq[z1]=idq[z1]+weight[iind];
                   5693:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   5694:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   5695:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  5696:                    }
1.284     brouard  5697:                  }
1.251     brouard  5698:                  /* if((int)agev[m][iind] == 55) */
                   5699:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5700:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5701:                  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  5702:                }
1.251     brouard  5703:              } /* end if between passes */  
                   5704:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5705:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5706:                k2cpt++;
                   5707:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  5708:              }
1.251     brouard  5709:            }else{
                   5710:              bool=1;
                   5711:            }/* end bool 2 */
                   5712:          } /* end m */
1.284     brouard  5713:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5714:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5715:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5716:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5717:          /* } */
1.251     brouard  5718:        } /* end bool */
                   5719:       } /* end iind = 1 to imx */
1.319     brouard  5720:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  5721:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5722:       
                   5723:       
                   5724:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335     brouard  5725:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  5726:         pstamp(ficresp);
1.335     brouard  5727:       if  (cptcoveff>0 && j!=0){
1.265     brouard  5728:         pstamp(ficresp);
1.251     brouard  5729:        printf( "\n#********** Variable "); 
                   5730:        fprintf(ficresp, "\n#********** Variable "); 
                   5731:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5732:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5733:        fprintf(ficlog, "\n#********** Variable "); 
1.340     brouard  5734:        for (z1=1; z1<=cptcoveff; z1++){
1.251     brouard  5735:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  5736:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5737:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5738:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5739:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5740:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  5741:          }else{
1.330     brouard  5742:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5743:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5744:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5745:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5746:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5747:          }
                   5748:        }
                   5749:        printf( "**********\n#");
                   5750:        fprintf(ficresp, "**********\n#");
                   5751:        fprintf(ficresphtm, "**********</h3>\n");
                   5752:        fprintf(ficresphtmfr, "**********</h3>\n");
                   5753:        fprintf(ficlog, "**********\n");
                   5754:       }
1.284     brouard  5755:       /*
                   5756:        Printing means of quantitative variables if any
                   5757:       */
                   5758:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5759:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5760:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5761:        if(weightopt==1){
                   5762:          printf(" Weighted mean and standard deviation of");
                   5763:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5764:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5765:        }
1.311     brouard  5766:        /* mu = \frac{w x}{\sum w}
                   5767:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5768:        */
                   5769:        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]));
                   5770:        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]));
                   5771:        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  5772:       }
                   5773:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5774:       /*       for(m=1;m<=lastpass;m++){ */
                   5775:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5776:       /*   } */
                   5777:       /* } */
1.283     brouard  5778: 
1.251     brouard  5779:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335     brouard  5780:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  5781:         fprintf(ficresp, " Age");
1.335     brouard  5782:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   5783:          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]]);
                   5784:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5785:        }
1.251     brouard  5786:       for(i=1; i<=nlstate;i++) {
1.335     brouard  5787:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5788:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5789:       }
1.335     brouard  5790:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5791:       fprintf(ficresphtm, "\n");
                   5792:       
                   5793:       /* Header of frequency table by age */
                   5794:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5795:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5796:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5797:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5798:          if(s2!=0 && m!=0)
                   5799:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5800:        }
1.226     brouard  5801:       }
1.251     brouard  5802:       fprintf(ficresphtmfr, "\n");
                   5803:     
                   5804:       /* For each age */
                   5805:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5806:        fprintf(ficresphtm,"<tr>");
                   5807:        if(iage==iagemax+1){
                   5808:          fprintf(ficlog,"1");
                   5809:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5810:        }else if(iage==iagemax+2){
                   5811:          fprintf(ficlog,"0");
                   5812:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5813:        }else if(iage==iagemax+3){
                   5814:          fprintf(ficlog,"Total");
                   5815:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5816:        }else{
1.240     brouard  5817:          if(first==1){
1.251     brouard  5818:            first=0;
                   5819:            printf("See log file for details...\n");
                   5820:          }
                   5821:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5822:          fprintf(ficlog,"Age %d", iage);
                   5823:        }
1.265     brouard  5824:        for(s1=1; s1 <=nlstate ; s1++){
                   5825:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5826:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5827:        }
1.265     brouard  5828:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5829:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5830:            pos += freq[s1][m][iage];
                   5831:          if(pp[s1]>=1.e-10){
1.251     brouard  5832:            if(first==1){
1.265     brouard  5833:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5834:            }
1.265     brouard  5835:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5836:          }else{
                   5837:            if(first==1)
1.265     brouard  5838:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5839:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5840:          }
                   5841:        }
                   5842:       
1.265     brouard  5843:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5844:          /* posprop[s1]=0; */
                   5845:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5846:            pp[s1] += freq[s1][m][iage];
                   5847:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5848:       
                   5849:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5850:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5851:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5852:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5853:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5854:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5855:        }
                   5856:        
                   5857:        /* Writing ficresp */
1.335     brouard  5858:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5859:           if( iage <= iagemax){
                   5860:            fprintf(ficresp," %d",iage);
                   5861:           }
                   5862:         }else if( nj==2){
                   5863:           if( iage <= iagemax){
                   5864:            fprintf(ficresp," %d",iage);
1.335     brouard  5865:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  5866:           }
1.240     brouard  5867:        }
1.265     brouard  5868:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5869:          if(pos>=1.e-5){
1.251     brouard  5870:            if(first==1)
1.265     brouard  5871:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5872:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5873:          }else{
                   5874:            if(first==1)
1.265     brouard  5875:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5876:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5877:          }
                   5878:          if( iage <= iagemax){
                   5879:            if(pos>=1.e-5){
1.335     brouard  5880:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5881:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5882:               }else if( nj==2){
                   5883:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5884:               }
                   5885:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5886:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5887:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5888:            } else{
1.335     brouard  5889:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  5890:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5891:            }
1.240     brouard  5892:          }
1.265     brouard  5893:          pospropt[s1] +=posprop[s1];
                   5894:        } /* end loop s1 */
1.251     brouard  5895:        /* pospropt=0.; */
1.265     brouard  5896:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5897:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5898:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5899:              if(first==1){
1.265     brouard  5900:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5901:              }
1.265     brouard  5902:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5903:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5904:            }
1.265     brouard  5905:            if(s1!=0 && m!=0)
                   5906:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5907:          }
1.265     brouard  5908:        } /* end loop s1 */
1.251     brouard  5909:        posproptt=0.; 
1.265     brouard  5910:        for(s1=1; s1 <=nlstate; s1++){
                   5911:          posproptt += pospropt[s1];
1.251     brouard  5912:        }
                   5913:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5914:        fprintf(ficresphtm,"</tr>\n");
1.335     brouard  5915:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  5916:          if(iage <= iagemax)
                   5917:            fprintf(ficresp,"\n");
1.240     brouard  5918:        }
1.251     brouard  5919:        if(first==1)
                   5920:          printf("Others in log...\n");
                   5921:        fprintf(ficlog,"\n");
                   5922:       } /* end loop age iage */
1.265     brouard  5923:       
1.251     brouard  5924:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5925:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5926:        if(posproptt < 1.e-5){
1.265     brouard  5927:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5928:        }else{
1.265     brouard  5929:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5930:        }
1.226     brouard  5931:       }
1.251     brouard  5932:       fprintf(ficresphtm,"</tr>\n");
                   5933:       fprintf(ficresphtm,"</table>\n");
                   5934:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5935:       if(posproptt < 1.e-5){
1.251     brouard  5936:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5937:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5938:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5939:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5940:        invalidvarcomb[j1]=1;
1.226     brouard  5941:       }else{
1.338     brouard  5942:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
1.251     brouard  5943:        invalidvarcomb[j1]=0;
1.226     brouard  5944:       }
1.251     brouard  5945:       fprintf(ficresphtmfr,"</table>\n");
                   5946:       fprintf(ficlog,"\n");
                   5947:       if(j!=0){
                   5948:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5949:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5950:          for(k=1; k <=(nlstate+ndeath); k++){
                   5951:            if (k != i) {
1.265     brouard  5952:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5953:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5954:                  if(j1==1){ /* All dummy covariates to zero */
                   5955:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5956:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5957:                    printf("%d%d ",i,k);
                   5958:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5959:                    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]));
                   5960:                    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]));
                   5961:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5962:                  }
1.253     brouard  5963:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5964:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5965:                    x[iage]= (double)iage;
                   5966:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5967:                    /* 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  5968:                  }
1.268     brouard  5969:                  /* Some are not finite, but linreg will ignore these ages */
                   5970:                  no=0;
1.253     brouard  5971:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5972:                  pstart[s1]=b;
                   5973:                  pstart[s1-1]=a;
1.252     brouard  5974:                }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 */ 
                   5975:                  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]);
                   5976:                  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  5977:                  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  5978:                  printf("%d%d ",i,k);
                   5979:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5980:                  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  5981:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5982:                  ;
                   5983:                }
                   5984:                /* printf("%12.7f )", param[i][jj][k]); */
                   5985:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5986:                s1++; 
1.251     brouard  5987:              } /* end jj */
                   5988:            } /* end k!= i */
                   5989:          } /* end k */
1.265     brouard  5990:        } /* end i, s1 */
1.251     brouard  5991:       } /* end j !=0 */
                   5992:     } /* end selected combination of covariate j1 */
                   5993:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5994:       printf("#Freqsummary: Starting values for the constants:\n");
                   5995:       fprintf(ficlog,"\n");
1.265     brouard  5996:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5997:        for(k=1; k <=(nlstate+ndeath); k++){
                   5998:          if (k != i) {
                   5999:            printf("%d%d ",i,k);
                   6000:            fprintf(ficlog,"%d%d ",i,k);
                   6001:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  6002:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  6003:              if(jj==1){ /* Age has to be done */
1.265     brouard  6004:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   6005:                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]));
                   6006:                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  6007:              }
                   6008:              /* printf("%12.7f )", param[i][jj][k]); */
                   6009:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  6010:              s1++; 
1.250     brouard  6011:            }
1.251     brouard  6012:            printf("\n");
                   6013:            fprintf(ficlog,"\n");
1.250     brouard  6014:          }
                   6015:        }
1.284     brouard  6016:       } /* end of state i */
1.251     brouard  6017:       printf("#Freqsummary\n");
                   6018:       fprintf(ficlog,"\n");
1.265     brouard  6019:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   6020:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   6021:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   6022:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   6023:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   6024:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   6025:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   6026:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  6027:          /* } */
                   6028:        }
1.265     brouard  6029:       } /* end loop s1 */
1.251     brouard  6030:       
                   6031:       printf("\n");
                   6032:       fprintf(ficlog,"\n");
                   6033:     } /* end j=0 */
1.249     brouard  6034:   } /* end j */
1.252     brouard  6035: 
1.253     brouard  6036:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  6037:     for(i=1, jk=1; i <=nlstate; i++){
                   6038:       for(j=1; j <=nlstate+ndeath; j++){
                   6039:        if(j!=i){
                   6040:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   6041:          printf("%1d%1d",i,j);
                   6042:          fprintf(ficparo,"%1d%1d",i,j);
                   6043:          for(k=1; k<=ncovmodel;k++){
                   6044:            /*    printf(" %lf",param[i][j][k]); */
                   6045:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   6046:            p[jk]=pstart[jk];
                   6047:            printf(" %f ",pstart[jk]);
                   6048:            fprintf(ficparo," %f ",pstart[jk]);
                   6049:            jk++;
                   6050:          }
                   6051:          printf("\n");
                   6052:          fprintf(ficparo,"\n");
                   6053:        }
                   6054:       }
                   6055:     }
                   6056:   } /* end mle=-2 */
1.226     brouard  6057:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  6058:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  6059:   
1.226     brouard  6060:   fclose(ficresp);
                   6061:   fclose(ficresphtm);
                   6062:   fclose(ficresphtmfr);
1.283     brouard  6063:   free_vector(idq,1,nqfveff);
1.226     brouard  6064:   free_vector(meanq,1,nqfveff);
1.284     brouard  6065:   free_vector(stdq,1,nqfveff);
1.226     brouard  6066:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  6067:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   6068:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  6069:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  6070:   free_vector(pospropt,1,nlstate);
                   6071:   free_vector(posprop,1,nlstate);
1.251     brouard  6072:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  6073:   free_vector(pp,1,nlstate);
                   6074:   /* End of freqsummary */
                   6075: }
1.126     brouard  6076: 
1.268     brouard  6077: /* Simple linear regression */
                   6078: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   6079: 
                   6080:   /* y=a+bx regression */
                   6081:   double   sumx = 0.0;                        /* sum of x                      */
                   6082:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   6083:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   6084:   double   sumy = 0.0;                        /* sum of y                      */
                   6085:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   6086:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   6087:   double yhat;
                   6088:   
                   6089:   double denom=0;
                   6090:   int i;
                   6091:   int ne=*no;
                   6092:   
                   6093:   for ( i=ifi, ne=0;i<=ila;i++) {
                   6094:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   6095:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   6096:       continue;
                   6097:     }
                   6098:     ne=ne+1;
                   6099:     sumx  += x[i];       
                   6100:     sumx2 += x[i]*x[i];  
                   6101:     sumxy += x[i] * y[i];
                   6102:     sumy  += y[i];      
                   6103:     sumy2 += y[i]*y[i]; 
                   6104:     denom = (ne * sumx2 - sumx*sumx);
                   6105:     /* 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); */
                   6106:   } 
                   6107:   
                   6108:   denom = (ne * sumx2 - sumx*sumx);
                   6109:   if (denom == 0) {
                   6110:     // vertical, slope m is infinity
                   6111:     *b = INFINITY;
                   6112:     *a = 0;
                   6113:     if (r) *r = 0;
                   6114:     return 1;
                   6115:   }
                   6116:   
                   6117:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   6118:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   6119:   if (r!=NULL) {
                   6120:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   6121:       sqrt((sumx2 - sumx*sumx/ne) *
                   6122:           (sumy2 - sumy*sumy/ne));
                   6123:   }
                   6124:   *no=ne;
                   6125:   for ( i=ifi, ne=0;i<=ila;i++) {
                   6126:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   6127:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   6128:       continue;
                   6129:     }
                   6130:     ne=ne+1;
                   6131:     yhat = y[i] - *a -*b* x[i];
                   6132:     sume2  += yhat * yhat ;       
                   6133:     
                   6134:     denom = (ne * sumx2 - sumx*sumx);
                   6135:     /* 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); */
                   6136:   } 
                   6137:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   6138:   *sa= *sb * sqrt(sumx2/ne);
                   6139:   
                   6140:   return 0; 
                   6141: }
                   6142: 
1.126     brouard  6143: /************ Prevalence ********************/
1.227     brouard  6144: 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)
                   6145: {  
                   6146:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   6147:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   6148:      We still use firstpass and lastpass as another selection.
                   6149:   */
1.126     brouard  6150:  
1.227     brouard  6151:   int i, m, jk, j1, bool, z1,j, iv;
                   6152:   int mi; /* Effective wave */
                   6153:   int iage;
                   6154:   double agebegin, ageend;
                   6155: 
                   6156:   double **prop;
                   6157:   double posprop; 
                   6158:   double  y2; /* in fractional years */
                   6159:   int iagemin, iagemax;
                   6160:   int first; /** to stop verbosity which is redirected to log file */
                   6161: 
                   6162:   iagemin= (int) agemin;
                   6163:   iagemax= (int) agemax;
                   6164:   /*pp=vector(1,nlstate);*/
1.251     brouard  6165:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  6166:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   6167:   j1=0;
1.222     brouard  6168:   
1.227     brouard  6169:   /*j=cptcoveff;*/
                   6170:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  6171:   
1.288     brouard  6172:   first=0;
1.335     brouard  6173:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  6174:     for (i=1; i<=nlstate; i++)  
1.251     brouard  6175:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  6176:        prop[i][iage]=0.0;
                   6177:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   6178:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   6179:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   6180:     
                   6181:     for (i=1; i<=imx; i++) { /* Each individual */
                   6182:       bool=1;
                   6183:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   6184:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   6185:        m=mw[mi][i];
                   6186:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   6187:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   6188:        for (z1=1; z1<=cptcoveff; z1++){
                   6189:          if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  6190:            iv= Tvar[Tmodelind[z1]];/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.332     brouard  6191:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  6192:              bool=0;
                   6193:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  6194:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  6195:              bool=0;
                   6196:            }
                   6197:        }
                   6198:        if(bool==1){ /* Otherwise we skip that wave/person */
                   6199:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   6200:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   6201:          if(m >=firstpass && m <=lastpass){
                   6202:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   6203:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   6204:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   6205:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  6206:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  6207:                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); 
                   6208:                exit(1);
                   6209:              }
                   6210:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   6211:                /*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]]);*/
                   6212:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   6213:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   6214:              } /* end valid statuses */ 
                   6215:            } /* end selection of dates */
                   6216:          } /* end selection of waves */
                   6217:        } /* end bool */
                   6218:       } /* end wave */
                   6219:     } /* end individual */
                   6220:     for(i=iagemin; i <= iagemax+3; i++){  
                   6221:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   6222:        posprop += prop[jk][i]; 
                   6223:       } 
                   6224:       
                   6225:       for(jk=1; jk <=nlstate ; jk++){      
                   6226:        if( i <=  iagemax){ 
                   6227:          if(posprop>=1.e-5){ 
                   6228:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   6229:          } else{
1.288     brouard  6230:            if(!first){
                   6231:              first=1;
1.266     brouard  6232:              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]);
                   6233:            }else{
1.288     brouard  6234:              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  6235:            }
                   6236:          }
                   6237:        } 
                   6238:       }/* end jk */ 
                   6239:     }/* end i */ 
1.222     brouard  6240:      /*} *//* end i1 */
1.227     brouard  6241:   } /* end j1 */
1.222     brouard  6242:   
1.227     brouard  6243:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   6244:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  6245:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  6246: }  /* End of prevalence */
1.126     brouard  6247: 
                   6248: /************* Waves Concatenation ***************/
                   6249: 
                   6250: 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)
                   6251: {
1.298     brouard  6252:   /* 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  6253:      Death is a valid wave (if date is known).
                   6254:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   6255:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  6256:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  6257:   */
1.126     brouard  6258: 
1.224     brouard  6259:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  6260:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   6261:      double sum=0., jmean=0.;*/
1.224     brouard  6262:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  6263:   int j, k=0,jk, ju, jl;
                   6264:   double sum=0.;
                   6265:   first=0;
1.214     brouard  6266:   firstwo=0;
1.217     brouard  6267:   firsthree=0;
1.218     brouard  6268:   firstfour=0;
1.164     brouard  6269:   jmin=100000;
1.126     brouard  6270:   jmax=-1;
                   6271:   jmean=0.;
1.224     brouard  6272: 
                   6273: /* Treating live states */
1.214     brouard  6274:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  6275:     mi=0;  /* First valid wave */
1.227     brouard  6276:     mli=0; /* Last valid wave */
1.309     brouard  6277:     m=firstpass;  /* Loop on waves */
                   6278:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  6279:       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 */
                   6280:        mli=m-1;/* mw[++mi][i]=m-1; */
                   6281:       }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  6282:        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  6283:        mli=m;
1.224     brouard  6284:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   6285:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  6286:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  6287:       }
1.309     brouard  6288:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  6289: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  6290:        break;
1.224     brouard  6291: #else
1.317     brouard  6292:        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  6293:          if(firsthree == 0){
1.302     brouard  6294:            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  6295:            firsthree=1;
1.317     brouard  6296:          }else if(firsthree >=1 && firsthree < 10){
                   6297:            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);
                   6298:            firsthree++;
                   6299:          }else if(firsthree == 10){
                   6300:            printf("Information, too many Information flags: no more reported to log either\n");
                   6301:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   6302:            firsthree++;
                   6303:          }else{
                   6304:            firsthree++;
1.227     brouard  6305:          }
1.309     brouard  6306:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  6307:          mli=m;
                   6308:        }
                   6309:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   6310:          nbwarn++;
1.309     brouard  6311:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  6312:            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);
                   6313:            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);
                   6314:          }
                   6315:          break;
                   6316:        }
                   6317:        break;
1.224     brouard  6318: #endif
1.227     brouard  6319:       }/* End m >= lastpass */
1.126     brouard  6320:     }/* end while */
1.224     brouard  6321: 
1.227     brouard  6322:     /* 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  6323:     /* After last pass */
1.224     brouard  6324: /* Treating death states */
1.214     brouard  6325:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  6326:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   6327:       /* } */
1.126     brouard  6328:       mi++;    /* Death is another wave */
                   6329:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  6330:       /* Only death is a correct wave */
1.126     brouard  6331:       mw[mi][i]=m;
1.257     brouard  6332:     } /* else not in a death state */
1.224     brouard  6333: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  6334:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  6335:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  6336:        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  6337:          nbwarn++;
                   6338:          if(firstfiv==0){
1.309     brouard  6339:            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  6340:            firstfiv=1;
                   6341:          }else{
1.309     brouard  6342:            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  6343:          }
1.309     brouard  6344:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   6345:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  6346:          nberr++;
                   6347:          if(firstwo==0){
1.309     brouard  6348:            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  6349:            firstwo=1;
                   6350:          }
1.309     brouard  6351:          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  6352:        }
1.257     brouard  6353:       }else{ /* if date of interview is unknown */
1.227     brouard  6354:        /* death is known but not confirmed by death status at any wave */
                   6355:        if(firstfour==0){
1.309     brouard  6356:          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  6357:          firstfour=1;
                   6358:        }
1.309     brouard  6359:        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  6360:       }
1.224     brouard  6361:     } /* end if date of death is known */
                   6362: #endif
1.309     brouard  6363:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   6364:     /* wav[i]=mw[mi][i];   */
1.126     brouard  6365:     if(mi==0){
                   6366:       nbwarn++;
                   6367:       if(first==0){
1.227     brouard  6368:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   6369:        first=1;
1.126     brouard  6370:       }
                   6371:       if(first==1){
1.227     brouard  6372:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  6373:       }
                   6374:     } /* end mi==0 */
                   6375:   } /* End individuals */
1.214     brouard  6376:   /* wav and mw are no more changed */
1.223     brouard  6377:        
1.317     brouard  6378:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6379:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6380: 
                   6381: 
1.126     brouard  6382:   for(i=1; i<=imx; i++){
                   6383:     for(mi=1; mi<wav[i];mi++){
                   6384:       if (stepm <=0)
1.227     brouard  6385:        dh[mi][i]=1;
1.126     brouard  6386:       else{
1.260     brouard  6387:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  6388:          if (agedc[i] < 2*AGESUP) {
                   6389:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   6390:            if(j==0) j=1;  /* Survives at least one month after exam */
                   6391:            else if(j<0){
                   6392:              nberr++;
                   6393:              printf("Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
                   6394:              j=1; /* Temporary Dangerous patch */
                   6395:              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);
                   6396:              fprintf(ficlog,"Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
                   6397:              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);
                   6398:            }
                   6399:            k=k+1;
                   6400:            if (j >= jmax){
                   6401:              jmax=j;
                   6402:              ijmax=i;
                   6403:            }
                   6404:            if (j <= jmin){
                   6405:              jmin=j;
                   6406:              ijmin=i;
                   6407:            }
                   6408:            sum=sum+j;
                   6409:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   6410:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   6411:          }
                   6412:        }
                   6413:        else{
                   6414:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  6415: /*       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  6416:                                        
1.227     brouard  6417:          k=k+1;
                   6418:          if (j >= jmax) {
                   6419:            jmax=j;
                   6420:            ijmax=i;
                   6421:          }
                   6422:          else if (j <= jmin){
                   6423:            jmin=j;
                   6424:            ijmin=i;
                   6425:          }
                   6426:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   6427:          /*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]);*/
                   6428:          if(j<0){
                   6429:            nberr++;
                   6430:            printf("Error! Negative delay (%d) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
                   6431:            fprintf(ficlog,"Error! Negative delay (%d) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
                   6432:          }
                   6433:          sum=sum+j;
                   6434:        }
                   6435:        jk= j/stepm;
                   6436:        jl= j -jk*stepm;
                   6437:        ju= j -(jk+1)*stepm;
                   6438:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   6439:          if(jl==0){
                   6440:            dh[mi][i]=jk;
                   6441:            bh[mi][i]=0;
                   6442:          }else{ /* We want a negative bias in order to only have interpolation ie
                   6443:                  * to avoid the price of an extra matrix product in likelihood */
                   6444:            dh[mi][i]=jk+1;
                   6445:            bh[mi][i]=ju;
                   6446:          }
                   6447:        }else{
                   6448:          if(jl <= -ju){
                   6449:            dh[mi][i]=jk;
                   6450:            bh[mi][i]=jl;       /* bias is positive if real duration
                   6451:                                 * is higher than the multiple of stepm and negative otherwise.
                   6452:                                 */
                   6453:          }
                   6454:          else{
                   6455:            dh[mi][i]=jk+1;
                   6456:            bh[mi][i]=ju;
                   6457:          }
                   6458:          if(dh[mi][i]==0){
                   6459:            dh[mi][i]=1; /* At least one step */
                   6460:            bh[mi][i]=ju; /* At least one step */
                   6461:            /*  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);*/
                   6462:          }
                   6463:        } /* end if mle */
1.126     brouard  6464:       }
                   6465:     } /* end wave */
                   6466:   }
                   6467:   jmean=sum/k;
                   6468:   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  6469:   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  6470: }
1.126     brouard  6471: 
                   6472: /*********** Tricode ****************************/
1.220     brouard  6473:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  6474:  {
                   6475:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   6476:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   6477:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   6478:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   6479:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   6480:     */
1.130     brouard  6481: 
1.242     brouard  6482:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   6483:    int modmaxcovj=0; /* Modality max of covariates j */
                   6484:    int cptcode=0; /* Modality max of covariates j */
                   6485:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  6486: 
                   6487: 
1.242     brouard  6488:    /* cptcoveff=0;  */
                   6489:    /* *cptcov=0; */
1.126     brouard  6490:  
1.242     brouard  6491:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  6492:    for (k=1; k <= maxncov; k++)
                   6493:      for(j=1; j<=2; j++)
                   6494:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  6495: 
1.242     brouard  6496:    /* Loop on covariates without age and products and no quantitative variable */
1.335     brouard  6497:    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  6498:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
1.343     brouard  6499:      /* printf("Testing k=%d, cptcovt=%d\n",k, cptcovt); */
1.349     brouard  6500:      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  6501:        switch(Fixed[k]) {
                   6502:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  6503:         modmaxcovj=0;
                   6504:         modmincovj=0;
1.242     brouard  6505:         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  6506:           /* 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  6507:           ij=(int)(covar[Tvar[k]][i]);
                   6508:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   6509:            * If product of Vn*Vm, still boolean *:
                   6510:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   6511:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   6512:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   6513:              modality of the nth covariate of individual i. */
                   6514:           if (ij > modmaxcovj)
                   6515:             modmaxcovj=ij; 
                   6516:           else if (ij < modmincovj) 
                   6517:             modmincovj=ij; 
1.287     brouard  6518:           if (ij <0 || ij >1 ){
1.311     brouard  6519:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6520:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6521:             fflush(ficlog);
                   6522:             exit(1);
1.287     brouard  6523:           }
                   6524:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  6525:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   6526:             exit(1);
                   6527:           }else
                   6528:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   6529:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   6530:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   6531:           /* getting the maximum value of the modality of the covariate
                   6532:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   6533:              female ies 1, then modmaxcovj=1.
                   6534:           */
                   6535:         } /* end for loop on individuals i */
                   6536:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6537:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6538:         cptcode=modmaxcovj;
                   6539:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   6540:         /*for (i=0; i<=cptcode; i++) {*/
                   6541:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   6542:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6543:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6544:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   6545:             if( j != -1){
                   6546:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   6547:                                  covariate for which somebody answered excluding 
                   6548:                                  undefined. Usually 2: 0 and 1. */
                   6549:             }
                   6550:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   6551:                                     covariate for which somebody answered including 
                   6552:                                     undefined. Usually 3: -1, 0 and 1. */
                   6553:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   6554:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   6555:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  6556:                        
1.242     brouard  6557:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   6558:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   6559:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   6560:         /* modmincovj=3; modmaxcovj = 7; */
                   6561:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   6562:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   6563:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   6564:         /* nbcode[Tvar[j]][ij]=k; */
                   6565:         /* nbcode[Tvar[j]][1]=0; */
                   6566:         /* nbcode[Tvar[j]][2]=1; */
                   6567:         /* nbcode[Tvar[j]][3]=2; */
                   6568:         /* To be continued (not working yet). */
                   6569:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  6570: 
                   6571:         /* 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*/
                   6572:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   6573:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   6574:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   6575:         /*, could be restored in the future */
                   6576:         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  6577:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   6578:             break;
                   6579:           }
                   6580:           ij++;
1.287     brouard  6581:           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  6582:           cptcode = ij; /* New max modality for covar j */
                   6583:         } /* end of loop on modality i=-1 to 1 or more */
                   6584:         break;
                   6585:        case 1: /* Testing on varying covariate, could be simple and
                   6586:                * should look at waves or product of fixed *
                   6587:                * varying. No time to test -1, assuming 0 and 1 only */
                   6588:         ij=0;
                   6589:         for(i=0; i<=1;i++){
                   6590:           nbcode[Tvar[k]][++ij]=i;
                   6591:         }
                   6592:         break;
                   6593:        default:
                   6594:         break;
                   6595:        } /* end switch */
                   6596:      } /* end dummy test */
1.349     brouard  6597:      if(Dummy[k]==1 && Typevar[k] !=1 && Typevar[k] !=3 && Fixed ==0){ /* Fixed Quantitative covariate and not age product */ 
1.311     brouard  6598:        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  6599:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   6600:           printf("Error k=%d \n",k);
                   6601:           exit(1);
                   6602:         }
1.311     brouard  6603:         if(isnan(covar[Tvar[k]][i])){
                   6604:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6605:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6606:           fflush(ficlog);
                   6607:           exit(1);
                   6608:          }
                   6609:        }
1.335     brouard  6610:      } /* end Quanti */
1.287     brouard  6611:    } /* 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  6612:   
                   6613:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   6614:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   6615:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   6616:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   6617:      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 */ 
                   6618:      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 */
                   6619:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   6620:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   6621:   
                   6622:    ij=0;
                   6623:    /* 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  6624:    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 */
                   6625:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  6626:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6627:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335     brouard  6628:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   6629:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   6630:        /* 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  6631:        /* If product not in single variable we don't print results */
                   6632:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335     brouard  6633:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   6634:        /* k=       1    2   3     4       5       6      7       8        9  */
                   6635:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   6636:        /* ij            1    2                                            3  */  
                   6637:        /* Tvaraff[ij]=  4    3                                            1  */
                   6638:        /* Tmodelind[ij]=2    3                                            9  */
                   6639:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  6640:        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*/
                   6641:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   6642:        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 */
                   6643:        if(Fixed[k]!=0)
                   6644:         anyvaryingduminmodel=1;
                   6645:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   6646:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6647:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   6648:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   6649:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   6650:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6651:      } 
                   6652:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   6653:    /* ij--; */
                   6654:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335     brouard  6655:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  6656:                * because they can be excluded from the model and real
                   6657:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   6658:    for(j=ij+1; j<= cptcovt; j++){
                   6659:      Tvaraff[j]=0;
                   6660:      Tmodelind[j]=0;
                   6661:    }
                   6662:    for(j=ntveff+1; j<= cptcovt; j++){
                   6663:      TmodelInvind[j]=0;
                   6664:    }
                   6665:    /* To be sorted */
                   6666:    ;
                   6667:  }
1.126     brouard  6668: 
1.145     brouard  6669: 
1.126     brouard  6670: /*********** Health Expectancies ****************/
                   6671: 
1.235     brouard  6672:  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  6673: 
                   6674: {
                   6675:   /* Health expectancies, no variances */
1.329     brouard  6676:   /* cij is the combination in the list of combination of dummy covariates */
                   6677:   /* strstart is a string of time at start of computing */
1.164     brouard  6678:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  6679:   int nhstepma, nstepma; /* Decreasing with age */
                   6680:   double age, agelim, hf;
                   6681:   double ***p3mat;
                   6682:   double eip;
                   6683: 
1.238     brouard  6684:   /* pstamp(ficreseij); */
1.126     brouard  6685:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   6686:   fprintf(ficreseij,"# Age");
                   6687:   for(i=1; i<=nlstate;i++){
                   6688:     for(j=1; j<=nlstate;j++){
                   6689:       fprintf(ficreseij," e%1d%1d ",i,j);
                   6690:     }
                   6691:     fprintf(ficreseij," e%1d. ",i);
                   6692:   }
                   6693:   fprintf(ficreseij,"\n");
                   6694: 
                   6695:   
                   6696:   if(estepm < stepm){
                   6697:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6698:   }
                   6699:   else  hstepm=estepm;   
                   6700:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6701:    * This is mainly to measure the difference between two models: for example
                   6702:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6703:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6704:    * progression in between and thus overestimating or underestimating according
                   6705:    * to the curvature of the survival function. If, for the same date, we 
                   6706:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6707:    * to compare the new estimate of Life expectancy with the same linear 
                   6708:    * hypothesis. A more precise result, taking into account a more precise
                   6709:    * curvature will be obtained if estepm is as small as stepm. */
                   6710: 
                   6711:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6712:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6713:      nhstepm is the number of hstepm from age to agelim 
                   6714:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  6715:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  6716:      and note for a fixed period like estepm months */
                   6717:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6718:      survival function given by stepm (the optimization length). Unfortunately it
                   6719:      means that if the survival funtion is printed only each two years of age and if
                   6720:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6721:      results. So we changed our mind and took the option of the best precision.
                   6722:   */
                   6723:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6724: 
                   6725:   agelim=AGESUP;
                   6726:   /* If stepm=6 months */
                   6727:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6728:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6729:     
                   6730: /* nhstepm age range expressed in number of stepm */
                   6731:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6732:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6733:   /* if (stepm >= YEARM) hstepm=1;*/
                   6734:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6735:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6736: 
                   6737:   for (age=bage; age<=fage; age ++){ 
                   6738:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6739:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6740:     /* if (stepm >= YEARM) hstepm=1;*/
                   6741:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   6742: 
                   6743:     /* If stepm=6 months */
                   6744:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6745:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  6746:     /* 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  6747:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  6748:     
                   6749:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6750:     
                   6751:     printf("%d|",(int)age);fflush(stdout);
                   6752:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6753:     
                   6754:     /* Computing expectancies */
                   6755:     for(i=1; i<=nlstate;i++)
                   6756:       for(j=1; j<=nlstate;j++)
                   6757:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6758:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   6759:          
                   6760:          /* 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]);*/
                   6761: 
                   6762:        }
                   6763: 
                   6764:     fprintf(ficreseij,"%3.0f",age );
                   6765:     for(i=1; i<=nlstate;i++){
                   6766:       eip=0;
                   6767:       for(j=1; j<=nlstate;j++){
                   6768:        eip +=eij[i][j][(int)age];
                   6769:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   6770:       }
                   6771:       fprintf(ficreseij,"%9.4f", eip );
                   6772:     }
                   6773:     fprintf(ficreseij,"\n");
                   6774:     
                   6775:   }
                   6776:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6777:   printf("\n");
                   6778:   fprintf(ficlog,"\n");
                   6779:   
                   6780: }
                   6781: 
1.235     brouard  6782:  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  6783: 
                   6784: {
                   6785:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6786:      to initial status i, ei. .
1.126     brouard  6787:   */
1.336     brouard  6788:   /* Very time consuming function, but already optimized with precov */
1.126     brouard  6789:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6790:   int nhstepma, nstepma; /* Decreasing with age */
                   6791:   double age, agelim, hf;
                   6792:   double ***p3matp, ***p3matm, ***varhe;
                   6793:   double **dnewm,**doldm;
                   6794:   double *xp, *xm;
                   6795:   double **gp, **gm;
                   6796:   double ***gradg, ***trgradg;
                   6797:   int theta;
                   6798: 
                   6799:   double eip, vip;
                   6800: 
                   6801:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6802:   xp=vector(1,npar);
                   6803:   xm=vector(1,npar);
                   6804:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6805:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6806:   
                   6807:   pstamp(ficresstdeij);
                   6808:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6809:   fprintf(ficresstdeij,"# Age");
                   6810:   for(i=1; i<=nlstate;i++){
                   6811:     for(j=1; j<=nlstate;j++)
                   6812:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6813:     fprintf(ficresstdeij," e%1d. ",i);
                   6814:   }
                   6815:   fprintf(ficresstdeij,"\n");
                   6816: 
                   6817:   pstamp(ficrescveij);
                   6818:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6819:   fprintf(ficrescveij,"# Age");
                   6820:   for(i=1; i<=nlstate;i++)
                   6821:     for(j=1; j<=nlstate;j++){
                   6822:       cptj= (j-1)*nlstate+i;
                   6823:       for(i2=1; i2<=nlstate;i2++)
                   6824:        for(j2=1; j2<=nlstate;j2++){
                   6825:          cptj2= (j2-1)*nlstate+i2;
                   6826:          if(cptj2 <= cptj)
                   6827:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6828:        }
                   6829:     }
                   6830:   fprintf(ficrescveij,"\n");
                   6831:   
                   6832:   if(estepm < stepm){
                   6833:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6834:   }
                   6835:   else  hstepm=estepm;   
                   6836:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6837:    * This is mainly to measure the difference between two models: for example
                   6838:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6839:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6840:    * progression in between and thus overestimating or underestimating according
                   6841:    * to the curvature of the survival function. If, for the same date, we 
                   6842:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6843:    * to compare the new estimate of Life expectancy with the same linear 
                   6844:    * hypothesis. A more precise result, taking into account a more precise
                   6845:    * curvature will be obtained if estepm is as small as stepm. */
                   6846: 
                   6847:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6848:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6849:      nhstepm is the number of hstepm from age to agelim 
                   6850:      nstepm is the number of stepm from age to agelin. 
                   6851:      Look at hpijx to understand the reason of that which relies in memory size
                   6852:      and note for a fixed period like estepm months */
                   6853:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6854:      survival function given by stepm (the optimization length). Unfortunately it
                   6855:      means that if the survival funtion is printed only each two years of age and if
                   6856:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6857:      results. So we changed our mind and took the option of the best precision.
                   6858:   */
                   6859:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6860: 
                   6861:   /* If stepm=6 months */
                   6862:   /* nhstepm age range expressed in number of stepm */
                   6863:   agelim=AGESUP;
                   6864:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6865:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6866:   /* if (stepm >= YEARM) hstepm=1;*/
                   6867:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6868:   
                   6869:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6870:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6871:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6872:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6873:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6874:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6875: 
                   6876:   for (age=bage; age<=fage; age ++){ 
                   6877:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6878:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6879:     /* if (stepm >= YEARM) hstepm=1;*/
                   6880:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6881:                
1.126     brouard  6882:     /* If stepm=6 months */
                   6883:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6884:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6885:     
                   6886:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6887:                
1.126     brouard  6888:     /* Computing  Variances of health expectancies */
                   6889:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6890:        decrease memory allocation */
                   6891:     for(theta=1; theta <=npar; theta++){
                   6892:       for(i=1; i<=npar; i++){ 
1.222     brouard  6893:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6894:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6895:       }
1.235     brouard  6896:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6897:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6898:                        
1.126     brouard  6899:       for(j=1; j<= nlstate; j++){
1.222     brouard  6900:        for(i=1; i<=nlstate; i++){
                   6901:          for(h=0; h<=nhstepm-1; h++){
                   6902:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6903:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6904:          }
                   6905:        }
1.126     brouard  6906:       }
1.218     brouard  6907:                        
1.126     brouard  6908:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6909:        for(h=0; h<=nhstepm-1; h++){
                   6910:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6911:        }
1.126     brouard  6912:     }/* End theta */
                   6913:     
                   6914:     
                   6915:     for(h=0; h<=nhstepm-1; h++)
                   6916:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6917:        for(theta=1; theta <=npar; theta++)
                   6918:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6919:     
1.218     brouard  6920:                
1.222     brouard  6921:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6922:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6923:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6924:                
1.222     brouard  6925:     printf("%d|",(int)age);fflush(stdout);
                   6926:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6927:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6928:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6929:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6930:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6931:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6932:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6933:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6934:       }
                   6935:     }
1.320     brouard  6936:     /* if((int)age ==50){ */
                   6937:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6938:     /* } */
1.126     brouard  6939:     /* Computing expectancies */
1.235     brouard  6940:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6941:     for(i=1; i<=nlstate;i++)
                   6942:       for(j=1; j<=nlstate;j++)
1.222     brouard  6943:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6944:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6945:                                        
1.222     brouard  6946:          /* 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  6947:                                        
1.222     brouard  6948:        }
1.269     brouard  6949: 
                   6950:     /* Standard deviation of expectancies ij */                
1.126     brouard  6951:     fprintf(ficresstdeij,"%3.0f",age );
                   6952:     for(i=1; i<=nlstate;i++){
                   6953:       eip=0.;
                   6954:       vip=0.;
                   6955:       for(j=1; j<=nlstate;j++){
1.222     brouard  6956:        eip += eij[i][j][(int)age];
                   6957:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6958:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6959:        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  6960:       }
                   6961:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6962:     }
                   6963:     fprintf(ficresstdeij,"\n");
1.218     brouard  6964:                
1.269     brouard  6965:     /* Variance of expectancies ij */          
1.126     brouard  6966:     fprintf(ficrescveij,"%3.0f",age );
                   6967:     for(i=1; i<=nlstate;i++)
                   6968:       for(j=1; j<=nlstate;j++){
1.222     brouard  6969:        cptj= (j-1)*nlstate+i;
                   6970:        for(i2=1; i2<=nlstate;i2++)
                   6971:          for(j2=1; j2<=nlstate;j2++){
                   6972:            cptj2= (j2-1)*nlstate+i2;
                   6973:            if(cptj2 <= cptj)
                   6974:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6975:          }
1.126     brouard  6976:       }
                   6977:     fprintf(ficrescveij,"\n");
1.218     brouard  6978:                
1.126     brouard  6979:   }
                   6980:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6981:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6982:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6983:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6984:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6985:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6986:   printf("\n");
                   6987:   fprintf(ficlog,"\n");
1.218     brouard  6988:        
1.126     brouard  6989:   free_vector(xm,1,npar);
                   6990:   free_vector(xp,1,npar);
                   6991:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6992:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6993:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6994: }
1.218     brouard  6995:  
1.126     brouard  6996: /************ Variance ******************/
1.235     brouard  6997:  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  6998:  {
1.279     brouard  6999:    /** Variance of health expectancies 
                   7000:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   7001:     * double **newm;
                   7002:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   7003:     */
1.218     brouard  7004:   
                   7005:    /* int movingaverage(); */
                   7006:    double **dnewm,**doldm;
                   7007:    double **dnewmp,**doldmp;
                   7008:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  7009:    int first=0;
1.218     brouard  7010:    int k;
                   7011:    double *xp;
1.279     brouard  7012:    double **gp, **gm;  /**< for var eij */
                   7013:    double ***gradg, ***trgradg; /**< for var eij */
                   7014:    double **gradgp, **trgradgp; /**< for var p point j */
                   7015:    double *gpp, *gmp; /**< for var p point j */
                   7016:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  7017:    double ***p3mat;
                   7018:    double age,agelim, hf;
                   7019:    /* double ***mobaverage; */
                   7020:    int theta;
                   7021:    char digit[4];
                   7022:    char digitp[25];
                   7023: 
                   7024:    char fileresprobmorprev[FILENAMELENGTH];
                   7025: 
                   7026:    if(popbased==1){
                   7027:      if(mobilav!=0)
                   7028:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   7029:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   7030:    }
                   7031:    else 
                   7032:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  7033: 
1.218     brouard  7034:    /* if (mobilav!=0) { */
                   7035:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7036:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   7037:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   7038:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   7039:    /*   } */
                   7040:    /* } */
                   7041: 
                   7042:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   7043:    sprintf(digit,"%-d",ij);
                   7044:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   7045:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   7046:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   7047:    strcat(fileresprobmorprev,fileresu);
                   7048:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   7049:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   7050:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   7051:    }
                   7052:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   7053:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   7054:    pstamp(ficresprobmorprev);
                   7055:    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  7056:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.337     brouard  7057: 
                   7058:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
                   7059:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
                   7060:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   7061:    /* } */
                   7062:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
1.344     brouard  7063:      /* fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); */
1.337     brouard  7064:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  7065:    }
1.337     brouard  7066:    /* for(j=1;j<=cptcoveff;j++)  */
                   7067:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
1.238     brouard  7068:    fprintf(ficresprobmorprev,"\n");
                   7069: 
1.218     brouard  7070:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   7071:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7072:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   7073:      for(i=1; i<=nlstate;i++)
                   7074:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   7075:    }  
                   7076:    fprintf(ficresprobmorprev,"\n");
                   7077:   
                   7078:    fprintf(ficgp,"\n# Routine varevsij");
                   7079:    fprintf(ficgp,"\nunset title \n");
                   7080:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   7081:    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");
                   7082:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  7083: 
1.218     brouard  7084:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7085:    pstamp(ficresvij);
                   7086:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   7087:    if(popbased==1)
                   7088:      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);
                   7089:    else
                   7090:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   7091:    fprintf(ficresvij,"# Age");
                   7092:    for(i=1; i<=nlstate;i++)
                   7093:      for(j=1; j<=nlstate;j++)
                   7094:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   7095:    fprintf(ficresvij,"\n");
                   7096: 
                   7097:    xp=vector(1,npar);
                   7098:    dnewm=matrix(1,nlstate,1,npar);
                   7099:    doldm=matrix(1,nlstate,1,nlstate);
                   7100:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   7101:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7102: 
                   7103:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   7104:    gpp=vector(nlstate+1,nlstate+ndeath);
                   7105:    gmp=vector(nlstate+1,nlstate+ndeath);
                   7106:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  7107:   
1.218     brouard  7108:    if(estepm < stepm){
                   7109:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   7110:    }
                   7111:    else  hstepm=estepm;   
                   7112:    /* For example we decided to compute the life expectancy with the smallest unit */
                   7113:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   7114:       nhstepm is the number of hstepm from age to agelim 
                   7115:       nstepm is the number of stepm from age to agelim. 
                   7116:       Look at function hpijx to understand why because of memory size limitations, 
                   7117:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   7118:       survival function given by stepm (the optimization length). Unfortunately it
                   7119:       means that if the survival funtion is printed every two years of age and if
                   7120:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   7121:       results. So we changed our mind and took the option of the best precision.
                   7122:    */
                   7123:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   7124:    agelim = AGESUP;
                   7125:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7126:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7127:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   7128:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7129:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   7130:      gp=matrix(0,nhstepm,1,nlstate);
                   7131:      gm=matrix(0,nhstepm,1,nlstate);
                   7132:                
                   7133:                
                   7134:      for(theta=1; theta <=npar; theta++){
                   7135:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   7136:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7137:        }
1.279     brouard  7138:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   7139:        * returns into prlim .
1.288     brouard  7140:        */
1.242     brouard  7141:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  7142: 
                   7143:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  7144:        if (popbased==1) {
                   7145:         if(mobilav ==0){
                   7146:           for(i=1; i<=nlstate;i++)
                   7147:             prlim[i][i]=probs[(int)age][i][ij];
                   7148:         }else{ /* mobilav */ 
                   7149:           for(i=1; i<=nlstate;i++)
                   7150:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   7151:         }
                   7152:        }
1.295     brouard  7153:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  7154:        */                      
                   7155:        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  7156:        /**< 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  7157:        * at horizon h in state j including mortality.
                   7158:        */
1.218     brouard  7159:        for(j=1; j<= nlstate; j++){
                   7160:         for(h=0; h<=nhstepm; h++){
                   7161:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   7162:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   7163:         }
                   7164:        }
1.279     brouard  7165:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  7166:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  7167:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  7168:        */
                   7169:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7170:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   7171:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  7172:        }
                   7173:        
                   7174:        /* Again with minus shift */
1.218     brouard  7175:                        
                   7176:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   7177:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  7178: 
1.242     brouard  7179:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  7180:                        
                   7181:        if (popbased==1) {
                   7182:         if(mobilav ==0){
                   7183:           for(i=1; i<=nlstate;i++)
                   7184:             prlim[i][i]=probs[(int)age][i][ij];
                   7185:         }else{ /* mobilav */ 
                   7186:           for(i=1; i<=nlstate;i++)
                   7187:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   7188:         }
                   7189:        }
                   7190:                        
1.235     brouard  7191:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  7192:                        
                   7193:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   7194:         for(h=0; h<=nhstepm; h++){
                   7195:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   7196:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   7197:         }
                   7198:        }
                   7199:        /* This for computing probability of death (h=1 means
                   7200:          computed over hstepm matrices product = hstepm*stepm months) 
                   7201:          as a weighted average of prlim.
                   7202:        */
                   7203:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7204:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   7205:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   7206:        }    
1.279     brouard  7207:        /* end shifting computations */
                   7208: 
                   7209:        /**< Computing gradient matrix at horizon h 
                   7210:        */
1.218     brouard  7211:        for(j=1; j<= nlstate; j++) /* vareij */
                   7212:         for(h=0; h<=nhstepm; h++){
                   7213:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   7214:         }
1.279     brouard  7215:        /**< Gradient of overall mortality p.3 (or p.j) 
                   7216:        */
                   7217:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  7218:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   7219:        }
                   7220:                        
                   7221:      } /* End theta */
1.279     brouard  7222:      
                   7223:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  7224:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   7225:                
                   7226:      for(h=0; h<=nhstepm; h++) /* veij */
                   7227:        for(j=1; j<=nlstate;j++)
                   7228:         for(theta=1; theta <=npar; theta++)
                   7229:           trgradg[h][j][theta]=gradg[h][theta][j];
                   7230:                
                   7231:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   7232:        for(theta=1; theta <=npar; theta++)
                   7233:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  7234:      /**< as well as its transposed matrix 
                   7235:       */               
1.218     brouard  7236:                
                   7237:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   7238:      for(i=1;i<=nlstate;i++)
                   7239:        for(j=1;j<=nlstate;j++)
                   7240:         vareij[i][j][(int)age] =0.;
1.279     brouard  7241: 
                   7242:      /* Computing trgradg by matcov by gradg at age and summing over h
                   7243:       * and k (nhstepm) formula 15 of article
                   7244:       * Lievre-Brouard-Heathcote
                   7245:       */
                   7246:      
1.218     brouard  7247:      for(h=0;h<=nhstepm;h++){
                   7248:        for(k=0;k<=nhstepm;k++){
                   7249:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   7250:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   7251:         for(i=1;i<=nlstate;i++)
                   7252:           for(j=1;j<=nlstate;j++)
                   7253:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   7254:        }
                   7255:      }
                   7256:                
1.279     brouard  7257:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   7258:       * p.j overall mortality formula 49 but computed directly because
                   7259:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   7260:       * wix is independent of theta.
                   7261:       */
1.218     brouard  7262:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   7263:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   7264:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   7265:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   7266:         varppt[j][i]=doldmp[j][i];
                   7267:      /* end ppptj */
                   7268:      /*  x centered again */
                   7269:                
1.242     brouard  7270:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  7271:                
                   7272:      if (popbased==1) {
                   7273:        if(mobilav ==0){
                   7274:         for(i=1; i<=nlstate;i++)
                   7275:           prlim[i][i]=probs[(int)age][i][ij];
                   7276:        }else{ /* mobilav */ 
                   7277:         for(i=1; i<=nlstate;i++)
                   7278:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   7279:        }
                   7280:      }
                   7281:                
                   7282:      /* This for computing probability of death (h=1 means
                   7283:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   7284:        as a weighted average of prlim.
                   7285:      */
1.235     brouard  7286:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  7287:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7288:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   7289:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   7290:      }    
                   7291:      /* end probability of death */
                   7292:                
                   7293:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   7294:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7295:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   7296:        for(i=1; i<=nlstate;i++){
                   7297:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   7298:        }
                   7299:      } 
                   7300:      fprintf(ficresprobmorprev,"\n");
                   7301:                
                   7302:      fprintf(ficresvij,"%.0f ",age );
                   7303:      for(i=1; i<=nlstate;i++)
                   7304:        for(j=1; j<=nlstate;j++){
                   7305:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   7306:        }
                   7307:      fprintf(ficresvij,"\n");
                   7308:      free_matrix(gp,0,nhstepm,1,nlstate);
                   7309:      free_matrix(gm,0,nhstepm,1,nlstate);
                   7310:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   7311:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   7312:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7313:    } /* End age */
                   7314:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   7315:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   7316:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   7317:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   7318:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   7319:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   7320:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   7321:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   7322:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   7323:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   7324:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7325:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7326:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   7327:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   7328:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   7329:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   7330:    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);
                   7331:    /*  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  7332:     */
1.218     brouard  7333:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   7334:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  7335: 
1.218     brouard  7336:    free_vector(xp,1,npar);
                   7337:    free_matrix(doldm,1,nlstate,1,nlstate);
                   7338:    free_matrix(dnewm,1,nlstate,1,npar);
                   7339:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7340:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   7341:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7342:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7343:    fclose(ficresprobmorprev);
                   7344:    fflush(ficgp);
                   7345:    fflush(fichtm); 
                   7346:  }  /* end varevsij */
1.126     brouard  7347: 
                   7348: /************ Variance of prevlim ******************/
1.269     brouard  7349:  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  7350: {
1.205     brouard  7351:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  7352:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  7353: 
1.268     brouard  7354:   double **dnewmpar,**doldm;
1.126     brouard  7355:   int i, j, nhstepm, hstepm;
                   7356:   double *xp;
                   7357:   double *gp, *gm;
                   7358:   double **gradg, **trgradg;
1.208     brouard  7359:   double **mgm, **mgp;
1.126     brouard  7360:   double age,agelim;
                   7361:   int theta;
                   7362:   
                   7363:   pstamp(ficresvpl);
1.288     brouard  7364:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  7365:   fprintf(ficresvpl,"# Age ");
                   7366:   if(nresult >=1)
                   7367:     fprintf(ficresvpl," Result# ");
1.126     brouard  7368:   for(i=1; i<=nlstate;i++)
                   7369:       fprintf(ficresvpl," %1d-%1d",i,i);
                   7370:   fprintf(ficresvpl,"\n");
                   7371: 
                   7372:   xp=vector(1,npar);
1.268     brouard  7373:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  7374:   doldm=matrix(1,nlstate,1,nlstate);
                   7375:   
                   7376:   hstepm=1*YEARM; /* Every year of age */
                   7377:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7378:   agelim = AGESUP;
                   7379:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7380:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7381:     if (stepm >= YEARM) hstepm=1;
                   7382:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7383:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  7384:     mgp=matrix(1,npar,1,nlstate);
                   7385:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  7386:     gp=vector(1,nlstate);
                   7387:     gm=vector(1,nlstate);
                   7388: 
                   7389:     for(theta=1; theta <=npar; theta++){
                   7390:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7391:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7392:       }
1.288     brouard  7393:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7394:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7395:       /* else */
                   7396:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7397:       for(i=1;i<=nlstate;i++){
1.126     brouard  7398:        gp[i] = prlim[i][i];
1.208     brouard  7399:        mgp[theta][i] = prlim[i][i];
                   7400:       }
1.126     brouard  7401:       for(i=1; i<=npar; i++) /* Computes gradient */
                   7402:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  7403:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7404:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7405:       /* else */
                   7406:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7407:       for(i=1;i<=nlstate;i++){
1.126     brouard  7408:        gm[i] = prlim[i][i];
1.208     brouard  7409:        mgm[theta][i] = prlim[i][i];
                   7410:       }
1.126     brouard  7411:       for(i=1;i<=nlstate;i++)
                   7412:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  7413:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  7414:     } /* End theta */
                   7415: 
                   7416:     trgradg =matrix(1,nlstate,1,npar);
                   7417: 
                   7418:     for(j=1; j<=nlstate;j++)
                   7419:       for(theta=1; theta <=npar; theta++)
                   7420:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  7421:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7422:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7423:     /*   for(j=1; j<=nlstate;j++){ */
                   7424:     /*         printf(" %d ",j); */
                   7425:     /*         for(theta=1; theta <=npar; theta++) */
                   7426:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7427:     /*         printf("\n "); */
                   7428:     /*   } */
                   7429:     /* } */
                   7430:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7431:     /*   printf("\n gradg %d ",(int)age); */
                   7432:     /*   for(j=1; j<=nlstate;j++){ */
                   7433:     /*         printf("%d ",j); */
                   7434:     /*         for(theta=1; theta <=npar; theta++) */
                   7435:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7436:     /*         printf("\n "); */
                   7437:     /*   } */
                   7438:     /* } */
1.126     brouard  7439: 
                   7440:     for(i=1;i<=nlstate;i++)
                   7441:       varpl[i][(int)age] =0.;
1.209     brouard  7442:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  7443:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7444:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7445:     }else{
1.268     brouard  7446:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7447:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7448:     }
1.126     brouard  7449:     for(i=1;i<=nlstate;i++)
                   7450:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7451: 
                   7452:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  7453:     if(nresult >=1)
                   7454:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  7455:     for(i=1; i<=nlstate;i++){
1.126     brouard  7456:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  7457:       /* for(j=1;j<=nlstate;j++) */
                   7458:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   7459:     }
1.126     brouard  7460:     fprintf(ficresvpl,"\n");
                   7461:     free_vector(gp,1,nlstate);
                   7462:     free_vector(gm,1,nlstate);
1.208     brouard  7463:     free_matrix(mgm,1,npar,1,nlstate);
                   7464:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  7465:     free_matrix(gradg,1,npar,1,nlstate);
                   7466:     free_matrix(trgradg,1,nlstate,1,npar);
                   7467:   } /* End age */
                   7468: 
                   7469:   free_vector(xp,1,npar);
                   7470:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  7471:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   7472: 
                   7473: }
                   7474: 
                   7475: 
                   7476: /************ Variance of backprevalence limit ******************/
1.269     brouard  7477:  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  7478: {
                   7479:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   7480:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   7481: 
                   7482:   double **dnewmpar,**doldm;
                   7483:   int i, j, nhstepm, hstepm;
                   7484:   double *xp;
                   7485:   double *gp, *gm;
                   7486:   double **gradg, **trgradg;
                   7487:   double **mgm, **mgp;
                   7488:   double age,agelim;
                   7489:   int theta;
                   7490:   
                   7491:   pstamp(ficresvbl);
                   7492:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   7493:   fprintf(ficresvbl,"# Age ");
                   7494:   if(nresult >=1)
                   7495:     fprintf(ficresvbl," Result# ");
                   7496:   for(i=1; i<=nlstate;i++)
                   7497:       fprintf(ficresvbl," %1d-%1d",i,i);
                   7498:   fprintf(ficresvbl,"\n");
                   7499: 
                   7500:   xp=vector(1,npar);
                   7501:   dnewmpar=matrix(1,nlstate,1,npar);
                   7502:   doldm=matrix(1,nlstate,1,nlstate);
                   7503:   
                   7504:   hstepm=1*YEARM; /* Every year of age */
                   7505:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7506:   agelim = AGEINF;
                   7507:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   7508:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7509:     if (stepm >= YEARM) hstepm=1;
                   7510:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7511:     gradg=matrix(1,npar,1,nlstate);
                   7512:     mgp=matrix(1,npar,1,nlstate);
                   7513:     mgm=matrix(1,npar,1,nlstate);
                   7514:     gp=vector(1,nlstate);
                   7515:     gm=vector(1,nlstate);
                   7516: 
                   7517:     for(theta=1; theta <=npar; theta++){
                   7518:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7519:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7520:       }
                   7521:       if(mobilavproj > 0 )
                   7522:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7523:       else
                   7524:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7525:       for(i=1;i<=nlstate;i++){
                   7526:        gp[i] = bprlim[i][i];
                   7527:        mgp[theta][i] = bprlim[i][i];
                   7528:       }
                   7529:      for(i=1; i<=npar; i++) /* Computes gradient */
                   7530:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   7531:        if(mobilavproj > 0 )
                   7532:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7533:        else
                   7534:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7535:       for(i=1;i<=nlstate;i++){
                   7536:        gm[i] = bprlim[i][i];
                   7537:        mgm[theta][i] = bprlim[i][i];
                   7538:       }
                   7539:       for(i=1;i<=nlstate;i++)
                   7540:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   7541:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   7542:     } /* End theta */
                   7543: 
                   7544:     trgradg =matrix(1,nlstate,1,npar);
                   7545: 
                   7546:     for(j=1; j<=nlstate;j++)
                   7547:       for(theta=1; theta <=npar; theta++)
                   7548:        trgradg[j][theta]=gradg[theta][j];
                   7549:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7550:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7551:     /*   for(j=1; j<=nlstate;j++){ */
                   7552:     /*         printf(" %d ",j); */
                   7553:     /*         for(theta=1; theta <=npar; theta++) */
                   7554:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7555:     /*         printf("\n "); */
                   7556:     /*   } */
                   7557:     /* } */
                   7558:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7559:     /*   printf("\n gradg %d ",(int)age); */
                   7560:     /*   for(j=1; j<=nlstate;j++){ */
                   7561:     /*         printf("%d ",j); */
                   7562:     /*         for(theta=1; theta <=npar; theta++) */
                   7563:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7564:     /*         printf("\n "); */
                   7565:     /*   } */
                   7566:     /* } */
                   7567: 
                   7568:     for(i=1;i<=nlstate;i++)
                   7569:       varbpl[i][(int)age] =0.;
                   7570:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   7571:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7572:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7573:     }else{
                   7574:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7575:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7576:     }
                   7577:     for(i=1;i<=nlstate;i++)
                   7578:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7579: 
                   7580:     fprintf(ficresvbl,"%.0f ",age );
                   7581:     if(nresult >=1)
                   7582:       fprintf(ficresvbl,"%d ",nres );
                   7583:     for(i=1; i<=nlstate;i++)
                   7584:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   7585:     fprintf(ficresvbl,"\n");
                   7586:     free_vector(gp,1,nlstate);
                   7587:     free_vector(gm,1,nlstate);
                   7588:     free_matrix(mgm,1,npar,1,nlstate);
                   7589:     free_matrix(mgp,1,npar,1,nlstate);
                   7590:     free_matrix(gradg,1,npar,1,nlstate);
                   7591:     free_matrix(trgradg,1,nlstate,1,npar);
                   7592:   } /* End age */
                   7593: 
                   7594:   free_vector(xp,1,npar);
                   7595:   free_matrix(doldm,1,nlstate,1,npar);
                   7596:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  7597: 
                   7598: }
                   7599: 
                   7600: /************ Variance of one-step probabilities  ******************/
                   7601: 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  7602:  {
                   7603:    int i, j=0,  k1, l1, tj;
                   7604:    int k2, l2, j1,  z1;
                   7605:    int k=0, l;
                   7606:    int first=1, first1, first2;
1.326     brouard  7607:    int nres=0; /* New */
1.222     brouard  7608:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   7609:    double **dnewm,**doldm;
                   7610:    double *xp;
                   7611:    double *gp, *gm;
                   7612:    double **gradg, **trgradg;
                   7613:    double **mu;
                   7614:    double age, cov[NCOVMAX+1];
                   7615:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   7616:    int theta;
                   7617:    char fileresprob[FILENAMELENGTH];
                   7618:    char fileresprobcov[FILENAMELENGTH];
                   7619:    char fileresprobcor[FILENAMELENGTH];
                   7620:    double ***varpij;
                   7621: 
                   7622:    strcpy(fileresprob,"PROB_"); 
                   7623:    strcat(fileresprob,fileres);
                   7624:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   7625:      printf("Problem with resultfile: %s\n", fileresprob);
                   7626:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   7627:    }
                   7628:    strcpy(fileresprobcov,"PROBCOV_"); 
                   7629:    strcat(fileresprobcov,fileresu);
                   7630:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   7631:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   7632:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   7633:    }
                   7634:    strcpy(fileresprobcor,"PROBCOR_"); 
                   7635:    strcat(fileresprobcor,fileresu);
                   7636:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   7637:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   7638:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   7639:    }
                   7640:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7641:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7642:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7643:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7644:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7645:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7646:    pstamp(ficresprob);
                   7647:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   7648:    fprintf(ficresprob,"# Age");
                   7649:    pstamp(ficresprobcov);
                   7650:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   7651:    fprintf(ficresprobcov,"# Age");
                   7652:    pstamp(ficresprobcor);
                   7653:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   7654:    fprintf(ficresprobcor,"# Age");
1.126     brouard  7655: 
                   7656: 
1.222     brouard  7657:    for(i=1; i<=nlstate;i++)
                   7658:      for(j=1; j<=(nlstate+ndeath);j++){
                   7659:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   7660:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   7661:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   7662:      }  
                   7663:    /* fprintf(ficresprob,"\n");
                   7664:       fprintf(ficresprobcov,"\n");
                   7665:       fprintf(ficresprobcor,"\n");
                   7666:    */
                   7667:    xp=vector(1,npar);
                   7668:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7669:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7670:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   7671:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   7672:    first=1;
                   7673:    fprintf(ficgp,"\n# Routine varprob");
                   7674:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   7675:    fprintf(fichtm,"\n");
                   7676: 
1.288     brouard  7677:    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  7678:    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);
                   7679:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  7680: and drawn. It helps understanding how is the covariance between two incidences.\
                   7681:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  7682:    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  7683: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   7684: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   7685: standard deviations wide on each axis. <br>\
                   7686:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   7687:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   7688: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   7689: 
1.222     brouard  7690:    cov[1]=1;
                   7691:    /* tj=cptcoveff; */
1.225     brouard  7692:    tj = (int) pow(2,cptcoveff);
1.222     brouard  7693:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   7694:    j1=0;
1.332     brouard  7695: 
                   7696:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   7697:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.342     brouard  7698:      /* 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  7699:      if(tj != 1 && TKresult[nres]!= j1)
                   7700:        continue;
                   7701: 
                   7702:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   7703:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   7704:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  7705:      if  (cptcovn>0) {
1.334     brouard  7706:        fprintf(ficresprob, "\n#********** Variable ");
                   7707:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   7708:        fprintf(ficgp, "\n#********** Variable ");
                   7709:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   7710:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   7711: 
                   7712:        /* Including quantitative variables of the resultline to be done */
                   7713:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
1.343     brouard  7714:         /* printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model); */
1.338     brouard  7715:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   7716:         /* 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  7717:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   7718:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   7719:             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  */
                   7720:             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  */
                   7721:             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  */
                   7722:             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  */
                   7723:             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  */
                   7724:             fprintf(ficresprob,"fixed ");
                   7725:             fprintf(ficresprobcov,"fixed ");
                   7726:             fprintf(ficgp,"fixed ");
                   7727:             fprintf(fichtmcov,"fixed ");
                   7728:             fprintf(ficresprobcor,"fixed ");
                   7729:           }else{
                   7730:             fprintf(ficresprob,"varyi ");
                   7731:             fprintf(ficresprobcov,"varyi ");
                   7732:             fprintf(ficgp,"varyi ");
                   7733:             fprintf(fichtmcov,"varyi ");
                   7734:             fprintf(ficresprobcor,"varyi ");
                   7735:           }
                   7736:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   7737:           /* For each selected (single) quantitative value */
1.337     brouard  7738:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
1.334     brouard  7739:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   7740:             fprintf(ficresprob,"fixed ");
                   7741:             fprintf(ficresprobcov,"fixed ");
                   7742:             fprintf(ficgp,"fixed ");
                   7743:             fprintf(fichtmcov,"fixed ");
                   7744:             fprintf(ficresprobcor,"fixed ");
                   7745:           }else{
                   7746:             fprintf(ficresprob,"varyi ");
                   7747:             fprintf(ficresprobcov,"varyi ");
                   7748:             fprintf(ficgp,"varyi ");
                   7749:             fprintf(fichtmcov,"varyi ");
                   7750:             fprintf(ficresprobcor,"varyi ");
                   7751:           }
                   7752:         }else{
                   7753:           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 */
                   7754:           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 */
                   7755:           exit(1);
                   7756:         }
                   7757:        } /* End loop on variable of this resultline */
                   7758:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  7759:        fprintf(ficresprob, "**********\n#\n");
                   7760:        fprintf(ficresprobcov, "**********\n#\n");
                   7761:        fprintf(ficgp, "**********\n#\n");
                   7762:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   7763:        fprintf(ficresprobcor, "**********\n#");    
                   7764:        if(invalidvarcomb[j1]){
                   7765:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   7766:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   7767:         continue;
                   7768:        }
                   7769:      }
                   7770:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   7771:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7772:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   7773:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  7774:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  7775:        cov[2]=age;
                   7776:        if(nagesqr==1)
                   7777:         cov[3]= age*age;
1.334     brouard  7778:        /* New code end of combination but for each resultline */
                   7779:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  7780:         if(Typevar[k1]==1 || Typevar[k1] ==3){ /* A product with age */
1.334     brouard  7781:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  7782:         }else{
1.334     brouard  7783:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  7784:         }
1.334     brouard  7785:        }/* End of loop on model equation */
                   7786: /* Old code */
                   7787:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   7788:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   7789:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   7790:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   7791:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   7792:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   7793:        /*                                                                  * 1  1 1 1 1 */
                   7794:        /*                                                                  * 2  2 1 1 1 */
                   7795:        /*                                                                  * 3  1 2 1 1 */
                   7796:        /*                                                                  *\/ */
                   7797:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   7798:        /* } */
                   7799:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   7800:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   7801:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   7802:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   7803:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   7804:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   7805:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7806:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   7807:        /*         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]); */
                   7808:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   7809:        /*         /\* exit(1); *\/ */
                   7810:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   7811:        /*       } */
                   7812:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7813:        /* } */
                   7814:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   7815:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   7816:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7817:        /*           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]])]; */
                   7818:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7819:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   7820:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   7821:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   7822:        /*         } */
                   7823:        /*       }else{ */
                   7824:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7825:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   7826:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   7827:        /*         }else{ */
                   7828:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   7829:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   7830:        /*         } */
                   7831:        /*       } */
                   7832:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7833:        /* } */                 
1.326     brouard  7834: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  7835:        for(theta=1; theta <=npar; theta++){
                   7836:         for(i=1; i<=npar; i++)
                   7837:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7838:                                
1.222     brouard  7839:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7840:                                
1.222     brouard  7841:         k=0;
                   7842:         for(i=1; i<= (nlstate); i++){
                   7843:           for(j=1; j<=(nlstate+ndeath);j++){
                   7844:             k=k+1;
                   7845:             gp[k]=pmmij[i][j];
                   7846:           }
                   7847:         }
1.220     brouard  7848:                                
1.222     brouard  7849:         for(i=1; i<=npar; i++)
                   7850:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7851:                                
1.222     brouard  7852:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7853:         k=0;
                   7854:         for(i=1; i<=(nlstate); i++){
                   7855:           for(j=1; j<=(nlstate+ndeath);j++){
                   7856:             k=k+1;
                   7857:             gm[k]=pmmij[i][j];
                   7858:           }
                   7859:         }
1.220     brouard  7860:                                
1.222     brouard  7861:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7862:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7863:        }
1.126     brouard  7864: 
1.222     brouard  7865:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7866:         for(theta=1; theta <=npar; theta++)
                   7867:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7868:                        
1.222     brouard  7869:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7870:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7871:                        
1.222     brouard  7872:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7873:                        
1.222     brouard  7874:        k=0;
                   7875:        for(i=1; i<=(nlstate); i++){
                   7876:         for(j=1; j<=(nlstate+ndeath);j++){
                   7877:           k=k+1;
                   7878:           mu[k][(int) age]=pmmij[i][j];
                   7879:         }
                   7880:        }
                   7881:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7882:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7883:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7884:                        
1.222     brouard  7885:        /*printf("\n%d ",(int)age);
                   7886:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7887:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7888:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7889:         }*/
1.220     brouard  7890:                        
1.222     brouard  7891:        fprintf(ficresprob,"\n%d ",(int)age);
                   7892:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7893:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7894:                        
1.222     brouard  7895:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7896:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7897:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7898:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7899:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7900:        }
                   7901:        i=0;
                   7902:        for (k=1; k<=(nlstate);k++){
                   7903:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7904:           i++;
                   7905:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7906:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7907:           for (j=1; j<=i;j++){
                   7908:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7909:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7910:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7911:           }
                   7912:         }
                   7913:        }/* end of loop for state */
                   7914:      } /* end of loop for age */
                   7915:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7916:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7917:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7918:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7919:     
                   7920:      /* Confidence intervalle of pij  */
                   7921:      /*
                   7922:        fprintf(ficgp,"\nunset parametric;unset label");
                   7923:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7924:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7925:        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);
                   7926:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7927:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7928:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7929:      */
                   7930:                
                   7931:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7932:      first1=1;first2=2;
                   7933:      for (k2=1; k2<=(nlstate);k2++){
                   7934:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7935:         if(l2==k2) continue;
                   7936:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7937:         for (k1=1; k1<=(nlstate);k1++){
                   7938:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7939:             if(l1==k1) continue;
                   7940:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7941:             if(i<=j) continue;
                   7942:             for (age=bage; age<=fage; age ++){ 
                   7943:               if ((int)age %5==0){
                   7944:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7945:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7946:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7947:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7948:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7949:                 c12=cv12/sqrt(v1*v2);
                   7950:                 /* Computing eigen value of matrix of covariance */
                   7951:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7952:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7953:                 if ((lc2 <0) || (lc1 <0) ){
                   7954:                   if(first2==1){
                   7955:                     first1=0;
                   7956:                     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);
                   7957:                   }
                   7958:                   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);
                   7959:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7960:                   /* lc2=fabs(lc2); */
                   7961:                 }
1.220     brouard  7962:                                                                
1.222     brouard  7963:                 /* Eigen vectors */
1.280     brouard  7964:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7965:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7966:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7967:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7968:                 }else
                   7969:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7970:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7971:                 v21=(lc1-v1)/cv12*v11;
                   7972:                 v12=-v21;
                   7973:                 v22=v11;
                   7974:                 tnalp=v21/v11;
                   7975:                 if(first1==1){
                   7976:                   first1=0;
                   7977:                   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);
                   7978:                 }
                   7979:                 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);
                   7980:                 /*printf(fignu*/
                   7981:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7982:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7983:                 if(first==1){
                   7984:                   first=0;
                   7985:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7986:                   fprintf(ficgp,"\nset parametric;unset label");
                   7987:                   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);
                   7988:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7989:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7990:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7991: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7992:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7993:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7994:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7995:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7996:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7997:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7998:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7999:                   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  8000:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   8001:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  8002:                 }else{
                   8003:                   first=0;
                   8004:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   8005:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   8006:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   8007:                   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  8008:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   8009:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  8010:                 }/* if first */
                   8011:               } /* age mod 5 */
                   8012:             } /* end loop age */
                   8013:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   8014:             first=1;
                   8015:           } /*l12 */
                   8016:         } /* k12 */
                   8017:        } /*l1 */
                   8018:      }/* k1 */
1.332     brouard  8019:    }  /* loop on combination of covariates j1 */
1.326     brouard  8020:    } /* loop on nres */
1.222     brouard  8021:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   8022:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   8023:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   8024:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   8025:    free_vector(xp,1,npar);
                   8026:    fclose(ficresprob);
                   8027:    fclose(ficresprobcov);
                   8028:    fclose(ficresprobcor);
                   8029:    fflush(ficgp);
                   8030:    fflush(fichtmcov);
                   8031:  }
1.126     brouard  8032: 
                   8033: 
                   8034: /******************* Printing html file ***********/
1.201     brouard  8035: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  8036:                  int lastpass, int stepm, int weightopt, char model[],\
                   8037:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  8038:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   8039:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   8040:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  8041:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  8042:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  8043:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   8044:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   8045: </ul>");
1.319     brouard  8046: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   8047: /* </ul>", model); */
1.214     brouard  8048:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   8049:    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",
                   8050:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  8051:    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  8052:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   8053:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  8054:    fprintf(fichtm,"\
                   8055:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  8056:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  8057:    fprintf(fichtm,"\
1.217     brouard  8058:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   8059:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   8060:    fprintf(fichtm,"\
1.288     brouard  8061:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  8062:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  8063:    fprintf(fichtm,"\
1.288     brouard  8064:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  8065:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   8066:    fprintf(fichtm,"\
1.211     brouard  8067:  - (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  8068:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  8069:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  8070:    if(prevfcast==1){
                   8071:      fprintf(fichtm,"\
                   8072:  - Prevalence projections by age and states:                           \
1.201     brouard  8073:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  8074:    }
1.126     brouard  8075: 
                   8076: 
1.225     brouard  8077:    m=pow(2,cptcoveff);
1.222     brouard  8078:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  8079: 
1.317     brouard  8080:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  8081: 
                   8082:    jj1=0;
                   8083: 
                   8084:    fprintf(fichtm," \n<ul>");
1.337     brouard  8085:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8086:      /* k1=nres; */
1.338     brouard  8087:      k1=TKresult[nres];
                   8088:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
1.337     brouard  8089:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8090:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   8091:    /*     continue; */
1.264     brouard  8092:      jj1++;
                   8093:      if (cptcovn > 0) {
                   8094:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
1.337     brouard  8095:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   8096:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  8097:        }
1.337     brouard  8098:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   8099:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   8100:        /* } */
                   8101:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8102:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8103:        /* } */
1.264     brouard  8104:        fprintf(fichtm,"\">");
                   8105:        
                   8106:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8107:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  8108:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8109:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  8110:        }
1.337     brouard  8111:        /* fprintf(fichtm,"************ Results for covariates"); */
                   8112:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   8113:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   8114:        /* } */
                   8115:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8116:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8117:        /* } */
1.264     brouard  8118:        if(invalidvarcomb[k1]){
                   8119:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8120:         continue;
                   8121:        }
                   8122:        fprintf(fichtm,"</a></li>");
                   8123:      } /* cptcovn >0 */
                   8124:    }
1.317     brouard  8125:    fprintf(fichtm," \n</ul>");
1.264     brouard  8126: 
1.222     brouard  8127:    jj1=0;
1.237     brouard  8128: 
1.337     brouard  8129:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8130:      /* k1=nres; */
1.338     brouard  8131:      k1=TKresult[nres];
                   8132:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8133:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8134:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   8135:    /*     continue; */
1.220     brouard  8136: 
1.222     brouard  8137:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8138:      jj1++;
                   8139:      if (cptcovn > 0) {
1.264     brouard  8140:        fprintf(fichtm,"\n<p><a name=\"rescov");
1.337     brouard  8141:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8142:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  8143:        }
1.337     brouard  8144:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8145:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8146:        /* } */
1.264     brouard  8147:        fprintf(fichtm,"\"</a>");
                   8148:  
1.222     brouard  8149:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  8150:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8151:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8152:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  8153:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   8154:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  8155:        }
1.230     brouard  8156:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.338     brouard  8157:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  8158:        if(invalidvarcomb[k1]){
                   8159:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   8160:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   8161:         continue;
                   8162:        }
                   8163:      }
                   8164:      /* aij, bij */
1.259     brouard  8165:      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  8166: <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  8167:      /* Pij */
1.241     brouard  8168:      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> \
                   8169: <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  8170:      /* Quasi-incidences */
                   8171:      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  8172:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  8173:  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  8174: 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> \
                   8175: <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  8176:      /* Survival functions (period) in state j */
                   8177:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  8178:        fprintf(fichtm,"<br>\n- Survival functions in state %d. And probability to be observed in state %d being in state (1 to %d) at different ages. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br>", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
                   8179:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   8180:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  8181:      }
                   8182:      /* State specific survival functions (period) */
                   8183:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  8184:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   8185:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.329     brouard  8186:  <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);
                   8187:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   8188:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  8189:      }
1.288     brouard  8190:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  8191:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  8192:        fprintf(fichtm,"<br>\n- Convergence to period (stable) prevalence in state %d. Or probability for a person being in state (1 to %d) at different ages, to be in state %d some years after. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br>", cpt, nlstate, cpt, subdirf2(optionfilefiname,"P_"),cpt,k1,nres,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.338     brouard  8193:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
1.329     brouard  8194:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  8195:      }
1.296     brouard  8196:      if(prevbcast==1){
1.288     brouard  8197:        /* Backward prevalence in each health state */
1.222     brouard  8198:        for(cpt=1; cpt<=nlstate;cpt++){
1.338     brouard  8199:         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);
                   8200:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
                   8201:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  8202:        }
1.217     brouard  8203:      }
1.222     brouard  8204:      if(prevfcast==1){
1.288     brouard  8205:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  8206:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  8207:         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);
                   8208:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   8209:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   8210:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  8211:        }
                   8212:      }
1.296     brouard  8213:      if(prevbcast==1){
1.268     brouard  8214:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   8215:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  8216:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   8217:  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 \
                   8218:  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  8219: 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);
                   8220:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   8221:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  8222:        }
                   8223:      }
1.220     brouard  8224:         
1.222     brouard  8225:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  8226:        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);
                   8227:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   8228:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  8229:      }
                   8230:      /* } /\* end i1 *\/ */
1.337     brouard  8231:    }/* End k1=nres */
1.222     brouard  8232:    fprintf(fichtm,"</ul>");
1.126     brouard  8233: 
1.222     brouard  8234:    fprintf(fichtm,"\
1.126     brouard  8235: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  8236:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  8237:  - 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  8238: But because parameters are usually highly correlated (a higher incidence of disability \
                   8239: and a higher incidence of recovery can give very close observed transition) it might \
                   8240: be very useful to look not only at linear confidence intervals estimated from the \
                   8241: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   8242: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   8243: covariance matrix of the one-step probabilities. \
                   8244: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  8245: 
1.222     brouard  8246:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   8247:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   8248:    fprintf(fichtm,"\
1.126     brouard  8249:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8250:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  8251: 
1.222     brouard  8252:    fprintf(fichtm,"\
1.126     brouard  8253:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8254:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   8255:    fprintf(fichtm,"\
1.126     brouard  8256:  - 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): \
                   8257:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8258:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  8259:    fprintf(fichtm,"\
1.126     brouard  8260:  - (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): \
                   8261:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8262:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  8263:    fprintf(fichtm,"\
1.288     brouard  8264:  - 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  8265:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   8266:    fprintf(fichtm,"\
1.128     brouard  8267:  - 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  8268:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   8269:    fprintf(fichtm,"\
1.288     brouard  8270:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  8271:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  8272: 
                   8273: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   8274: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   8275: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   8276: /*     <br>",fileres,fileres,fileres,fileres); */
                   8277: /*  else  */
1.338     brouard  8278: /*    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  8279:    fflush(fichtm);
1.126     brouard  8280: 
1.225     brouard  8281:    m=pow(2,cptcoveff);
1.222     brouard  8282:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  8283: 
1.317     brouard  8284:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   8285: 
                   8286:   jj1=0;
                   8287: 
                   8288:    fprintf(fichtm," \n<ul>");
1.337     brouard  8289:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8290:      /* k1=nres; */
1.338     brouard  8291:      k1=TKresult[nres];
1.337     brouard  8292:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8293:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8294:      /*   continue; */
1.317     brouard  8295:      jj1++;
                   8296:      if (cptcovn > 0) {
                   8297:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
1.337     brouard  8298:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8299:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8300:        }
                   8301:        fprintf(fichtm,"\">");
                   8302:        
                   8303:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8304:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  8305:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8306:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8307:        }
                   8308:        if(invalidvarcomb[k1]){
                   8309:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8310:         continue;
                   8311:        }
                   8312:        fprintf(fichtm,"</a></li>");
                   8313:      } /* cptcovn >0 */
1.337     brouard  8314:    } /* End nres */
1.317     brouard  8315:    fprintf(fichtm," \n</ul>");
                   8316: 
1.222     brouard  8317:    jj1=0;
1.237     brouard  8318: 
1.241     brouard  8319:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8320:      /* k1=nres; */
1.338     brouard  8321:      k1=TKresult[nres];
                   8322:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8323:      /* for(k1=1; k1<=m;k1++){ */
                   8324:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8325:      /*   continue; */
1.222     brouard  8326:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8327:      jj1++;
1.126     brouard  8328:      if (cptcovn > 0) {
1.317     brouard  8329:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
1.337     brouard  8330:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8331:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8332:        }
                   8333:        fprintf(fichtm,"\"</a>");
                   8334:        
1.126     brouard  8335:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  8336:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
                   8337:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8338:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  8339:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  8340:        }
1.237     brouard  8341: 
1.338     brouard  8342:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  8343: 
1.222     brouard  8344:        if(invalidvarcomb[k1]){
                   8345:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   8346:         continue;
                   8347:        }
1.337     brouard  8348:      } /* If cptcovn >0 */
1.126     brouard  8349:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  8350:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  8351: 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);
                   8352:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   8353:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  8354:      }
                   8355:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  8356: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  8357: true period expectancies (those weighted with period prevalences are also\
                   8358:  drawn in addition to the population based expectancies computed using\
1.314     brouard  8359:  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);
                   8360:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   8361:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  8362:      /* } /\* end i1 *\/ */
1.241     brouard  8363:   }/* End nres */
1.222     brouard  8364:    fprintf(fichtm,"</ul>");
                   8365:    fflush(fichtm);
1.126     brouard  8366: }
                   8367: 
                   8368: /******************* Gnuplot file **************/
1.296     brouard  8369: 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  8370: 
1.354   ! brouard  8371:   char dirfileres[256],optfileres[256];
        !          8372:   char gplotcondition[256], gplotlabel[256];
1.343     brouard  8373:   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  8374:   int lv=0, vlv=0, kl=0;
1.130     brouard  8375:   int ng=0;
1.201     brouard  8376:   int vpopbased;
1.223     brouard  8377:   int ioffset; /* variable offset for columns */
1.270     brouard  8378:   int iyearc=1; /* variable column for year of projection  */
                   8379:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  8380:   int nres=0; /* Index of resultline */
1.266     brouard  8381:   int istart=1; /* For starting graphs in projections */
1.219     brouard  8382: 
1.126     brouard  8383: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   8384: /*     printf("Problem with file %s",optionfilegnuplot); */
                   8385: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   8386: /*   } */
                   8387: 
                   8388:   /*#ifdef windows */
                   8389:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  8390:   /*#endif */
1.225     brouard  8391:   m=pow(2,cptcoveff);
1.126     brouard  8392: 
1.274     brouard  8393:   /* diagram of the model */
                   8394:   fprintf(ficgp,"\n#Diagram of the model \n");
                   8395:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   8396:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   8397:   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);
                   8398: 
1.343     brouard  8399:   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  8400:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   8401:   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);
                   8402:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   8403:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   8404:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   8405:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   8406: 
1.202     brouard  8407:   /* Contribution to likelihood */
                   8408:   /* Plot the probability implied in the likelihood */
1.223     brouard  8409:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   8410:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   8411:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   8412:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  8413: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  8414:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   8415: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  8416:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   8417:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8418:   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));
                   8419:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8420:   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));
                   8421:   for (i=1; i<= nlstate ; i ++) {
                   8422:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   8423:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   8424:     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);
                   8425:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   8426:       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);
                   8427:     }
                   8428:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8429:   }
                   8430:   /* 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 */               
                   8431:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8432:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8433:   fprintf(ficgp,"\nset out;unset log\n");
                   8434:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  8435: 
1.343     brouard  8436:   /* Plot the probability implied in the likelihood by covariate value */
                   8437:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
                   8438:   /* if(debugILK==1){ */
                   8439:   for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.347     brouard  8440:     kvar=Tvar[TvarFind[kf]]; /* variable name */
                   8441:     /* k=18+Tvar[TvarFind[kf]];/\*offset because there are 18 columns in the ILK_ file but could be placed else where *\/ */
1.350     brouard  8442:     /* k=18+kf;/\*offset because there are 18 columns in the ILK_ file *\/ */
                   8443:     k=19+kf;/*offset because there are 19 columns in the ILK_ file */
1.343     brouard  8444:     for (i=1; i<= nlstate ; i ++) {
                   8445:       fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8446:       fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
1.348     brouard  8447:       if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   8448:        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);
                   8449:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   8450:          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);
                   8451:        }
                   8452:       }else{
                   8453:        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);
                   8454:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   8455:          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);
                   8456:        }
1.343     brouard  8457:       }
                   8458:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8459:     }
                   8460:   } /* End of each covariate dummy */
                   8461:   for(ncovv=1, iposold=0, kk=0; ncovv <= ncovvt ; ncovv++){
                   8462:     /* Other example        V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   8463:      *     kmodel       =     1   2     3     4         5        6        7       8        9
                   8464:      *  varying                   1     2                                 3       4        5
                   8465:      *  ncovv                     1     2                                3 4     5 6      7 8
                   8466:      * TvarVV[ncovv]             V3     5                                1 3     3 5      1 5
                   8467:      * TvarVVind[ncovv]=kmodel    2     3                                7 7     8 8      9 9
                   8468:      * TvarFind[kmodel]       1   0     0     0         0        0        0       0        0
                   8469:      * kdata     ncovcol=[V1 V2] nqv=0 ntv=[V3 V4] nqtv=V5
                   8470:      * Dummy[kmodel]          0   0     1     2         2        3        1       1        1
                   8471:      */
                   8472:     ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   8473:     kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   8474:     /* 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]); */
                   8475:     if(ipos!=iposold){ /* Not a product or first of a product */
                   8476:       /* printf(" %d",ipos); */
                   8477:       /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   8478:       /* printf(" DebugILK ficgp suite ipos=%d != iposold=%d\n", ipos, iposold); */
                   8479:       kk++; /* Position of the ncovv column in ILK_ */
                   8480:       k=18+ncovf+kk; /*offset because there are 18 columns in the ILK_ file plus ncovf fixed covariate */
                   8481:       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)  */
                   8482:        for (i=1; i<= nlstate ; i ++) {
                   8483:          fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8484:          fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   8485: 
1.348     brouard  8486:            /* printf("Before DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
1.343     brouard  8487:          if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   8488:            /* printf("DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
                   8489:            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);
                   8490:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8491:              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);
                   8492:            }
                   8493:          }else{
                   8494:            /* printf("DebugILK gnuplotversion=%g <5.2\n",gnuplotversion); */
                   8495:            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);
                   8496:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8497:              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);
                   8498:            }
                   8499:          }
                   8500:          fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8501:        }
                   8502:       }/* End if dummy varying */
                   8503:     }else{ /*Product */
                   8504:       /* printf("*"); */
                   8505:       /* fprintf(ficresilk,"*"); */
                   8506:     }
                   8507:     iposold=ipos;
                   8508:   } /* For each time varying covariate */
                   8509:   /* } /\* debugILK==1 *\/ */
                   8510:   /* 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 */               
                   8511:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8512:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8513:   fprintf(ficgp,"\nset out;unset log\n");
                   8514:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   8515: 
                   8516: 
                   8517:   
1.126     brouard  8518:   strcpy(dirfileres,optionfilefiname);
                   8519:   strcpy(optfileres,"vpl");
1.223     brouard  8520:   /* 1eme*/
1.238     brouard  8521:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
1.337     brouard  8522:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
1.236     brouard  8523:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8524:        k1=TKresult[nres];
1.338     brouard  8525:        if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.238     brouard  8526:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.337     brouard  8527:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8528:        /*   continue; */
1.238     brouard  8529:        /* We are interested in selected combination by the resultline */
1.246     brouard  8530:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  8531:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  8532:        strcpy(gplotlabel,"(");
1.337     brouard  8533:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8534:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8535:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8536: 
                   8537:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
                   8538:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
                   8539:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8540:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8541:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8542:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8543:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
                   8544:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
                   8545:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
                   8546:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8547:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8548:        /* } */
                   8549:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8550:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
                   8551:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8552:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.264     brouard  8553:        }
                   8554:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  8555:        /* printf("\n#\n"); */
1.238     brouard  8556:        fprintf(ficgp,"\n#\n");
                   8557:        if(invalidvarcomb[k1]){
1.260     brouard  8558:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  8559:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8560:          continue;
                   8561:        }
1.235     brouard  8562:       
1.241     brouard  8563:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   8564:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  8565:        /* 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  8566:        fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  8567:        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);
                   8568:        /* 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); */
                   8569:       /* k1-1 error should be nres-1*/
1.238     brouard  8570:        for (i=1; i<= nlstate ; i ++) {
                   8571:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8572:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   8573:        }
1.288     brouard  8574:        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  8575:        for (i=1; i<= nlstate ; i ++) {
                   8576:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8577:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8578:        } 
1.260     brouard  8579:        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  8580:        for (i=1; i<= nlstate ; i ++) {
                   8581:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8582:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8583:        }  
1.265     brouard  8584:        /* 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)); */
                   8585:        
                   8586:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   8587:         if(cptcoveff ==0){
1.271     brouard  8588:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  8589:        }else{
                   8590:          kl=0;
                   8591:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8592:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8593:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  8594:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8595:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8596:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8597:            vlv= nbcode[Tvaraff[k]][lv];
                   8598:            kl++;
                   8599:            /* 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 *\/ */
                   8600:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8601:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8602:            /* ''  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*/
                   8603:            if(k==cptcoveff){
                   8604:              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], \
                   8605:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   8606:            }else{
                   8607:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   8608:              kl++;
                   8609:            }
                   8610:          } /* end covariate */
                   8611:        } /* end if no covariate */
                   8612: 
1.296     brouard  8613:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  8614:          /* 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  8615:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  8616:          if(cptcoveff ==0){
1.245     brouard  8617:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  8618:          }else{
                   8619:            kl=0;
                   8620:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8621:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8622:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  8623:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8624:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8625:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8626:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8627:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  8628:              kl++;
1.238     brouard  8629:              /* 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 *\/ */
                   8630:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8631:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8632:              /* ''  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*/
                   8633:              if(k==cptcoveff){
1.245     brouard  8634:                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  8635:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  8636:              }else{
1.332     brouard  8637:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  8638:                kl++;
                   8639:              }
                   8640:            } /* end covariate */
                   8641:          } /* end if no covariate */
1.296     brouard  8642:          if(prevbcast == 1){
1.268     brouard  8643:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   8644:            /* k1-1 error should be nres-1*/
                   8645:            for (i=1; i<= nlstate ; i ++) {
                   8646:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8647:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   8648:            }
1.271     brouard  8649:            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  8650:            for (i=1; i<= nlstate ; i ++) {
                   8651:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8652:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8653:            } 
1.276     brouard  8654:            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  8655:            for (i=1; i<= nlstate ; i ++) {
                   8656:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8657:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8658:            } 
1.274     brouard  8659:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  8660:          } /* end if backprojcast */
1.296     brouard  8661:        } /* end if prevbcast */
1.276     brouard  8662:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   8663:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  8664:       } /* nres */
1.337     brouard  8665:     /* } /\* k1 *\/ */
1.201     brouard  8666:   } /* cpt */
1.235     brouard  8667: 
                   8668:   
1.126     brouard  8669:   /*2 eme*/
1.337     brouard  8670:   /* for (k1=1; k1<= m ; k1 ++){   */
1.238     brouard  8671:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8672:       k1=TKresult[nres];
1.338     brouard  8673:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8674:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8675:       /*       continue; */
1.238     brouard  8676:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  8677:       strcpy(gplotlabel,"(");
1.337     brouard  8678:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8679:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8680:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8681:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8682:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8683:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8684:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8685:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8686:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8687:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8688:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8689:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8690:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8691:       /* } */
                   8692:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
                   8693:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8694:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8695:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8696:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  8697:       }
1.264     brouard  8698:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8699:       fprintf(ficgp,"\n#\n");
1.223     brouard  8700:       if(invalidvarcomb[k1]){
                   8701:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8702:        continue;
                   8703:       }
1.219     brouard  8704:                        
1.241     brouard  8705:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  8706:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  8707:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   8708:        if(vpopbased==0){
1.238     brouard  8709:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  8710:        }else
1.238     brouard  8711:          fprintf(ficgp,"\nreplot ");
                   8712:        for (i=1; i<= nlstate+1 ; i ++) {
                   8713:          k=2*i;
1.261     brouard  8714:          fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ?$4 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),nres-1,nres-1, vpopbased);
1.238     brouard  8715:          for (j=1; j<= nlstate+1 ; j ++) {
                   8716:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8717:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8718:          }   
                   8719:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   8720:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  8721:          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  8722:          for (j=1; j<= nlstate+1 ; j ++) {
                   8723:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8724:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8725:          }   
                   8726:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  8727:          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  8728:          for (j=1; j<= nlstate+1 ; j ++) {
                   8729:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8730:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8731:          }   
                   8732:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   8733:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   8734:        } /* state */
                   8735:       } /* vpopbased */
1.264     brouard  8736:       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  8737:     } /* end nres */
1.337     brouard  8738:   /* } /\* k1 end 2 eme*\/ */
1.238     brouard  8739:        
                   8740:        
                   8741:   /*3eme*/
1.337     brouard  8742:   /* for (k1=1; k1<= m ; k1 ++){ */
1.238     brouard  8743:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8744:       k1=TKresult[nres];
1.338     brouard  8745:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8746:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8747:       /*       continue; */
1.238     brouard  8748: 
1.332     brouard  8749:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  8750:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  8751:        strcpy(gplotlabel,"(");
1.337     brouard  8752:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8753:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8754:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8755:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8756:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8757:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8758:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8759:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8760:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8761:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8762:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8763:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8764:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8765:        /* } */
                   8766:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8767:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8768:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8769:        }
1.264     brouard  8770:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8771:        fprintf(ficgp,"\n#\n");
                   8772:        if(invalidvarcomb[k1]){
                   8773:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8774:          continue;
                   8775:        }
                   8776:                        
                   8777:        /*       k=2+nlstate*(2*cpt-2); */
                   8778:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  8779:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  8780:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  8781:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  8782: 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  8783:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8784:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8785:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   8786:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8787:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8788:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  8789:                                
1.238     brouard  8790:        */
                   8791:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  8792:          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  8793:          /*    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  8794:                                
1.238     brouard  8795:        } 
1.261     brouard  8796:        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  8797:       }
1.264     brouard  8798:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  8799:     } /* end nres */
1.337     brouard  8800:   /* } /\* end kl 3eme *\/ */
1.126     brouard  8801:   
1.223     brouard  8802:   /* 4eme */
1.201     brouard  8803:   /* Survival functions (period) from state i in state j by initial state i */
1.337     brouard  8804:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
1.238     brouard  8805:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8806:       k1=TKresult[nres];
1.338     brouard  8807:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8808:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8809:       /*       continue; */
1.238     brouard  8810:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  8811:        strcpy(gplotlabel,"(");
1.337     brouard  8812:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
                   8813:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8814:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8815:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8816:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8817:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8818:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8819:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8820:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8821:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8822:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8823:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8824:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8825:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8826:        /* } */
                   8827:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8828:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8829:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8830:        }       
1.264     brouard  8831:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8832:        fprintf(ficgp,"\n#\n");
                   8833:        if(invalidvarcomb[k1]){
                   8834:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8835:          continue;
1.223     brouard  8836:        }
1.238     brouard  8837:       
1.241     brouard  8838:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  8839:        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  8840:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8841: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8842:        k=3;
                   8843:        for (i=1; i<= nlstate ; i ++){
                   8844:          if(i==1){
                   8845:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8846:          }else{
                   8847:            fprintf(ficgp,", '' ");
                   8848:          }
                   8849:          l=(nlstate+ndeath)*(i-1)+1;
                   8850:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8851:          for (j=2; j<= nlstate+ndeath ; j ++)
                   8852:            fprintf(ficgp,"+$%d",k+l+j-1);
                   8853:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   8854:        } /* nlstate */
1.264     brouard  8855:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8856:       } /* end cpt state*/ 
                   8857:     } /* end nres */
1.337     brouard  8858:   /* } /\* end covariate k1 *\/   */
1.238     brouard  8859: 
1.220     brouard  8860: /* 5eme */
1.201     brouard  8861:   /* Survival functions (period) from state i in state j by final state j */
1.337     brouard  8862:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
1.238     brouard  8863:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8864:       k1=TKresult[nres];
1.338     brouard  8865:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8866:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8867:       /*       continue; */
1.238     brouard  8868:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  8869:        strcpy(gplotlabel,"(");
1.238     brouard  8870:        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  8871:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8872:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8873:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8874:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8875:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8876:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8877:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8878:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8879:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8880:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8881:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8882:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8883:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8884:        /* } */
                   8885:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8886:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8887:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8888:        }       
1.264     brouard  8889:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8890:        fprintf(ficgp,"\n#\n");
                   8891:        if(invalidvarcomb[k1]){
                   8892:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8893:          continue;
                   8894:        }
1.227     brouard  8895:       
1.241     brouard  8896:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  8897:        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  8898:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8899: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8900:        k=3;
                   8901:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8902:          if(j==1)
                   8903:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8904:          else
                   8905:            fprintf(ficgp,", '' ");
                   8906:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8907:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   8908:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   8909:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   8910:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   8911:        } /* nlstate */
                   8912:        fprintf(ficgp,", '' ");
                   8913:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   8914:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8915:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8916:          if(j < nlstate)
                   8917:            fprintf(ficgp,"$%d +",k+l);
                   8918:          else
                   8919:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   8920:        }
1.264     brouard  8921:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8922:       } /* end cpt state*/ 
1.337     brouard  8923:     /* } /\* end covariate *\/   */
1.238     brouard  8924:   } /* end nres */
1.227     brouard  8925:   
1.220     brouard  8926: /* 6eme */
1.202     brouard  8927:   /* CV preval stable (period) for each covariate */
1.337     brouard  8928:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8929:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8930:      k1=TKresult[nres];
1.338     brouard  8931:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8932:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8933:      /*  continue; */
1.255     brouard  8934:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  8935:       strcpy(gplotlabel,"(");      
1.288     brouard  8936:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8937:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8938:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8939:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8940:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8941:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8942:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8943:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8944:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8945:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8946:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8947:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8948:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8949:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8950:       /* } */
                   8951:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8952:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8953:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8954:       }        
1.264     brouard  8955:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8956:       fprintf(ficgp,"\n#\n");
1.223     brouard  8957:       if(invalidvarcomb[k1]){
1.227     brouard  8958:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8959:        continue;
1.223     brouard  8960:       }
1.227     brouard  8961:       
1.241     brouard  8962:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  8963:       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  8964:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8965: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  8966:       k=3; /* Offset */
1.255     brouard  8967:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  8968:        if(i==1)
                   8969:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8970:        else
                   8971:          fprintf(ficgp,", '' ");
1.255     brouard  8972:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  8973:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8974:        for (j=2; j<= nlstate ; j ++)
                   8975:          fprintf(ficgp,"+$%d",k+l+j-1);
                   8976:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  8977:       } /* nlstate */
1.264     brouard  8978:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  8979:     } /* end cpt state*/ 
                   8980:   } /* end covariate */  
1.227     brouard  8981:   
                   8982:   
1.220     brouard  8983: /* 7eme */
1.296     brouard  8984:   if(prevbcast == 1){
1.288     brouard  8985:     /* CV backward prevalence  for each covariate */
1.337     brouard  8986:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8987:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8988:       k1=TKresult[nres];
1.338     brouard  8989:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8990:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8991:       /*       continue; */
1.268     brouard  8992:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  8993:        strcpy(gplotlabel,"(");      
1.288     brouard  8994:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8995:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8996:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8997:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8998:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8999:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   9000:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9001:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9002:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9003:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9004:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9005:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9006:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9007:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9008:        /* } */
                   9009:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9010:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9011:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  9012:        }       
1.264     brouard  9013:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  9014:        fprintf(ficgp,"\n#\n");
                   9015:        if(invalidvarcomb[k1]){
                   9016:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9017:          continue;
                   9018:        }
                   9019:        
1.241     brouard  9020:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  9021:        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  9022:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  9023: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  9024:        k=3; /* Offset */
1.268     brouard  9025:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  9026:          if(i==1)
                   9027:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   9028:          else
                   9029:            fprintf(ficgp,", '' ");
                   9030:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  9031:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  9032:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   9033:          /* 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  9034:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  9035:          /* for (j=2; j<= nlstate ; j ++) */
                   9036:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   9037:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  9038:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  9039:        } /* nlstate */
1.264     brouard  9040:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  9041:       } /* end cpt state*/ 
                   9042:     } /* end covariate */  
1.296     brouard  9043:   } /* End if prevbcast */
1.218     brouard  9044:   
1.223     brouard  9045:   /* 8eme */
1.218     brouard  9046:   if(prevfcast==1){
1.288     brouard  9047:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  9048:     
1.337     brouard  9049:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  9050:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9051:       k1=TKresult[nres];
1.338     brouard  9052:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9053:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9054:       /*       continue; */
1.211     brouard  9055:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  9056:        strcpy(gplotlabel,"(");      
1.288     brouard  9057:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  9058:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9059:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9060:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9061:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9062:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9063:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9064:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9065:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9066:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9067:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9068:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9069:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9070:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9071:        /* } */
                   9072:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9073:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9074:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  9075:        }       
1.264     brouard  9076:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  9077:        fprintf(ficgp,"\n#\n");
                   9078:        if(invalidvarcomb[k1]){
                   9079:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9080:          continue;
                   9081:        }
                   9082:        
                   9083:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  9084:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  9085:        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  9086:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  9087: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  9088: 
                   9089:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   9090:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9091:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9092:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  9093:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9094:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9095:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9096:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  9097:          if(i==istart){
1.227     brouard  9098:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   9099:          }else{
                   9100:            fprintf(ficgp,",\\\n '' ");
                   9101:          }
                   9102:          if(cptcoveff ==0){ /* No covariate */
                   9103:            ioffset=2; /* Age is in 2 */
                   9104:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9105:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9106:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9107:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9108:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  9109:            if(i==nlstate+1){
1.270     brouard  9110:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  9111:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   9112:              fprintf(ficgp,",\\\n '' ");
                   9113:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  9114:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  9115:                     offyear,                           \
1.268     brouard  9116:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  9117:            }else
1.227     brouard  9118:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   9119:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   9120:          }else{ /* more than 2 covariates */
1.270     brouard  9121:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   9122:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9123:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   9124:            iyearc=ioffset-1;
                   9125:            iagec=ioffset;
1.227     brouard  9126:            fprintf(ficgp," u %d:(",ioffset); 
                   9127:            kl=0;
                   9128:            strcpy(gplotcondition,"(");
1.351     brouard  9129:            /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
1.332     brouard  9130:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
1.351     brouard  9131:            for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9132:              /* lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9133:              lv=Tvresult[nres][k];
                   9134:              vlv=TinvDoQresult[nres][Tvresult[nres][k]];
1.227     brouard  9135:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9136:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9137:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  9138:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
1.351     brouard  9139:              /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
1.227     brouard  9140:              kl++;
1.351     brouard  9141:              /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   9142:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,lv, kl+1, vlv );
1.227     brouard  9143:              kl++;
1.351     brouard  9144:              if(k <cptcovs && cptcovs>1)
1.227     brouard  9145:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9146:            }
                   9147:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9148:            /* 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 *\/ */
                   9149:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9150:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9151:            /* ''  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*/
                   9152:            if(i==nlstate+1){
1.270     brouard  9153:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   9154:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  9155:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  9156:              fprintf(ficgp," u %d:(",iagec); 
                   9157:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   9158:                      iyearc, iagec, offyear,                           \
                   9159:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  9160: /*  '' 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  9161:            }else{
                   9162:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   9163:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   9164:            }
                   9165:          } /* end if covariate */
                   9166:        } /* nlstate */
1.264     brouard  9167:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  9168:       } /* end cpt state*/
                   9169:     } /* end covariate */
                   9170:   } /* End if prevfcast */
1.227     brouard  9171:   
1.296     brouard  9172:   if(prevbcast==1){
1.268     brouard  9173:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   9174:     
1.337     brouard  9175:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.268     brouard  9176:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9177:      k1=TKresult[nres];
1.338     brouard  9178:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9179:        /* if(m != 1 && TKresult[nres]!= k1) */
                   9180:        /*      continue; */
1.268     brouard  9181:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   9182:        strcpy(gplotlabel,"(");      
                   9183:        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  9184:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9185:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9186:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9187:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9188:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9189:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9190:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9191:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9192:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9193:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9194:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9195:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9196:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9197:        /* } */
                   9198:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9199:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9200:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.268     brouard  9201:        }       
                   9202:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   9203:        fprintf(ficgp,"\n#\n");
                   9204:        if(invalidvarcomb[k1]){
                   9205:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9206:          continue;
                   9207:        }
                   9208:        
                   9209:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   9210:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   9211:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   9212:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   9213: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   9214: 
                   9215:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   9216:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9217:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9218:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   9219:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9220:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9221:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9222:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9223:          if(i==istart){
                   9224:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   9225:          }else{
                   9226:            fprintf(ficgp,",\\\n '' ");
                   9227:          }
1.351     brouard  9228:          /* if(cptcoveff ==0){ /\* No covariate *\/ */
                   9229:          if(cptcovs ==0){ /* No covariate */
1.268     brouard  9230:            ioffset=2; /* Age is in 2 */
                   9231:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9232:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9233:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9234:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9235:            fprintf(ficgp," u %d:(", ioffset); 
                   9236:            if(i==nlstate+1){
1.270     brouard  9237:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  9238:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   9239:              fprintf(ficgp,",\\\n '' ");
                   9240:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  9241:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  9242:                     offbyear,                          \
                   9243:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   9244:            }else
                   9245:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   9246:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   9247:          }else{ /* more than 2 covariates */
1.270     brouard  9248:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   9249:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9250:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   9251:            iyearc=ioffset-1;
                   9252:            iagec=ioffset;
1.268     brouard  9253:            fprintf(ficgp," u %d:(",ioffset); 
                   9254:            kl=0;
                   9255:            strcpy(gplotcondition,"(");
1.337     brouard  9256:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
1.338     brouard  9257:              if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
1.337     brouard  9258:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
                   9259:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9260:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9261:                lv=Tvresult[nres][k];
                   9262:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
                   9263:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9264:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9265:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   9266:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   9267:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9268:                kl++;
                   9269:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   9270:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
                   9271:                kl++;
1.338     brouard  9272:                if(k <cptcovs && cptcovs>1)
1.337     brouard  9273:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9274:              }
1.268     brouard  9275:            }
                   9276:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9277:            /* 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 *\/ */
                   9278:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9279:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9280:            /* ''  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*/
                   9281:            if(i==nlstate+1){
1.270     brouard  9282:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   9283:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  9284:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  9285:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  9286:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  9287:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   9288:                      iyearc,iagec,offbyear,                            \
                   9289:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  9290: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   9291:            }else{
                   9292:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   9293:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   9294:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   9295:            }
                   9296:          } /* end if covariate */
                   9297:        } /* nlstate */
                   9298:        fprintf(ficgp,"\nset out; unset label;\n");
                   9299:       } /* end cpt state*/
                   9300:     } /* end covariate */
1.296     brouard  9301:   } /* End if prevbcast */
1.268     brouard  9302:   
1.227     brouard  9303:   
1.238     brouard  9304:   /* 9eme writing MLE parameters */
                   9305:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  9306:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  9307:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  9308:     for(k=1; k <=(nlstate+ndeath); k++){
                   9309:       if (k != i) {
1.227     brouard  9310:        fprintf(ficgp,"#   current state %d\n",k);
                   9311:        for(j=1; j <=ncovmodel; j++){
                   9312:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   9313:          jk++; 
                   9314:        }
                   9315:        fprintf(ficgp,"\n");
1.126     brouard  9316:       }
                   9317:     }
1.223     brouard  9318:   }
1.187     brouard  9319:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  9320:   
1.145     brouard  9321:   /*goto avoid;*/
1.238     brouard  9322:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   9323:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  9324:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   9325:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   9326:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   9327:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   9328:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9329:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9330:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9331:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9332:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   9333:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9334:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   9335:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   9336:   fprintf(ficgp,"#\n");
1.223     brouard  9337:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  9338:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.338     brouard  9339:     fprintf(ficgp,"#model=1+age+%s \n",model);
1.238     brouard  9340:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.351     brouard  9341:     /* fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/\* to be checked *\/ */
                   9342:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcovs,m);/* to be checked */
1.337     brouard  9343:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
1.237     brouard  9344:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9345:      /* k1=nres; */
1.338     brouard  9346:       k1=TKresult[nres];
                   9347:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9348:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
1.264     brouard  9349:       strcpy(gplotlabel,"(");
1.276     brouard  9350:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.337     brouard  9351:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   9352:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
                   9353:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
                   9354:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9355:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9356:       }
                   9357:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9358:       /*       continue; */
                   9359:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
                   9360:       /* strcpy(gplotlabel,"("); */
                   9361:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
                   9362:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9363:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9364:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9365:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9366:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9367:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9368:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9369:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9370:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9371:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9372:       /* } */
                   9373:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9374:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9375:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9376:       /* }      */
1.264     brouard  9377:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  9378:       fprintf(ficgp,"\n#\n");
1.264     brouard  9379:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  9380:       fprintf(ficgp,"\nset key outside ");
                   9381:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   9382:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  9383:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   9384:       if (ng==1){
                   9385:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   9386:        fprintf(ficgp,"\nunset log y");
                   9387:       }else if (ng==2){
                   9388:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   9389:        fprintf(ficgp,"\nset log y");
                   9390:       }else if (ng==3){
                   9391:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   9392:        fprintf(ficgp,"\nset log y");
                   9393:       }else
                   9394:        fprintf(ficgp,"\nunset title ");
                   9395:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   9396:       i=1;
                   9397:       for(k2=1; k2<=nlstate; k2++) {
                   9398:        k3=i;
                   9399:        for(k=1; k<=(nlstate+ndeath); k++) {
                   9400:          if (k != k2){
                   9401:            switch( ng) {
                   9402:            case 1:
                   9403:              if(nagesqr==0)
                   9404:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   9405:              else /* nagesqr =1 */
                   9406:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9407:              break;
                   9408:            case 2: /* ng=2 */
                   9409:              if(nagesqr==0)
                   9410:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   9411:              else /* nagesqr =1 */
                   9412:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9413:              break;
                   9414:            case 3:
                   9415:              if(nagesqr==0)
                   9416:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   9417:              else /* nagesqr =1 */
                   9418:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   9419:              break;
                   9420:            }
                   9421:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  9422:            ijp=1; /* product no age */
                   9423:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   9424:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  9425:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  9426:              switch(Typevar[j]){
                   9427:              case 1:
                   9428:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9429:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   9430:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9431:                      if(DummyV[j]==0){/* Bug valgrind */
                   9432:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   9433:                      }else{ /* quantitative */
                   9434:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9435:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9436:                      }
                   9437:                      ij++;
1.268     brouard  9438:                    }
1.237     brouard  9439:                  }
1.329     brouard  9440:                }
                   9441:                break;
                   9442:              case 2:
                   9443:                if(cptcovprod >0){
                   9444:                  if(j==Tprod[ijp]) { /* */ 
                   9445:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9446:                    if(ijp <=cptcovprod) { /* Product */
                   9447:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9448:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9449:                          /* 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)]); */
                   9450:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9451:                        }else{ /* Vn is dummy and Vm is quanti */
                   9452:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9453:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9454:                        }
                   9455:                      }else{ /* Vn*Vm Vn is quanti */
                   9456:                        if(DummyV[Tvard[ijp][2]]==0){
                   9457:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9458:                        }else{ /* Both quanti */
                   9459:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9460:                        }
1.268     brouard  9461:                      }
1.329     brouard  9462:                      ijp++;
1.237     brouard  9463:                    }
1.329     brouard  9464:                  } /* end Tprod */
                   9465:                }
                   9466:                break;
1.349     brouard  9467:              case 3:
                   9468:                if(cptcovdageprod >0){
                   9469:                  /* if(j==Tprod[ijp]) { */ /* not necessary */ 
                   9470:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
1.350     brouard  9471:                    if(ijp <=cptcovprod) { /* Product Vn*Vm and age*VN*Vm*/
                   9472:                      if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   9473:                        if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  9474:                          /* 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)]); */
                   9475:                          fprintf(ficgp,"+p%d*%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9476:                        }else{ /* Vn is dummy and Vm is quanti */
                   9477:                          /* 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  9478:                          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  9479:                        }
1.350     brouard  9480:                      }else{ /* age* Vn*Vm Vn is quanti HERE */
1.349     brouard  9481:                        if(DummyV[Tvard[ijp][2]]==0){
1.350     brouard  9482:                          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  9483:                        }else{ /* Both quanti */
1.350     brouard  9484:                          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  9485:                        }
                   9486:                      }
                   9487:                      ijp++;
                   9488:                    }
                   9489:                    /* } */ /* end Tprod */
                   9490:                }
                   9491:                break;
1.329     brouard  9492:              case 0:
                   9493:                /* simple covariate */
1.264     brouard  9494:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  9495:                if(Dummy[j]==0){
                   9496:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   9497:                }else{ /* quantitative */
                   9498:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  9499:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  9500:                }
1.329     brouard  9501:               /* end simple */
                   9502:                break;
                   9503:              default:
                   9504:                break;
                   9505:              } /* end switch */
1.237     brouard  9506:            } /* end j */
1.329     brouard  9507:          }else{ /* k=k2 */
                   9508:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   9509:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   9510:            }else
                   9511:              i=i-ncovmodel;
1.223     brouard  9512:          }
1.227     brouard  9513:          
1.223     brouard  9514:          if(ng != 1){
                   9515:            fprintf(ficgp,")/(1");
1.227     brouard  9516:            
1.264     brouard  9517:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  9518:              if(nagesqr==0)
1.264     brouard  9519:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  9520:              else /* nagesqr =1 */
1.264     brouard  9521:                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  9522:               
1.223     brouard  9523:              ij=1;
1.329     brouard  9524:              ijp=1;
                   9525:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   9526:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   9527:                switch(Typevar[j]){
                   9528:                case 1:
                   9529:                  if(cptcovage >0){ 
                   9530:                    if(j==Tage[ij]) { /* Bug valgrind */
                   9531:                      if(ij <=cptcovage) { /* Bug valgrind */
                   9532:                        if(DummyV[j]==0){/* Bug valgrind */
                   9533:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   9534:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   9535:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   9536:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   9537:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9538:                        }else{ /* quantitative */
                   9539:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9540:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9541:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9542:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9543:                        }
                   9544:                        ij++;
                   9545:                      }
                   9546:                    }
                   9547:                  }
                   9548:                  break;
                   9549:                case 2:
                   9550:                  if(cptcovprod >0){
                   9551:                    if(j==Tprod[ijp]) { /* */ 
                   9552:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9553:                      if(ijp <=cptcovprod) { /* Product */
                   9554:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9555:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9556:                            /* 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)]); */
                   9557:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9558:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9559:                          }else{ /* Vn is dummy and Vm is quanti */
                   9560:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9561:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9562:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9563:                          }
                   9564:                        }else{ /* Vn*Vm Vn is quanti */
                   9565:                          if(DummyV[Tvard[ijp][2]]==0){
                   9566:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9567:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9568:                          }else{ /* Both quanti */
                   9569:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9570:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9571:                          } 
                   9572:                        }
                   9573:                        ijp++;
                   9574:                      }
                   9575:                    } /* end Tprod */
                   9576:                  } /* end if */
                   9577:                  break;
1.349     brouard  9578:                case 3:
                   9579:                  if(cptcovdageprod >0){
                   9580:                    /* if(j==Tprod[ijp]) { /\* *\/  */
                   9581:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9582:                      if(ijp <=cptcovprod) { /* Product */
1.350     brouard  9583:                        if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   9584:                          if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  9585:                            /* 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  9586:                            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  9587:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9588:                          }else{ /* Vn is dummy and Vm is quanti */
                   9589:                            /* 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  9590:                            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  9591:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9592:                          }
                   9593:                        }else{ /* Vn*Vm Vn is quanti */
1.350     brouard  9594:                          if(DummyV[Tvardk[ijp][2]]==0){
                   9595:                            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  9596:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9597:                          }else{ /* Both quanti */
1.350     brouard  9598:                            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  9599:                            /* fprintf(ficgp,"+p%d*%f*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9600:                          } 
                   9601:                        }
                   9602:                        ijp++;
                   9603:                      }
                   9604:                    /* } /\* end Tprod *\/ */
                   9605:                  } /* end if */
                   9606:                  break;
1.329     brouard  9607:                case 0: 
                   9608:                  /* simple covariate */
                   9609:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   9610:                  if(Dummy[j]==0){
                   9611:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9612:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   9613:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9614:                  }else{ /* quantitative */
                   9615:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   9616:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   9617:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9618:                  }
                   9619:                  /* end simple */
                   9620:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   9621:                  break;
                   9622:                default:
                   9623:                  break;
                   9624:                } /* end switch */
1.223     brouard  9625:              }
                   9626:              fprintf(ficgp,")");
                   9627:            }
                   9628:            fprintf(ficgp,")");
                   9629:            if(ng ==2)
1.276     brouard  9630:              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  9631:            else /* ng= 3 */
1.276     brouard  9632:              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  9633:           }else{ /* end ng <> 1 */
1.223     brouard  9634:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  9635:              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  9636:          }
                   9637:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   9638:            fprintf(ficgp,",");
                   9639:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   9640:            fprintf(ficgp,",");
                   9641:          i=i+ncovmodel;
                   9642:        } /* end k */
                   9643:       } /* end k2 */
1.276     brouard  9644:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   9645:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.337     brouard  9646:     } /* end resultline */
1.223     brouard  9647:   } /* end ng */
                   9648:   /* avoid: */
                   9649:   fflush(ficgp); 
1.126     brouard  9650: }  /* end gnuplot */
                   9651: 
                   9652: 
                   9653: /*************** Moving average **************/
1.219     brouard  9654: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  9655:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  9656:    
1.222     brouard  9657:    int i, cpt, cptcod;
                   9658:    int modcovmax =1;
                   9659:    int mobilavrange, mob;
                   9660:    int iage=0;
1.288     brouard  9661:    int firstA1=0, firstA2=0;
1.222     brouard  9662: 
1.266     brouard  9663:    double sum=0., sumr=0.;
1.222     brouard  9664:    double age;
1.266     brouard  9665:    double *sumnewp, *sumnewm, *sumnewmr;
                   9666:    double *agemingood, *agemaxgood; 
                   9667:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  9668:   
                   9669:   
1.278     brouard  9670:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   9671:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  9672: 
                   9673:    sumnewp = vector(1,ncovcombmax);
                   9674:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  9675:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  9676:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  9677:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  9678:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  9679:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  9680: 
                   9681:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  9682:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  9683:      sumnewp[cptcod]=0.;
1.266     brouard  9684:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   9685:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  9686:    }
                   9687:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   9688:   
1.266     brouard  9689:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   9690:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  9691:      else mobilavrange=mobilav;
                   9692:      for (age=bage; age<=fage; age++)
                   9693:        for (i=1; i<=nlstate;i++)
                   9694:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   9695:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9696:      /* We keep the original values on the extreme ages bage, fage and for 
                   9697:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   9698:        we use a 5 terms etc. until the borders are no more concerned. 
                   9699:      */ 
                   9700:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   9701:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  9702:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   9703:           sumnewm[cptcod]=0.;
                   9704:           for (i=1; i<=nlstate;i++){
1.222     brouard  9705:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   9706:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   9707:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   9708:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   9709:             }
                   9710:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  9711:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9712:           } /* end i */
                   9713:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   9714:         } /* end cptcod */
1.222     brouard  9715:        }/* end age */
                   9716:      }/* end mob */
1.266     brouard  9717:    }else{
                   9718:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  9719:      return -1;
1.266     brouard  9720:    }
                   9721: 
                   9722:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  9723:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   9724:      if(invalidvarcomb[cptcod]){
                   9725:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   9726:        continue;
                   9727:      }
1.219     brouard  9728: 
1.266     brouard  9729:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   9730:        sumnewm[cptcod]=0.;
                   9731:        sumnewmr[cptcod]=0.;
                   9732:        for (i=1; i<=nlstate;i++){
                   9733:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9734:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9735:        }
                   9736:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9737:         agemingoodr[cptcod]=age;
                   9738:        }
                   9739:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9740:           agemingood[cptcod]=age;
                   9741:        }
                   9742:      } /* age */
                   9743:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  9744:        sumnewm[cptcod]=0.;
1.266     brouard  9745:        sumnewmr[cptcod]=0.;
1.222     brouard  9746:        for (i=1; i<=nlstate;i++){
                   9747:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9748:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9749:        }
                   9750:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9751:         agemaxgoodr[cptcod]=age;
1.222     brouard  9752:        }
                   9753:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  9754:         agemaxgood[cptcod]=age;
                   9755:        }
                   9756:      } /* age */
                   9757:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   9758:      /* but they will change */
1.288     brouard  9759:      firstA1=0;firstA2=0;
1.266     brouard  9760:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   9761:        sumnewm[cptcod]=0.;
                   9762:        sumnewmr[cptcod]=0.;
                   9763:        for (i=1; i<=nlstate;i++){
                   9764:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9765:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9766:        }
                   9767:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9768:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9769:           agemaxgoodr[cptcod]=age;  /* age min */
                   9770:           for (i=1; i<=nlstate;i++)
                   9771:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9772:         }else{ /* bad we change the value with the values of good ages */
                   9773:           for (i=1; i<=nlstate;i++){
                   9774:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   9775:           } /* i */
                   9776:         } /* end bad */
                   9777:        }else{
                   9778:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9779:           agemaxgood[cptcod]=age;
                   9780:         }else{ /* bad we change the value with the values of good ages */
                   9781:           for (i=1; i<=nlstate;i++){
                   9782:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   9783:           } /* i */
                   9784:         } /* end bad */
                   9785:        }/* end else */
                   9786:        sum=0.;sumr=0.;
                   9787:        for (i=1; i<=nlstate;i++){
                   9788:         sum+=mobaverage[(int)age][i][cptcod];
                   9789:         sumr+=probs[(int)age][i][cptcod];
                   9790:        }
                   9791:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  9792:         if(!firstA1){
                   9793:           firstA1=1;
                   9794:           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);
                   9795:         }
                   9796:         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  9797:        } /* end bad */
                   9798:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9799:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  9800:         if(!firstA2){
                   9801:           firstA2=1;
                   9802:           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);
                   9803:         }
                   9804:         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  9805:        } /* end bad */
                   9806:      }/* age */
1.266     brouard  9807: 
                   9808:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  9809:        sumnewm[cptcod]=0.;
1.266     brouard  9810:        sumnewmr[cptcod]=0.;
1.222     brouard  9811:        for (i=1; i<=nlstate;i++){
                   9812:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9813:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9814:        } 
                   9815:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9816:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   9817:           agemingoodr[cptcod]=age;
                   9818:           for (i=1; i<=nlstate;i++)
                   9819:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9820:         }else{ /* bad we change the value with the values of good ages */
                   9821:           for (i=1; i<=nlstate;i++){
                   9822:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   9823:           } /* i */
                   9824:         } /* end bad */
                   9825:        }else{
                   9826:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9827:           agemingood[cptcod]=age;
                   9828:         }else{ /* bad */
                   9829:           for (i=1; i<=nlstate;i++){
                   9830:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   9831:           } /* i */
                   9832:         } /* end bad */
                   9833:        }/* end else */
                   9834:        sum=0.;sumr=0.;
                   9835:        for (i=1; i<=nlstate;i++){
                   9836:         sum+=mobaverage[(int)age][i][cptcod];
                   9837:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  9838:        }
1.266     brouard  9839:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  9840:         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  9841:        } /* end bad */
                   9842:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9843:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  9844:         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  9845:        } /* end bad */
                   9846:      }/* age */
1.266     brouard  9847: 
1.222     brouard  9848:                
                   9849:      for (age=bage; age<=fage; age++){
1.235     brouard  9850:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  9851:        sumnewp[cptcod]=0.;
                   9852:        sumnewm[cptcod]=0.;
                   9853:        for (i=1; i<=nlstate;i++){
                   9854:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   9855:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9856:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   9857:        }
                   9858:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   9859:      }
                   9860:      /* printf("\n"); */
                   9861:      /* } */
1.266     brouard  9862: 
1.222     brouard  9863:      /* brutal averaging */
1.266     brouard  9864:      /* for (i=1; i<=nlstate;i++){ */
                   9865:      /*   for (age=1; age<=bage; age++){ */
                   9866:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   9867:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9868:      /*   }     */
                   9869:      /*   for (age=fage; age<=AGESUP; age++){ */
                   9870:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   9871:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9872:      /*   } */
                   9873:      /* } /\* end i status *\/ */
                   9874:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   9875:      /*   for (age=1; age<=AGESUP; age++){ */
                   9876:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   9877:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   9878:      /*   } */
                   9879:      /* } */
1.222     brouard  9880:    }/* end cptcod */
1.266     brouard  9881:    free_vector(agemaxgoodr,1, ncovcombmax);
                   9882:    free_vector(agemaxgood,1, ncovcombmax);
                   9883:    free_vector(agemingood,1, ncovcombmax);
                   9884:    free_vector(agemingoodr,1, ncovcombmax);
                   9885:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  9886:    free_vector(sumnewm,1, ncovcombmax);
                   9887:    free_vector(sumnewp,1, ncovcombmax);
                   9888:    return 0;
                   9889:  }/* End movingaverage */
1.218     brouard  9890:  
1.126     brouard  9891: 
1.296     brouard  9892:  
1.126     brouard  9893: /************** Forecasting ******************/
1.296     brouard  9894: /* 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)*/
                   9895: 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){
                   9896:   /* dateintemean, mean date of interviews
                   9897:      dateprojd, year, month, day of starting projection 
                   9898:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  9899:      agemin, agemax range of age
                   9900:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   9901:   */
1.296     brouard  9902:   /* double anprojd, mprojd, jprojd; */
                   9903:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  9904:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  9905:   double agec; /* generic age */
1.296     brouard  9906:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  9907:   double *popeffectif,*popcount;
                   9908:   double ***p3mat;
1.218     brouard  9909:   /* double ***mobaverage; */
1.126     brouard  9910:   char fileresf[FILENAMELENGTH];
                   9911: 
                   9912:   agelim=AGESUP;
1.211     brouard  9913:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9914:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9915:      We still use firstpass and lastpass as another selection.
                   9916:   */
1.214     brouard  9917:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9918:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  9919:  
1.201     brouard  9920:   strcpy(fileresf,"F_"); 
                   9921:   strcat(fileresf,fileresu);
1.126     brouard  9922:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   9923:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   9924:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   9925:   }
1.235     brouard  9926:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   9927:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  9928: 
1.225     brouard  9929:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  9930: 
                   9931: 
                   9932:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9933:   if (stepm<=12) stepsize=1;
                   9934:   if(estepm < stepm){
                   9935:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9936:   }
1.270     brouard  9937:   else{
                   9938:     hstepm=estepm;   
                   9939:   }
                   9940:   if(estepm > stepm){ /* Yes every two year */
                   9941:     stepsize=2;
                   9942:   }
1.296     brouard  9943:   hstepm=hstepm/stepm;
1.126     brouard  9944: 
1.296     brouard  9945:   
                   9946:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9947:   /*                              fractional in yp1 *\/ */
                   9948:   /* aintmean=yp; */
                   9949:   /* yp2=modf((yp1*12),&yp); */
                   9950:   /* mintmean=yp; */
                   9951:   /* yp1=modf((yp2*30.5),&yp); */
                   9952:   /* jintmean=yp; */
                   9953:   /* if(jintmean==0) jintmean=1; */
                   9954:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  9955: 
1.296     brouard  9956: 
                   9957:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   9958:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   9959:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.351     brouard  9960:   /* i1=pow(2,cptcoveff); */
                   9961:   /* if (cptcovn < 1){i1=1;} */
1.126     brouard  9962:   
1.296     brouard  9963:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  9964:   
                   9965:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  9966:   
1.126     brouard  9967: /*           if (h==(int)(YEARM*yearp)){ */
1.351     brouard  9968:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9969:     k=TKresult[nres];
                   9970:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   9971:     /*  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) *\/ */
                   9972:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   9973:     /*   continue; */
                   9974:     /* if(invalidvarcomb[k]){ */
                   9975:     /*   printf("\nCombination (%d) projection ignored because no cases \n",k);  */
                   9976:     /*   continue; */
                   9977:     /* } */
1.227     brouard  9978:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
1.351     brouard  9979:     for(j=1;j<=cptcovs;j++){
                   9980:       /* for(j=1;j<=cptcoveff;j++) { */
                   9981:     /*   /\* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); *\/ */
                   9982:     /*   fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9983:     /* } */
                   9984:     /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9985:     /*   fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   9986:     /* } */
                   9987:       fprintf(ficresf," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.235     brouard  9988:     }
1.351     brouard  9989:  
1.227     brouard  9990:     fprintf(ficresf," yearproj age");
                   9991:     for(j=1; j<=nlstate+ndeath;j++){ 
                   9992:       for(i=1; i<=nlstate;i++)               
                   9993:        fprintf(ficresf," p%d%d",i,j);
                   9994:       fprintf(ficresf," wp.%d",j);
                   9995:     }
1.296     brouard  9996:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  9997:       fprintf(ficresf,"\n");
1.296     brouard  9998:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  9999:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   10000:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  10001:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   10002:        nhstepm = nhstepm/hstepm; 
                   10003:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10004:        oldm=oldms;savm=savms;
1.268     brouard  10005:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  10006:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  10007:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  10008:        for (h=0; h<=nhstepm; h++){
                   10009:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  10010:            break;
                   10011:          }
                   10012:        }
                   10013:        fprintf(ficresf,"\n");
1.351     brouard  10014:        /* for(j=1;j<=cptcoveff;j++)  */
                   10015:        for(j=1;j<=cptcovs;j++) 
                   10016:          fprintf(ficresf,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.332     brouard  10017:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
1.351     brouard  10018:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* TnsdVar[Tvaraff]  correct *\/ */
1.296     brouard  10019:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  10020:        
                   10021:        for(j=1; j<=nlstate+ndeath;j++) {
                   10022:          ppij=0.;
                   10023:          for(i=1; i<=nlstate;i++) {
1.278     brouard  10024:            if (mobilav>=1)
                   10025:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   10026:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   10027:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   10028:            }
1.268     brouard  10029:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   10030:          } /* end i */
                   10031:          fprintf(ficresf," %.3f", ppij);
                   10032:        }/* end j */
1.227     brouard  10033:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10034:       } /* end agec */
1.266     brouard  10035:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   10036:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  10037:     } /* end yearp */
                   10038:   } /* end  k */
1.219     brouard  10039:        
1.126     brouard  10040:   fclose(ficresf);
1.215     brouard  10041:   printf("End of Computing forecasting \n");
                   10042:   fprintf(ficlog,"End of Computing forecasting\n");
                   10043: 
1.126     brouard  10044: }
                   10045: 
1.269     brouard  10046: /************** Back Forecasting ******************/
1.296     brouard  10047:  /* 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){ */
                   10048:  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){
                   10049:   /* back1, year, month, day of starting backprojection
1.267     brouard  10050:      agemin, agemax range of age
                   10051:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  10052:      anback2 year of end of backprojection (same day and month as back1).
                   10053:      prevacurrent and prev are prevalences.
1.267     brouard  10054:   */
                   10055:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   10056:   double agec; /* generic age */
1.302     brouard  10057:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  10058:   double *popeffectif,*popcount;
                   10059:   double ***p3mat;
                   10060:   /* double ***mobaverage; */
                   10061:   char fileresfb[FILENAMELENGTH];
                   10062:  
1.268     brouard  10063:   agelim=AGEINF;
1.267     brouard  10064:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   10065:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   10066:      We still use firstpass and lastpass as another selection.
                   10067:   */
                   10068:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   10069:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   10070: 
                   10071:   /*Do we need to compute prevalence again?*/
                   10072: 
                   10073:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   10074:   
                   10075:   strcpy(fileresfb,"FB_");
                   10076:   strcat(fileresfb,fileresu);
                   10077:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   10078:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   10079:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   10080:   }
                   10081:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   10082:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   10083:   
                   10084:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   10085:   
                   10086:    
                   10087:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10088:   if (stepm<=12) stepsize=1;
                   10089:   if(estepm < stepm){
                   10090:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   10091:   }
1.270     brouard  10092:   else{
                   10093:     hstepm=estepm;   
                   10094:   }
                   10095:   if(estepm >= stepm){ /* Yes every two year */
                   10096:     stepsize=2;
                   10097:   }
1.267     brouard  10098:   
                   10099:   hstepm=hstepm/stepm;
1.296     brouard  10100:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   10101:   /*                              fractional in yp1 *\/ */
                   10102:   /* aintmean=yp; */
                   10103:   /* yp2=modf((yp1*12),&yp); */
                   10104:   /* mintmean=yp; */
                   10105:   /* yp1=modf((yp2*30.5),&yp); */
                   10106:   /* jintmean=yp; */
                   10107:   /* if(jintmean==0) jintmean=1; */
                   10108:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  10109:   
1.351     brouard  10110:   /* i1=pow(2,cptcoveff); */
                   10111:   /* if (cptcovn < 1){i1=1;} */
1.267     brouard  10112:   
1.296     brouard  10113:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   10114:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  10115:   
                   10116:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   10117:   
1.351     brouard  10118:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10119:     k=TKresult[nres];
                   10120:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   10121:   /* for(k=1; k<=i1;k++){ */
                   10122:   /*   if(i1 != 1 && TKresult[nres]!= k) */
                   10123:   /*     continue; */
                   10124:   /*   if(invalidvarcomb[k]){ */
                   10125:   /*     printf("\nCombination (%d) projection ignored because no cases \n",k);  */
                   10126:   /*     continue; */
                   10127:   /*   } */
1.268     brouard  10128:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.351     brouard  10129:     for(j=1;j<=cptcovs;j++){
                   10130:     /* for(j=1;j<=cptcoveff;j++) { */
                   10131:     /*   fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10132:     /* } */
                   10133:       fprintf(ficresfb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.267     brouard  10134:     }
1.351     brouard  10135:    /*  fprintf(ficrespij,"******\n"); */
                   10136:    /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10137:    /*    fprintf(ficresfb," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10138:    /*  } */
1.267     brouard  10139:     fprintf(ficresfb," yearbproj age");
                   10140:     for(j=1; j<=nlstate+ndeath;j++){
                   10141:       for(i=1; i<=nlstate;i++)
1.268     brouard  10142:        fprintf(ficresfb," b%d%d",i,j);
                   10143:       fprintf(ficresfb," b.%d",j);
1.267     brouard  10144:     }
1.296     brouard  10145:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  10146:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   10147:       fprintf(ficresfb,"\n");
1.296     brouard  10148:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  10149:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  10150:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   10151:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  10152:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  10153:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  10154:        nhstepm = nhstepm/hstepm;
                   10155:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10156:        oldm=oldms;savm=savms;
1.268     brouard  10157:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  10158:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  10159:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  10160:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   10161:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   10162:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  10163:        for (h=0; h<=nhstepm; h++){
1.268     brouard  10164:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   10165:            break;
                   10166:          }
                   10167:        }
                   10168:        fprintf(ficresfb,"\n");
1.351     brouard  10169:        /* for(j=1;j<=cptcoveff;j++) */
                   10170:        for(j=1;j<=cptcovs;j++)
                   10171:          fprintf(ficresfb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10172:          /* fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.296     brouard  10173:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  10174:        for(i=1; i<=nlstate+ndeath;i++) {
                   10175:          ppij=0.;ppi=0.;
                   10176:          for(j=1; j<=nlstate;j++) {
                   10177:            /* if (mobilav==1) */
1.269     brouard  10178:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   10179:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   10180:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   10181:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  10182:              /* else { */
                   10183:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   10184:              /* } */
1.268     brouard  10185:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   10186:          } /* end j */
                   10187:          if(ppi <0.99){
                   10188:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   10189:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   10190:          }
                   10191:          fprintf(ficresfb," %.3f", ppij);
                   10192:        }/* end j */
1.267     brouard  10193:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10194:       } /* end agec */
                   10195:     } /* end yearp */
                   10196:   } /* end k */
1.217     brouard  10197:   
1.267     brouard  10198:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  10199:   
1.267     brouard  10200:   fclose(ficresfb);
                   10201:   printf("End of Computing Back forecasting \n");
                   10202:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  10203:        
1.267     brouard  10204: }
1.217     brouard  10205: 
1.269     brouard  10206: /* Variance of prevalence limit: varprlim */
                   10207:  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  10208:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  10209:  
                   10210:    char fileresvpl[FILENAMELENGTH];  
                   10211:    FILE *ficresvpl;
                   10212:    double **oldm, **savm;
                   10213:    double **varpl; /* Variances of prevalence limits by age */   
                   10214:    int i1, k, nres, j ;
                   10215:    
                   10216:     strcpy(fileresvpl,"VPL_");
                   10217:     strcat(fileresvpl,fileresu);
                   10218:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  10219:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  10220:       exit(0);
                   10221:     }
1.288     brouard  10222:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   10223:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  10224:     
                   10225:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   10226:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   10227:     
                   10228:     i1=pow(2,cptcoveff);
                   10229:     if (cptcovn < 1){i1=1;}
                   10230: 
1.337     brouard  10231:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10232:        k=TKresult[nres];
1.338     brouard  10233:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  10234:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
1.269     brouard  10235:       if(i1 != 1 && TKresult[nres]!= k)
                   10236:        continue;
                   10237:       fprintf(ficresvpl,"\n#****** ");
                   10238:       printf("\n#****** ");
                   10239:       fprintf(ficlog,"\n#****** ");
1.337     brouard  10240:       for(j=1;j<=cptcovs;j++) {
                   10241:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10242:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10243:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10244:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10245:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.269     brouard  10246:       }
1.337     brouard  10247:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   10248:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10249:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10250:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10251:       /* }      */
1.269     brouard  10252:       fprintf(ficresvpl,"******\n");
                   10253:       printf("******\n");
                   10254:       fprintf(ficlog,"******\n");
                   10255:       
                   10256:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10257:       oldm=oldms;savm=savms;
                   10258:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   10259:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   10260:       /*}*/
                   10261:     }
                   10262:     
                   10263:     fclose(ficresvpl);
1.288     brouard  10264:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   10265:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  10266: 
                   10267:  }
                   10268: /* Variance of back prevalence: varbprlim */
                   10269:  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){
                   10270:       /*------- Variance of back (stable) prevalence------*/
                   10271: 
                   10272:    char fileresvbl[FILENAMELENGTH];  
                   10273:    FILE  *ficresvbl;
                   10274: 
                   10275:    double **oldm, **savm;
                   10276:    double **varbpl; /* Variances of back prevalence limits by age */   
                   10277:    int i1, k, nres, j ;
                   10278: 
                   10279:    strcpy(fileresvbl,"VBL_");
                   10280:    strcat(fileresvbl,fileresu);
                   10281:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   10282:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   10283:      exit(0);
                   10284:    }
                   10285:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   10286:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   10287:    
                   10288:    
                   10289:    i1=pow(2,cptcoveff);
                   10290:    if (cptcovn < 1){i1=1;}
                   10291:    
1.337     brouard  10292:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10293:      k=TKresult[nres];
1.338     brouard  10294:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  10295:     /* for(k=1; k<=i1;k++){ */
                   10296:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   10297:     /*          continue; */
1.269     brouard  10298:        fprintf(ficresvbl,"\n#****** ");
                   10299:        printf("\n#****** ");
                   10300:        fprintf(ficlog,"\n#****** ");
1.337     brouard  10301:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
1.338     brouard  10302:         printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10303:         fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10304:         fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
1.337     brouard  10305:        /* for(j=1;j<=cptcoveff;j++) { */
                   10306:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10307:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10308:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10309:        /* } */
                   10310:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   10311:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10312:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10313:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
1.269     brouard  10314:        }
                   10315:        fprintf(ficresvbl,"******\n");
                   10316:        printf("******\n");
                   10317:        fprintf(ficlog,"******\n");
                   10318:        
                   10319:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10320:        oldm=oldms;savm=savms;
                   10321:        
                   10322:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   10323:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   10324:        /*}*/
                   10325:      }
                   10326:    
                   10327:    fclose(ficresvbl);
                   10328:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   10329:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   10330: 
                   10331:  } /* End of varbprlim */
                   10332: 
1.126     brouard  10333: /************** Forecasting *****not tested NB*************/
1.227     brouard  10334: /* 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  10335:   
1.227     brouard  10336: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   10337: /*   int *popage; */
                   10338: /*   double calagedatem, agelim, kk1, kk2; */
                   10339: /*   double *popeffectif,*popcount; */
                   10340: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   10341: /*   /\* double ***mobaverage; *\/ */
                   10342: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  10343: 
1.227     brouard  10344: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10345: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10346: /*   agelim=AGESUP; */
                   10347: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  10348:   
1.227     brouard  10349: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  10350:   
                   10351:   
1.227     brouard  10352: /*   strcpy(filerespop,"POP_");  */
                   10353: /*   strcat(filerespop,fileresu); */
                   10354: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   10355: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   10356: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   10357: /*   } */
                   10358: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   10359: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  10360: 
1.227     brouard  10361: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  10362: 
1.227     brouard  10363: /*   /\* if (mobilav!=0) { *\/ */
                   10364: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   10365: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   10366: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10367: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10368: /*   /\*   } *\/ */
                   10369: /*   /\* } *\/ */
1.126     brouard  10370: 
1.227     brouard  10371: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   10372: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  10373:   
1.227     brouard  10374: /*   agelim=AGESUP; */
1.126     brouard  10375:   
1.227     brouard  10376: /*   hstepm=1; */
                   10377: /*   hstepm=hstepm/stepm;  */
1.218     brouard  10378:        
1.227     brouard  10379: /*   if (popforecast==1) { */
                   10380: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   10381: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   10382: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   10383: /*     }  */
                   10384: /*     popage=ivector(0,AGESUP); */
                   10385: /*     popeffectif=vector(0,AGESUP); */
                   10386: /*     popcount=vector(0,AGESUP); */
1.126     brouard  10387:     
1.227     brouard  10388: /*     i=1;    */
                   10389: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  10390:     
1.227     brouard  10391: /*     imx=i; */
                   10392: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   10393: /*   } */
1.218     brouard  10394:   
1.227     brouard  10395: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   10396: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   10397: /*       k=k+1; */
                   10398: /*       fprintf(ficrespop,"\n#******"); */
                   10399: /*       for(j=1;j<=cptcoveff;j++) { */
                   10400: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   10401: /*       } */
                   10402: /*       fprintf(ficrespop,"******\n"); */
                   10403: /*       fprintf(ficrespop,"# Age"); */
                   10404: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   10405: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  10406:       
1.227     brouard  10407: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   10408: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  10409:        
1.227     brouard  10410: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10411: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10412: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10413:          
1.227     brouard  10414: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10415: /*       oldm=oldms;savm=savms; */
                   10416: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  10417:          
1.227     brouard  10418: /*       for (h=0; h<=nhstepm; h++){ */
                   10419: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10420: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10421: /*         }  */
                   10422: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10423: /*           kk1=0.;kk2=0; */
                   10424: /*           for(i=1; i<=nlstate;i++) {               */
                   10425: /*             if (mobilav==1)  */
                   10426: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   10427: /*             else { */
                   10428: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   10429: /*             } */
                   10430: /*           } */
                   10431: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   10432: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   10433: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   10434: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   10435: /*           } */
                   10436: /*         } */
                   10437: /*         for(i=1; i<=nlstate;i++){ */
                   10438: /*           kk1=0.; */
                   10439: /*           for(j=1; j<=nlstate;j++){ */
                   10440: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   10441: /*           } */
                   10442: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   10443: /*         } */
1.218     brouard  10444:            
1.227     brouard  10445: /*         if (h==(int)(calagedatem+12*cpt)) */
                   10446: /*           for(j=1; j<=nlstate;j++)  */
                   10447: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   10448: /*       } */
                   10449: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10450: /*     } */
                   10451: /*       } */
1.218     brouard  10452:       
1.227     brouard  10453: /*       /\******\/ */
1.218     brouard  10454:       
1.227     brouard  10455: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   10456: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   10457: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10458: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10459: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10460:          
1.227     brouard  10461: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10462: /*       oldm=oldms;savm=savms; */
                   10463: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   10464: /*       for (h=0; h<=nhstepm; h++){ */
                   10465: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10466: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10467: /*         }  */
                   10468: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10469: /*           kk1=0.;kk2=0; */
                   10470: /*           for(i=1; i<=nlstate;i++) {               */
                   10471: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   10472: /*           } */
                   10473: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   10474: /*         } */
                   10475: /*       } */
                   10476: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10477: /*     } */
                   10478: /*       } */
                   10479: /*     }  */
                   10480: /*   } */
1.218     brouard  10481:   
1.227     brouard  10482: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  10483:   
1.227     brouard  10484: /*   if (popforecast==1) { */
                   10485: /*     free_ivector(popage,0,AGESUP); */
                   10486: /*     free_vector(popeffectif,0,AGESUP); */
                   10487: /*     free_vector(popcount,0,AGESUP); */
                   10488: /*   } */
                   10489: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10490: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10491: /*   fclose(ficrespop); */
                   10492: /* } /\* End of popforecast *\/ */
1.218     brouard  10493:  
1.126     brouard  10494: int fileappend(FILE *fichier, char *optionfich)
                   10495: {
                   10496:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   10497:     printf("Problem with file: %s\n", optionfich);
                   10498:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   10499:     return (0);
                   10500:   }
                   10501:   fflush(fichier);
                   10502:   return (1);
                   10503: }
                   10504: 
                   10505: 
                   10506: /**************** function prwizard **********************/
                   10507: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   10508: {
                   10509: 
                   10510:   /* Wizard to print covariance matrix template */
                   10511: 
1.164     brouard  10512:   char ca[32], cb[32];
                   10513:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  10514:   int numlinepar;
                   10515: 
                   10516:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10517:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10518:   for(i=1; i <=nlstate; i++){
                   10519:     jj=0;
                   10520:     for(j=1; j <=nlstate+ndeath; j++){
                   10521:       if(j==i) continue;
                   10522:       jj++;
                   10523:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   10524:       printf("%1d%1d",i,j);
                   10525:       fprintf(ficparo,"%1d%1d",i,j);
                   10526:       for(k=1; k<=ncovmodel;k++){
                   10527:        /*        printf(" %lf",param[i][j][k]); */
                   10528:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   10529:        printf(" 0.");
                   10530:        fprintf(ficparo," 0.");
                   10531:       }
                   10532:       printf("\n");
                   10533:       fprintf(ficparo,"\n");
                   10534:     }
                   10535:   }
                   10536:   printf("# Scales (for hessian or gradient estimation)\n");
                   10537:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   10538:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   10539:   for(i=1; i <=nlstate; i++){
                   10540:     jj=0;
                   10541:     for(j=1; j <=nlstate+ndeath; j++){
                   10542:       if(j==i) continue;
                   10543:       jj++;
                   10544:       fprintf(ficparo,"%1d%1d",i,j);
                   10545:       printf("%1d%1d",i,j);
                   10546:       fflush(stdout);
                   10547:       for(k=1; k<=ncovmodel;k++){
                   10548:        /*      printf(" %le",delti3[i][j][k]); */
                   10549:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   10550:        printf(" 0.");
                   10551:        fprintf(ficparo," 0.");
                   10552:       }
                   10553:       numlinepar++;
                   10554:       printf("\n");
                   10555:       fprintf(ficparo,"\n");
                   10556:     }
                   10557:   }
                   10558:   printf("# Covariance matrix\n");
                   10559: /* # 121 Var(a12)\n\ */
                   10560: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10561: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10562: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10563: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10564: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10565: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10566: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10567:   fflush(stdout);
                   10568:   fprintf(ficparo,"# Covariance matrix\n");
                   10569:   /* # 121 Var(a12)\n\ */
                   10570:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10571:   /* #   ...\n\ */
                   10572:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   10573:   
                   10574:   for(itimes=1;itimes<=2;itimes++){
                   10575:     jj=0;
                   10576:     for(i=1; i <=nlstate; i++){
                   10577:       for(j=1; j <=nlstate+ndeath; j++){
                   10578:        if(j==i) continue;
                   10579:        for(k=1; k<=ncovmodel;k++){
                   10580:          jj++;
                   10581:          ca[0]= k+'a'-1;ca[1]='\0';
                   10582:          if(itimes==1){
                   10583:            printf("#%1d%1d%d",i,j,k);
                   10584:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   10585:          }else{
                   10586:            printf("%1d%1d%d",i,j,k);
                   10587:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   10588:            /*  printf(" %.5le",matcov[i][j]); */
                   10589:          }
                   10590:          ll=0;
                   10591:          for(li=1;li <=nlstate; li++){
                   10592:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   10593:              if(lj==li) continue;
                   10594:              for(lk=1;lk<=ncovmodel;lk++){
                   10595:                ll++;
                   10596:                if(ll<=jj){
                   10597:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   10598:                  if(ll<jj){
                   10599:                    if(itimes==1){
                   10600:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10601:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10602:                    }else{
                   10603:                      printf(" 0.");
                   10604:                      fprintf(ficparo," 0.");
                   10605:                    }
                   10606:                  }else{
                   10607:                    if(itimes==1){
                   10608:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   10609:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   10610:                    }else{
                   10611:                      printf(" 0.");
                   10612:                      fprintf(ficparo," 0.");
                   10613:                    }
                   10614:                  }
                   10615:                }
                   10616:              } /* end lk */
                   10617:            } /* end lj */
                   10618:          } /* end li */
                   10619:          printf("\n");
                   10620:          fprintf(ficparo,"\n");
                   10621:          numlinepar++;
                   10622:        } /* end k*/
                   10623:       } /*end j */
                   10624:     } /* end i */
                   10625:   } /* end itimes */
                   10626: 
                   10627: } /* end of prwizard */
                   10628: /******************* Gompertz Likelihood ******************************/
                   10629: double gompertz(double x[])
                   10630: { 
1.302     brouard  10631:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  10632:   int i,n=0; /* n is the size of the sample */
                   10633: 
1.220     brouard  10634:   for (i=1;i<=imx ; i++) {
1.126     brouard  10635:     sump=sump+weight[i];
                   10636:     /*    sump=sump+1;*/
                   10637:     num=num+1;
                   10638:   }
1.302     brouard  10639:   L=0.0;
                   10640:   /* agegomp=AGEGOMP; */
1.126     brouard  10641:   /* for (i=0; i<=imx; i++) 
                   10642:      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]);*/
                   10643: 
1.302     brouard  10644:   for (i=1;i<=imx ; i++) {
                   10645:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   10646:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   10647:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   10648:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   10649:      * +
                   10650:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   10651:      */
                   10652:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   10653:        if (cens[i] == 1){
                   10654:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   10655:        } else if (cens[i] == 0){
1.126     brouard  10656:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  10657:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   10658:       } else
                   10659:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  10660:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  10661:        L=L+A*weight[i];
1.126     brouard  10662:        /*      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  10663:      }
                   10664:   }
1.126     brouard  10665: 
1.302     brouard  10666:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  10667:  
                   10668:   return -2*L*num/sump;
                   10669: }
                   10670: 
1.136     brouard  10671: #ifdef GSL
                   10672: /******************* Gompertz_f Likelihood ******************************/
                   10673: double gompertz_f(const gsl_vector *v, void *params)
                   10674: { 
1.302     brouard  10675:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  10676:   double *x= (double *) v->data;
                   10677:   int i,n=0; /* n is the size of the sample */
                   10678: 
                   10679:   for (i=0;i<=imx-1 ; i++) {
                   10680:     sump=sump+weight[i];
                   10681:     /*    sump=sump+1;*/
                   10682:     num=num+1;
                   10683:   }
                   10684:  
                   10685:  
                   10686:   /* for (i=0; i<=imx; i++) 
                   10687:      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]);*/
                   10688:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   10689:   for (i=1;i<=imx ; i++)
                   10690:     {
                   10691:       if (cens[i] == 1 && wav[i]>1)
                   10692:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   10693:       
                   10694:       if (cens[i] == 0 && wav[i]>1)
                   10695:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   10696:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   10697:       
                   10698:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   10699:       if (wav[i] > 1 ) { /* ??? */
                   10700:        LL=LL+A*weight[i];
                   10701:        /*      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]);*/
                   10702:       }
                   10703:     }
                   10704: 
                   10705:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   10706:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   10707:  
                   10708:   return -2*LL*num/sump;
                   10709: }
                   10710: #endif
                   10711: 
1.126     brouard  10712: /******************* Printing html file ***********/
1.201     brouard  10713: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  10714:                  int lastpass, int stepm, int weightopt, char model[],\
                   10715:                  int imx,  double p[],double **matcov,double agemortsup){
                   10716:   int i,k;
                   10717: 
                   10718:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   10719:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   10720:   for (i=1;i<=2;i++) 
                   10721:     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  10722:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  10723:   fprintf(fichtm,"</ul>");
                   10724: 
                   10725: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   10726: 
                   10727:  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>");
                   10728: 
                   10729:  for (k=agegomp;k<(agemortsup-2);k++) 
                   10730:    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]);
                   10731: 
                   10732:  
                   10733:   fflush(fichtm);
                   10734: }
                   10735: 
                   10736: /******************* Gnuplot file **************/
1.201     brouard  10737: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  10738: 
                   10739:   char dirfileres[132],optfileres[132];
1.164     brouard  10740: 
1.126     brouard  10741:   int ng;
                   10742: 
                   10743: 
                   10744:   /*#ifdef windows */
                   10745:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   10746:     /*#endif */
                   10747: 
                   10748: 
                   10749:   strcpy(dirfileres,optionfilefiname);
                   10750:   strcpy(optfileres,"vpl");
1.199     brouard  10751:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  10752:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  10753:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  10754:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  10755:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   10756: 
                   10757: } 
                   10758: 
1.136     brouard  10759: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   10760: {
1.126     brouard  10761: 
1.136     brouard  10762:   /*-------- data file ----------*/
                   10763:   FILE *fic;
                   10764:   char dummy[]="                         ";
1.240     brouard  10765:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  10766:   int lstra;
1.136     brouard  10767:   int linei, month, year,iout;
1.302     brouard  10768:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  10769:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  10770:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  10771:   char *stratrunc;
1.223     brouard  10772: 
1.349     brouard  10773:   /* DummyV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
                   10774:   /* FixedV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
1.339     brouard  10775:   
                   10776:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
                   10777:   
1.136     brouard  10778:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  10779:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10780:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  10781:   }
1.126     brouard  10782: 
1.302     brouard  10783:     /* Is it a BOM UTF-8 Windows file? */
                   10784:   /* First data line */
                   10785:   linei=0;
                   10786:   while(fgets(line, MAXLINE, fic)) {
                   10787:     noffset=0;
                   10788:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   10789:     {
                   10790:       noffset=noffset+3;
                   10791:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   10792:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   10793:       fflush(ficlog); return 1;
                   10794:     }
                   10795:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   10796:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   10797:     {
                   10798:       noffset=noffset+2;
1.304     brouard  10799:       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);
                   10800:       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  10801:       fflush(ficlog); return 1;
                   10802:     }
                   10803:     else if( line[0] == 0 && line[1] == 0)
                   10804:     {
                   10805:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   10806:        noffset=noffset+4;
1.304     brouard  10807:        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);
                   10808:        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  10809:        fflush(ficlog); return 1;
                   10810:       }
                   10811:     } else{
                   10812:       ;/*printf(" Not a BOM file\n");*/
                   10813:     }
                   10814:         /* If line starts with a # it is a comment */
                   10815:     if (line[noffset] == '#') {
                   10816:       linei=linei+1;
                   10817:       break;
                   10818:     }else{
                   10819:       break;
                   10820:     }
                   10821:   }
                   10822:   fclose(fic);
                   10823:   if((fic=fopen(datafile,"r"))==NULL)    {
                   10824:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10825:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   10826:   }
                   10827:   /* Not a Bom file */
                   10828:   
1.136     brouard  10829:   i=1;
                   10830:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   10831:     linei=linei+1;
                   10832:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   10833:       if(line[j] == '\t')
                   10834:        line[j] = ' ';
                   10835:     }
                   10836:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   10837:       ;
                   10838:     };
                   10839:     line[j+1]=0;  /* Trims blanks at end of line */
                   10840:     if(line[0]=='#'){
                   10841:       fprintf(ficlog,"Comment line\n%s\n",line);
                   10842:       printf("Comment line\n%s\n",line);
                   10843:       continue;
                   10844:     }
                   10845:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  10846:     strcpy(line, linetmp);
1.223     brouard  10847:     
                   10848:     /* Loops on waves */
                   10849:     for (j=maxwav;j>=1;j--){
                   10850:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  10851:        cutv(stra, strb, line, ' '); 
                   10852:        if(strb[0]=='.') { /* Missing value */
                   10853:          lval=-1;
                   10854:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
1.341     brouard  10855:          cotvar[j][ncovcol+nqv+ntv+iv][i]=-1; /* For performance reasons */
1.238     brouard  10856:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   10857:            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);
                   10858:            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);
                   10859:            return 1;
                   10860:          }
                   10861:        }else{
                   10862:          errno=0;
                   10863:          /* what_kind_of_number(strb); */
                   10864:          dval=strtod(strb,&endptr); 
                   10865:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   10866:          /* if(strb != endptr && *endptr == '\0') */
                   10867:          /*    dval=dlval; */
                   10868:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10869:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10870:            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);
                   10871:            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);
                   10872:            return 1;
                   10873:          }
                   10874:          cotqvar[j][iv][i]=dval; 
1.341     brouard  10875:          cotvar[j][ncovcol+nqv+ntv+iv][i]=dval; /* because cotvar starts now at first ntv */ 
1.238     brouard  10876:        }
                   10877:        strcpy(line,stra);
1.223     brouard  10878:       }/* end loop ntqv */
1.225     brouard  10879:       
1.223     brouard  10880:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  10881:        cutv(stra, strb, line, ' '); 
                   10882:        if(strb[0]=='.') { /* Missing value */
                   10883:          lval=-1;
                   10884:        }else{
                   10885:          errno=0;
                   10886:          lval=strtol(strb,&endptr,10); 
                   10887:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10888:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10889:            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);
                   10890:            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);
                   10891:            return 1;
                   10892:          }
                   10893:        }
                   10894:        if(lval <-1 || lval >1){
                   10895:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10896:  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  10897:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10898:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10899:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10900:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10901:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10902:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10903:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  10904:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10905:  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  10906:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10907:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10908:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10909:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10910:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10911:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10912:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  10913:          return 1;
                   10914:        }
1.341     brouard  10915:        cotvar[j][ncovcol+nqv+iv][i]=(double)(lval);
1.238     brouard  10916:        strcpy(line,stra);
1.223     brouard  10917:       }/* end loop ntv */
1.225     brouard  10918:       
1.223     brouard  10919:       /* Statuses  at wave */
1.137     brouard  10920:       cutv(stra, strb, line, ' '); 
1.223     brouard  10921:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  10922:        lval=-1;
1.136     brouard  10923:       }else{
1.238     brouard  10924:        errno=0;
                   10925:        lval=strtol(strb,&endptr,10); 
                   10926:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
1.347     brouard  10927:        if( strb[0]=='\0' || (*endptr != '\0' )){
                   10928:          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);
                   10929:          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);
                   10930:          return 1;
                   10931:        }else if( lval==0 || lval > nlstate+ndeath){
1.348     brouard  10932:          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);
                   10933:          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  10934:          return 1;
                   10935:        }
1.136     brouard  10936:       }
1.225     brouard  10937:       
1.136     brouard  10938:       s[j][i]=lval;
1.225     brouard  10939:       
1.223     brouard  10940:       /* Date of Interview */
1.136     brouard  10941:       strcpy(line,stra);
                   10942:       cutv(stra, strb,line,' ');
1.169     brouard  10943:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10944:       }
1.169     brouard  10945:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  10946:        month=99;
                   10947:        year=9999;
1.136     brouard  10948:       }else{
1.225     brouard  10949:        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);
                   10950:        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);
                   10951:        return 1;
1.136     brouard  10952:       }
                   10953:       anint[j][i]= (double) year; 
1.302     brouard  10954:       mint[j][i]= (double)month;
                   10955:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   10956:       /*       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]); */
                   10957:       /*       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]); */
                   10958:       /* } */
1.136     brouard  10959:       strcpy(line,stra);
1.223     brouard  10960:     } /* End loop on waves */
1.225     brouard  10961:     
1.223     brouard  10962:     /* Date of death */
1.136     brouard  10963:     cutv(stra, strb,line,' '); 
1.169     brouard  10964:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10965:     }
1.169     brouard  10966:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  10967:       month=99;
                   10968:       year=9999;
                   10969:     }else{
1.141     brouard  10970:       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  10971:       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);
                   10972:       return 1;
1.136     brouard  10973:     }
                   10974:     andc[i]=(double) year; 
                   10975:     moisdc[i]=(double) month; 
                   10976:     strcpy(line,stra);
                   10977:     
1.223     brouard  10978:     /* Date of birth */
1.136     brouard  10979:     cutv(stra, strb,line,' '); 
1.169     brouard  10980:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10981:     }
1.169     brouard  10982:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  10983:       month=99;
                   10984:       year=9999;
                   10985:     }else{
1.141     brouard  10986:       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);
                   10987:       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  10988:       return 1;
1.136     brouard  10989:     }
                   10990:     if (year==9999) {
1.141     brouard  10991:       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);
                   10992:       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  10993:       return 1;
                   10994:       
1.136     brouard  10995:     }
                   10996:     annais[i]=(double)(year);
1.302     brouard  10997:     moisnais[i]=(double)(month);
                   10998:     for (j=1;j<=maxwav;j++){
                   10999:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   11000:        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]);
                   11001:        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]);
                   11002:       }
                   11003:     }
                   11004: 
1.136     brouard  11005:     strcpy(line,stra);
1.225     brouard  11006:     
1.223     brouard  11007:     /* Sample weight */
1.136     brouard  11008:     cutv(stra, strb,line,' '); 
                   11009:     errno=0;
                   11010:     dval=strtod(strb,&endptr); 
                   11011:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  11012:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   11013:       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  11014:       fflush(ficlog);
                   11015:       return 1;
                   11016:     }
                   11017:     weight[i]=dval; 
                   11018:     strcpy(line,stra);
1.225     brouard  11019:     
1.223     brouard  11020:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   11021:       cutv(stra, strb, line, ' '); 
                   11022:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  11023:        lval=-1;
1.311     brouard  11024:        coqvar[iv][i]=NAN; 
                   11025:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  11026:       }else{
1.225     brouard  11027:        errno=0;
                   11028:        /* what_kind_of_number(strb); */
                   11029:        dval=strtod(strb,&endptr);
                   11030:        /* if(strb != endptr && *endptr == '\0') */
                   11031:        /*   dval=dlval; */
                   11032:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   11033:        if( strb[0]=='\0' || (*endptr != '\0')){
                   11034:          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);
                   11035:          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);
                   11036:          return 1;
                   11037:        }
                   11038:        coqvar[iv][i]=dval; 
1.226     brouard  11039:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  11040:       }
                   11041:       strcpy(line,stra);
                   11042:     }/* end loop nqv */
1.136     brouard  11043:     
1.223     brouard  11044:     /* Covariate values */
1.136     brouard  11045:     for (j=ncovcol;j>=1;j--){
                   11046:       cutv(stra, strb,line,' '); 
1.223     brouard  11047:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  11048:        lval=-1;
1.136     brouard  11049:       }else{
1.225     brouard  11050:        errno=0;
                   11051:        lval=strtol(strb,&endptr,10); 
                   11052:        if( strb[0]=='\0' || (*endptr != '\0')){
                   11053:          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);
                   11054:          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);
                   11055:          return 1;
                   11056:        }
1.136     brouard  11057:       }
                   11058:       if(lval <-1 || lval >1){
1.225     brouard  11059:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  11060:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   11061:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  11062:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   11063:  build V1=0 V2=0 for the reference value (1),\n                                \
                   11064:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  11065:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  11066:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  11067:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  11068:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  11069:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   11070:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  11071:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   11072:  build V1=0 V2=0 for the reference value (1),\n                                \
                   11073:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  11074:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  11075:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  11076:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  11077:        return 1;
1.136     brouard  11078:       }
                   11079:       covar[j][i]=(double)(lval);
                   11080:       strcpy(line,stra);
                   11081:     }  
                   11082:     lstra=strlen(stra);
1.225     brouard  11083:     
1.136     brouard  11084:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   11085:       stratrunc = &(stra[lstra-9]);
                   11086:       num[i]=atol(stratrunc);
                   11087:     }
                   11088:     else
                   11089:       num[i]=atol(stra);
                   11090:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   11091:       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;}*/
                   11092:     
                   11093:     i=i+1;
                   11094:   } /* End loop reading  data */
1.225     brouard  11095:   
1.136     brouard  11096:   *imax=i-1; /* Number of individuals */
                   11097:   fclose(fic);
1.225     brouard  11098:   
1.136     brouard  11099:   return (0);
1.164     brouard  11100:   /* endread: */
1.225     brouard  11101:   printf("Exiting readdata: ");
                   11102:   fclose(fic);
                   11103:   return (1);
1.223     brouard  11104: }
1.126     brouard  11105: 
1.234     brouard  11106: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  11107:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  11108:   while (*p2 == ' ')
1.234     brouard  11109:     p2++; 
                   11110:   /* while ((*p1++ = *p2++) !=0) */
                   11111:   /*   ; */
                   11112:   /* do */
                   11113:   /*   while (*p2 == ' ') */
                   11114:   /*     p2++; */
                   11115:   /* while (*p1++ == *p2++); */
                   11116:   *stri=p2; 
1.145     brouard  11117: }
                   11118: 
1.330     brouard  11119: int decoderesult( char resultline[], int nres)
1.230     brouard  11120: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   11121: {
1.235     brouard  11122:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  11123:   char resultsav[MAXLINE];
1.330     brouard  11124:   /* int resultmodel[MAXLINE]; */
1.334     brouard  11125:   /* int modelresult[MAXLINE]; */
1.230     brouard  11126:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   11127: 
1.234     brouard  11128:   removefirstspace(&resultline);
1.332     brouard  11129:   printf("decoderesult:%s\n",resultline);
1.230     brouard  11130: 
1.332     brouard  11131:   strcpy(resultsav,resultline);
1.342     brouard  11132:   /* printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline); */
1.230     brouard  11133:   if (strlen(resultsav) >1){
1.334     brouard  11134:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  11135:   }
1.353     brouard  11136:   if(j == 0 && cptcovs== 0){ /* Resultline but no =  and no covariate in the model */
1.253     brouard  11137:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   11138:     return (0);
                   11139:   }
1.234     brouard  11140:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.353     brouard  11141:     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);
                   11142:     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);
                   11143:     if(j==0)
                   11144:       return 1;
1.234     brouard  11145:   }
1.334     brouard  11146:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  11147:     if(nbocc(resultsav,'=') >1){
1.318     brouard  11148:       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  11149:       /* 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  11150:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  11151:       /* If a blank, then strc="V4=" and strd='\0' */
                   11152:       if(strc[0]=='\0'){
                   11153:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   11154:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   11155:        return 1;
                   11156:       }
1.234     brouard  11157:     }else
                   11158:       cutl(strc,strd,resultsav,'=');
1.318     brouard  11159:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  11160:     
1.230     brouard  11161:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  11162:     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  11163:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   11164:     /* cptcovsel++;     */
                   11165:     if (nbocc(stra,'=') >0)
                   11166:       strcpy(resultsav,stra); /* and analyzes it */
                   11167:   }
1.235     brouard  11168:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  11169:   /* 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  11170:   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  11171:     if(Typevar[k1]==0){ /* Single covariate in model */
                   11172:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  11173:       match=0;
1.318     brouard  11174:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11175:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  11176:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  11177:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  11178:          break;
                   11179:        }
                   11180:       }
                   11181:       if(match == 0){
1.338     brouard  11182:        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]);
                   11183:        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  11184:        return 1;
1.234     brouard  11185:       }
1.332     brouard  11186:     }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*/
                   11187:       /* We feed resultmodel[k1]=k2; */
                   11188:       match=0;
                   11189:       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 */
                   11190:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  11191:          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  11192:          resultmodel[nres][k1]=k2; /* Added here */
1.342     brouard  11193:          /* printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]); */
1.332     brouard  11194:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11195:          break;
                   11196:        }
                   11197:       }
                   11198:       if(match == 0){
1.338     brouard  11199:        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]);
                   11200:        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  11201:       return 1;
                   11202:       }
1.349     brouard  11203:     }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  11204:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   11205:       match=0;
1.342     brouard  11206:       /* 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  11207:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11208:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   11209:          /* modelresult[k2]=k1; */
1.342     brouard  11210:          /* printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]); */
1.332     brouard  11211:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11212:        }
                   11213:       }
                   11214:       if(match == 0){
1.349     brouard  11215:        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);
                   11216:        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  11217:        return 1;
                   11218:       }
                   11219:       match=0;
                   11220:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11221:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   11222:          /* modelresult[k2]=k1;*/
1.342     brouard  11223:          /* printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]); */
1.332     brouard  11224:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11225:          break;
                   11226:        }
                   11227:       }
                   11228:       if(match == 0){
1.349     brouard  11229:        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);
                   11230:        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  11231:        return 1;
                   11232:       }
                   11233:     }/* End of testing */
1.333     brouard  11234:   }/* End loop cptcovt */
1.235     brouard  11235:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  11236:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  11237:   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)
                   11238:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  11239:     match=0;
1.318     brouard  11240:     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  11241:       if(Typevar[k1]==0){ /* Single only */
1.349     brouard  11242:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4  What if a product?  */
1.330     brouard  11243:          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  11244:          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  11245:          ++match;
                   11246:        }
                   11247:       }
                   11248:     }
                   11249:     if(match == 0){
1.338     brouard  11250:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   11251:       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  11252:       return 1;
1.234     brouard  11253:     }else if(match > 1){
1.338     brouard  11254:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   11255:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
1.310     brouard  11256:       return 1;
1.234     brouard  11257:     }
                   11258:   }
1.334     brouard  11259:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  11260:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  11261:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  11262:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   11263:   /* 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*/
                   11264:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  11265:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   11266:   /*    1 0 0 0 */
                   11267:   /*    2 1 0 0 */
                   11268:   /*    3 0 1 0 */ 
1.330     brouard  11269:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  11270:   /*    5 0 0 1 */
1.330     brouard  11271:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  11272:   /*    7 0 1 1 */
                   11273:   /*    8 1 1 1 */
1.237     brouard  11274:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   11275:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   11276:   /* V5*age V5 known which value for nres?  */
                   11277:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  11278:   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.
                   11279:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  11280:     /* k counting number of combination of single dummies in the equation model */
                   11281:     /* k4 counting single dummies in the equation model */
                   11282:     /* k4q counting single quantitatives in the equation model */
1.344     brouard  11283:     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  11284:        /* 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  11285:       /* 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  11286:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  11287:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   11288:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   11289:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   11290:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   11291:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  11292:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  11293:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  11294:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  11295:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   11296:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   11297:       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  11298:       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  11299:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  11300:       /* Tinvresult[nres][4]=1 */
1.334     brouard  11301:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   11302:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   11303:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11304:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  11305:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  11306:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.342     brouard  11307:       /* 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  11308:       k4++;;
1.331     brouard  11309:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  11310:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  11311:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  11312:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  11313:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   11314:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   11315:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  11316:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   11317:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11318:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   11319:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   11320:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   11321:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  11322:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  11323:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  11324:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  11325:       /* 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  11326:       k4q++;;
1.350     brouard  11327:     }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"*/
                   11328:       /* Tvar[k1]; */ /* Age variable */ /* 17 age*V6*V2 ?*/
1.332     brouard  11329:       /* Wrong we want the value of variable name Tvar[k1] */
1.350     brouard  11330:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   11331:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   11332:       /* 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]]); */
                   11333:       }else{
                   11334:        k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   11335:        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)*/
                   11336:        TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
                   11337:        precov[nres][k1]=Tvalsel[k3];
                   11338:       }
1.342     brouard  11339:       /* 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  11340:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.350     brouard  11341:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   11342:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   11343:       /* 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]]); */
                   11344:       }else{
                   11345:        k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
                   11346:        k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
                   11347:        TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
                   11348:        precov[nres][k1]=Tvalsel[k3q];
                   11349:       }
1.342     brouard  11350:       /* 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  11351:     }else if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
1.332     brouard  11352:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
1.342     brouard  11353:       /* 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  11354:     }else{
1.332     brouard  11355:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   11356:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  11357:     }
                   11358:   }
1.234     brouard  11359:   
1.334     brouard  11360:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  11361:   return (0);
                   11362: }
1.235     brouard  11363: 
1.230     brouard  11364: int decodemodel( char model[], int lastobs)
                   11365:  /**< This routine decodes the model and returns:
1.224     brouard  11366:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   11367:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   11368:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   11369:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   11370:        * - cptcovage number of covariates with age*products =2
                   11371:        * - cptcovs number of simple covariates
1.339     brouard  11372:        * ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
1.224     brouard  11373:        * - 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  11374:        *     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
1.319     brouard  11375:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  11376:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   11377:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   11378:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   11379:        */
1.319     brouard  11380: /* 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  11381: {
1.238     brouard  11382:   int i, j, k, ks, v;
1.349     brouard  11383:   int n,m;
                   11384:   int  j1, k1, k11, k12, k2, k3, k4;
                   11385:   char modelsav[300];
                   11386:   char stra[300], strb[300], strc[300], strd[300],stre[300],strf[300];
1.187     brouard  11387:   char *strpt;
1.349     brouard  11388:   int  **existcomb;
                   11389:   
                   11390:   existcomb=imatrix(1,NCOVMAX,1,NCOVMAX);
                   11391:   for(i=1;i<=NCOVMAX;i++)
                   11392:     for(j=1;j<=NCOVMAX;j++)
                   11393:       existcomb[i][j]=0;
                   11394:     
1.145     brouard  11395:   /*removespace(model);*/
1.136     brouard  11396:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.349     brouard  11397:     j=0, j1=0, k1=0, k12=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  11398:     if (strstr(model,"AGE") !=0){
1.192     brouard  11399:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   11400:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  11401:       return 1;
                   11402:     }
1.141     brouard  11403:     if (strstr(model,"v") !=0){
1.338     brouard  11404:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
                   11405:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
1.141     brouard  11406:       return 1;
                   11407:     }
1.187     brouard  11408:     strcpy(modelsav,model); 
                   11409:     if ((strpt=strstr(model,"age*age")) !=0){
1.338     brouard  11410:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
1.187     brouard  11411:       if(strpt != model){
1.338     brouard  11412:        printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11413:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11414:  corresponding column of parameters.\n",model);
1.338     brouard  11415:        fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11416:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11417:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  11418:        return 1;
1.225     brouard  11419:       }
1.187     brouard  11420:       nagesqr=1;
                   11421:       if (strstr(model,"+age*age") !=0)
1.234     brouard  11422:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  11423:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  11424:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  11425:       else 
1.234     brouard  11426:        substrchaine(modelsav, model, "age*age");
1.187     brouard  11427:     }else
                   11428:       nagesqr=0;
1.349     brouard  11429:     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  11430:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   11431:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.351     brouard  11432:       cptcovs=0; /**<  Number of simple covariates V1 +V1*age +V3 +V3*V4 +age*age => V1 + V3 =4+1-3=2  Wrong */
1.187     brouard  11433:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  11434:                     * cst, age and age*age 
                   11435:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   11436:       /* including age products which are counted in cptcovage.
                   11437:        * but the covariates which are products must be treated 
                   11438:        * separately: ncovn=4- 2=2 (V1+V3). */
1.349     brouard  11439:       cptcovprod=0; /**< Number of products  V1*V2 +v3*age = 2 */
                   11440:       cptcovdageprod=0; /* Number of doouble products with age age*Vn*VM or Vn*age*Vm or Vn*Vm*age */
1.187     brouard  11441:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.349     brouard  11442:       cptcovprodage=0;
                   11443:       /* cptcovprodage=nboccstr(modelsav,"age");*/
1.225     brouard  11444:       
1.187     brouard  11445:       /*   Design
                   11446:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   11447:        *  <          ncovcol=8                >
                   11448:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   11449:        *   k=  1    2      3       4     5       6      7        8
                   11450:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
1.345     brouard  11451:        *  covar[k,i], are for fixed covariates, value of kth covariate if not including age for individual i:
1.224     brouard  11452:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   11453:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  11454:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   11455:        *  Tage[++cptcovage]=k
1.345     brouard  11456:        *       if products, new covar are created after ncovcol + nqv (quanti fixed) with k1
1.187     brouard  11457:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   11458:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   11459:        *  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
                   11460:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   11461:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   11462:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
1.345     brouard  11463:        *  <          ncovcol=8  8 fixed covariate. Additional starts at 9 (V5*V6) and 10(V7*V8)              >
1.187     brouard  11464:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   11465:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
1.345     brouard  11466:        *     Tvard[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   11467:        * p Tvar[1]@12={2,   1,     3,      3,   9,     10,     8,       8}
1.187     brouard  11468:        * p Tprod[1]@2={                         6, 5}
                   11469:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   11470:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   11471:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  11472:        *How to reorganize? Tvars(orted)
1.187     brouard  11473:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   11474:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   11475:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   11476:        * Struct []
                   11477:        */
1.225     brouard  11478:       
1.187     brouard  11479:       /* This loop fills the array Tvar from the string 'model'.*/
                   11480:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   11481:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   11482:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   11483:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   11484:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   11485:       /*       k=1 Tvar[1]=2 (from V2) */
                   11486:       /*       k=5 Tvar[5] */
                   11487:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  11488:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  11489:       /*       } */
1.198     brouard  11490:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  11491:       /*
                   11492:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  11493:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   11494:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   11495:       }
1.187     brouard  11496:       cptcovage=0;
1.351     brouard  11497: 
                   11498:       /* First loop in order to calculate */
                   11499:       /* for age*VN*Vm
                   11500:        * Provides, Typevar[k], Tage[cptcovage], existcomb[n][m], FixedV[ncovcolt+k12]
                   11501:        * Tprod[k1]=k  Tposprod[k]=k1;    Tvard[k1][1] =m;
                   11502:       */
                   11503:       /* Needs  FixedV[Tvardk[k][1]] */
                   11504:       /* For others:
                   11505:        * Sets  Typevar[k];
                   11506:        * Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   11507:        *       Tposprod[k]=k11;
                   11508:        *       Tprod[k11]=k;
                   11509:        *       Tvardk[k][1] =m;
                   11510:        * Needs FixedV[Tvardk[k][1]] == 0
                   11511:       */
                   11512:       
1.319     brouard  11513:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   11514:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   11515:                                         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" */
                   11516:        if (nbocc(modelsav,'+')==0)
                   11517:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  11518:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   11519:        /*scanf("%d",i);*/
1.349     brouard  11520:        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 */
                   11521:          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  */
                   11522:          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   */
                   11523:            Typevar[k]=3;  /* 3 for age and double product age*Vn*Vm varying of fixed */
                   11524:             if(strstr(strc,"age")!=0) { /* It means that strc=V2*age or age*V2 and thus that strd=Vn */
                   11525:               cutl(stre,strf,strc,'*') ; /* strf=age or Vm, stre=Vm or age. If strc=V6*V2 then strf=V6 and stre=V2 */
                   11526:              strcpy(strc,strb); /* save strb(=age*Vn*Vm) into strc */
                   11527:              /* We want strb=Vn*Vm */
                   11528:               if(strcmp(strf,"age")==0){ /* strf is "age" so that stre=Vm =V2 . */
                   11529:                 strcpy(strb,strd);
                   11530:                 strcat(strb,"*");
                   11531:                 strcat(strb,stre);
                   11532:               }else{  /* strf=Vm  If strf=V6 then stre=V2 */
                   11533:                 strcpy(strb,strf);
                   11534:                 strcat(strb,"*");
                   11535:                 strcat(strb,stre);
                   11536:                 strcpy(strd,strb); /* in order for strd to not be "age"  for next test (will be Vn*Vm */
                   11537:               }
1.351     brouard  11538:              /* 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]]]); */
                   11539:              /* FixedV[Tvar[Tage[k]]]=0; /\* HERY not sure if V7*V4*age Fixed might not exist  yet*\/ */
1.349     brouard  11540:             }else{  /* strc=Vn*Vm (and strd=age) and should be strb=Vn*Vm but want to keep original strb double product  */
                   11541:              strcpy(stre,strb); /* save full b in stre */
                   11542:              strcpy(strb,strc); /* save short c in new short b for next block strb=Vn*Vm*/
                   11543:              strcpy(strf,strc); /* save short c in new short f */
                   11544:               cutl(strc,strd,strf,'*'); /* We get strd=Vn and strc=Vm for next block (strb=Vn*Vm)*/
                   11545:              /* strcpy(strc,stre);*/ /* save full e in c for future */
                   11546:             }
                   11547:             cptcovdageprod++; /* double product with age  Which product is it? */
                   11548:             /* 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 *\/ */
                   11549:             /* cutl(strc,strd,strb,'*'); /\* strd=  V6    or   V2     or    age and  strc=  V2 or    age or    V2 *\/ */
1.234     brouard  11550:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
1.349     brouard  11551:            n=atoi(stre);
1.234     brouard  11552:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.349     brouard  11553:            m=atoi(strc);
                   11554:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   11555:            Tage[cptcovage]=k; /* For age*V3*V2 gives the position in model of covariates associated with age Tage[1]=6 HERY too*/
                   11556:            if(existcomb[n][m] == 0){
                   11557:              /*  r /home/brouard/Documents/Recherches/REVES/Zachary/Zach-2022/Feinuo_Sun/Feinuo-threeway/femV12V15_3wayintNBe.imach */
                   11558:              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);
                   11559:              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);
                   11560:              fflush(ficlog);
                   11561:              k1++;  /* The combination Vn*Vm will be in the model so we create it at k1 */
                   11562:              k12++;
                   11563:              existcomb[n][m]=k1;
                   11564:              existcomb[m][n]=k1;
                   11565:              Tvar[k]=ncovcol+nqv+ntv+nqtv+k1;
                   11566:              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*/
                   11567:              Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 Gives the k1 double product  Vn*Vm or age*Vn*Vm at the k position */
                   11568:              Tvard[k1][1] =m; /* m 1 for V1*/
                   11569:              Tvardk[k][1] =m; /* m 1 for V1*/
                   11570:              Tvard[k1][2] =n; /* n 4 for V4*/
                   11571:              Tvardk[k][2] =n; /* n 4 for V4*/
1.351     brouard  11572: /*           Tvar[Tage[cptcovage]]=k1;*/ /* Tvar[6=age*V3*V2]=9 (new fixed covariate) */ /* We don't know about Fixed yet HERE */
1.349     brouard  11573:              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 */
                   11574:                for (i=1; i<=lastobs;i++){/* For fixed product */
                   11575:                  /* Computes the new covariate which is a product of
                   11576:                     covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   11577:                  covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   11578:                }
                   11579:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11580:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   11581:                k12++;
                   11582:                FixedV[ncovcolt+k12]=0;
                   11583:              }else{ /*End of FixedV */
                   11584:                cptcovprodvage++; /* Counting the number of varying covariate with age */
                   11585:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   11586:                k12++;
                   11587:                FixedV[ncovcolt+k12]=1;
                   11588:              }
                   11589:            }else{  /* k1 Vn*Vm already exists */
                   11590:              k11=existcomb[n][m];
                   11591:              Tposprod[k]=k11; /* OK */
                   11592:              Tvar[k]=Tvar[Tprod[k11]]; /* HERY */
                   11593:              Tvardk[k][1]=m;
                   11594:              Tvardk[k][2]=n;
                   11595:              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 */
                   11596:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   11597:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11598:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   11599:                Tvar[Tage[cptcovage]]=k1;
                   11600:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   11601:                k12++;
                   11602:                FixedV[ncovcolt+k12]=0;
                   11603:              }else{ /* Already exists but time varying (and age) */
                   11604:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   11605:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   11606:                /* Tvar[Tage[cptcovage]]=k1; */
                   11607:                cptcovprodvage++;
                   11608:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   11609:                k12++;
                   11610:                FixedV[ncovcolt+k12]=1;
                   11611:              }
                   11612:            }
                   11613:            /* Tage[cptcovage]=k;  /\*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   11614:            /* Tvar[k]=k11; /\* HERY *\/ */
                   11615:          } 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 */
                   11616:             cptcovprod++;
                   11617:             if (strcmp(strc,"age")==0) { /**< Model includes age: strb= Vn*age c=age d=Vn*/
                   11618:               /* covar is not filled and then is empty */
                   11619:               cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   11620:               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 */
                   11621:               Typevar[k]=1;  /* 1 for age product */
                   11622:               cptcovage++; /* Counts the number of covariates which include age as a product */
                   11623:               Tage[cptcovage]=k;  /*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   11624:              if( FixedV[Tvar[k]] == 0){
                   11625:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11626:              }else{
                   11627:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
                   11628:              }
                   11629:               /*printf("stre=%s ", stre);*/
                   11630:             } else if (strcmp(strd,"age")==0) { /* strb= age*Vn c=Vn */
                   11631:               cutl(stre,strb,strc,'V');
                   11632:               Tvar[k]=atoi(stre);
                   11633:               Typevar[k]=1;  /* 1 for age product */
                   11634:               cptcovage++;
                   11635:               Tage[cptcovage]=k;
                   11636:              if( FixedV[Tvar[k]] == 0){
                   11637:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11638:              }else{
                   11639:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
1.339     brouard  11640:              }
1.349     brouard  11641:             }else{ /*  for product Vn*Vm */
                   11642:              Typevar[k]=2;  /* 2 for product Vn*Vm */
                   11643:              cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   11644:              n=atoi(stre);
                   11645:              cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   11646:              m=atoi(strc);
                   11647:              k1++;
                   11648:              cptcovprodnoage++;
                   11649:              if(existcomb[n][m] != 0 || existcomb[m][n] != 0){
                   11650:                printf("Warning in model combination V%d*V%d already exists in the model in position k1=%d!\n",n,m,existcomb[n][m]);
                   11651:                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]);
                   11652:                fflush(ficlog);
                   11653:                k11=existcomb[n][m];
                   11654:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   11655:                Tposprod[k]=k11;
                   11656:                Tprod[k11]=k;
                   11657:                Tvardk[k][1] =m; /* m 1 for V1*/
                   11658:                /* Tvard[k11][1] =m; /\* n 4 for V4*\/ */
                   11659:                Tvardk[k][2] =n; /* n 4 for V4*/                
                   11660:                /* Tvard[k11][2] =n; /\* n 4 for V4*\/ */
                   11661:              }else{ /* combination Vn*Vm doesn't exist we create it (no age)*/
                   11662:                existcomb[n][m]=k1;
                   11663:                existcomb[m][n]=k1;
                   11664:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
                   11665:                                                    because this model-covariate is a construction we invent a new column
                   11666:                                                    which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   11667:                                                    If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
                   11668:                                                    thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
                   11669:                                                    Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
                   11670:                /* Please remark that the new variables are model dependent */
                   11671:                /* If we have 4 variable but the model uses only 3, like in
                   11672:                 * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   11673:                 *  k=     1     2      3   4     5        6        7       8
                   11674:                 * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   11675:                 * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   11676:                 * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   11677:                 */
                   11678:                /* We need to feed some variables like TvarVV, but later on next loop because of ncovv (k2) is not correct */
                   11679:                Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 +V6*V2*age  */
                   11680:                Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
                   11681:                Tvard[k1][1] =m; /* m 1 for V1*/
                   11682:                Tvardk[k][1] =m; /* m 1 for V1*/
                   11683:                Tvard[k1][2] =n; /* n 4 for V4*/
                   11684:                Tvardk[k][2] =n; /* n 4 for V4*/
                   11685:                k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   11686:                /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   11687:                /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
                   11688:                /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
                   11689:                /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   11690:                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 */
                   11691:                  for (i=1; i<=lastobs;i++){/* For fixed product */
                   11692:                    /* Computes the new covariate which is a product of
                   11693:                       covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   11694:                    covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   11695:                  }
                   11696:                  /* TvarVV[k2]=n; */
                   11697:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11698:                  /* TvarVV[k2+1]=m; */
                   11699:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11700:                }else{ /* not FixedV */
                   11701:                  /* TvarVV[k2]=n; */
                   11702:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11703:                  /* TvarVV[k2+1]=m; */
                   11704:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11705:                }                 
                   11706:              }  /* End of creation of Vn*Vm if not created by age*Vn*Vm earlier  */
                   11707:            } /*  End of product Vn*Vm */
                   11708:           } /* End of age*double product or simple product */
                   11709:        }else { /* not a product */
1.234     brouard  11710:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   11711:          /*  scanf("%d",i);*/
                   11712:          cutl(strd,strc,strb,'V');
                   11713:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   11714:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   11715:          Tvar[k]=atoi(strd);
                   11716:          Typevar[k]=0;  /* 0 for simple covariates */
                   11717:        }
                   11718:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  11719:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  11720:                                  scanf("%d",i);*/
1.187     brouard  11721:       } /* end of loop + on total covariates */
1.351     brouard  11722: 
                   11723:       
1.187     brouard  11724:     } /* end if strlen(modelsave == 0) age*age might exist */
                   11725:   } /* end if strlen(model == 0) */
1.349     brouard  11726:   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  */
                   11727: 
1.136     brouard  11728:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   11729:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  11730:   
1.136     brouard  11731:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  11732:      printf("cptcovprod=%d ", cptcovprod);
                   11733:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   11734:      scanf("%d ",i);*/
                   11735: 
                   11736: 
1.230     brouard  11737: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   11738:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  11739: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   11740:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   11741:    k =           1    2   3     4       5       6      7      8        9
                   11742:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  11743:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  11744:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   11745:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   11746:          Tmodelind[combination of covar]=k;
1.225     brouard  11747: */  
                   11748: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  11749:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  11750:   /* 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  11751:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  11752:   printf("Model=1+age+%s\n\
1.349     brouard  11753: 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  11754: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11755: 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  11756:   fprintf(ficlog,"Model=1+age+%s\n\
1.349     brouard  11757: 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  11758: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11759: 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  11760:   for(k=-1;k<=NCOVMAX; k++){ Fixed[k]=0; Dummy[k]=0;}
                   11761:   for(k=1;k<=NCOVMAX; k++){TvarFind[k]=0; TvarVind[k]=0;}
1.351     brouard  11762: 
                   11763: 
                   11764:   /* Second loop for calculating  Fixed[k], Dummy[k]*/
                   11765: 
                   11766:   
1.349     brouard  11767:   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  11768:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  11769:       Fixed[k]= 0;
                   11770:       Dummy[k]= 0;
1.225     brouard  11771:       ncoveff++;
1.232     brouard  11772:       ncovf++;
1.234     brouard  11773:       nsd++;
                   11774:       modell[k].maintype= FTYPE;
                   11775:       TvarsD[nsd]=Tvar[k];
                   11776:       TvarsDind[nsd]=k;
1.330     brouard  11777:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  11778:       TvarF[ncovf]=Tvar[k];
                   11779:       TvarFind[ncovf]=k;
                   11780:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11781:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.339     brouard  11782:     /* }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  11783:     }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  11784:       Fixed[k]= 0;
                   11785:       Dummy[k]= 1;
1.230     brouard  11786:       nqfveff++;
1.234     brouard  11787:       modell[k].maintype= FTYPE;
                   11788:       modell[k].subtype= FQ;
                   11789:       nsq++;
1.334     brouard  11790:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   11791:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  11792:       ncovf++;
1.234     brouard  11793:       TvarF[ncovf]=Tvar[k];
                   11794:       TvarFind[ncovf]=k;
1.231     brouard  11795:       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  11796:       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  11797:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.339     brouard  11798:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11799:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11800:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11801:       ncovvt++;
                   11802:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11803:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
                   11804: 
1.227     brouard  11805:       Fixed[k]= 1;
                   11806:       Dummy[k]= 0;
1.225     brouard  11807:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  11808:       modell[k].maintype= VTYPE;
                   11809:       modell[k].subtype= VD;
                   11810:       nsd++;
                   11811:       TvarsD[nsd]=Tvar[k];
                   11812:       TvarsDind[nsd]=k;
1.330     brouard  11813:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  11814:       ncovv++; /* Only simple time varying variables */
                   11815:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11816:       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  11817:       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 */
                   11818:       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  11819:       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);
                   11820:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  11821:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.339     brouard  11822:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11823:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11824:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11825:       ncovvt++;
                   11826:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11827:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11828:       
1.234     brouard  11829:       Fixed[k]= 1;
                   11830:       Dummy[k]= 1;
                   11831:       nqtveff++;
                   11832:       modell[k].maintype= VTYPE;
                   11833:       modell[k].subtype= VQ;
                   11834:       ncovv++; /* Only simple time varying variables */
                   11835:       nsq++;
1.334     brouard  11836:       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) */
                   11837:       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  11838:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11839:       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  11840:       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 */
                   11841:       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  11842:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   11843:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
1.349     brouard  11844:       /* 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  11845:       /* printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv); */
1.227     brouard  11846:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  11847:       ncova++;
                   11848:       TvarA[ncova]=Tvar[k];
                   11849:       TvarAind[ncova]=k;
1.349     brouard  11850:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   11851:       /** 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  11852:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  11853:        Fixed[k]= 2;
                   11854:        Dummy[k]= 2;
                   11855:        modell[k].maintype= ATYPE;
                   11856:        modell[k].subtype= APFD;
1.349     brouard  11857:        ncovta++;
                   11858:        TvarAVVA[ncovta]=Tvar[k]; /*  (2)age*V3 */
                   11859:        TvarAVVAind[ncovta]=k;
1.240     brouard  11860:        /* ncoveff++; */
1.227     brouard  11861:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  11862:        Fixed[k]= 2;
                   11863:        Dummy[k]= 3;
                   11864:        modell[k].maintype= ATYPE;
                   11865:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
1.349     brouard  11866:        ncovta++;
                   11867:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   11868:        TvarAVVAind[ncovta]=k;
1.240     brouard  11869:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  11870:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  11871:        Fixed[k]= 3;
                   11872:        Dummy[k]= 2;
                   11873:        modell[k].maintype= ATYPE;
                   11874:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
1.349     brouard  11875:        ncovva++;
                   11876:        TvarVVA[ncovva]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   11877:        TvarVVAind[ncovva]=k;
                   11878:        ncovta++;
                   11879:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   11880:        TvarAVVAind[ncovta]=k;
1.240     brouard  11881:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  11882:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  11883:        Fixed[k]= 3;
                   11884:        Dummy[k]= 3;
                   11885:        modell[k].maintype= ATYPE;
                   11886:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
1.349     brouard  11887:        ncovva++;
                   11888:        TvarVVA[ncovva]=Tvar[k]; /*   */
                   11889:        TvarVVAind[ncovva]=k;
                   11890:        ncovta++;
                   11891:        TvarAVVA[ncovta]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   11892:        TvarAVVAind[ncovta]=k;
1.240     brouard  11893:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  11894:       }
1.349     brouard  11895:     }else if( Tposprod[k]>0  &&  Typevar[k]==2){  /* Detects if fixed product no age Vm*Vn */
                   11896:       printf("MEMORY ERRORR k=%d  Tposprod[k]=%d, Typevar[k]=%d\n ",k, Tposprod[k], Typevar[k]);
                   11897:       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 */
                   11898:       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]]);
                   11899:        Fixed[k]= 0;
                   11900:        Dummy[k]= 0;
                   11901:        ncoveff++;
                   11902:        ncovf++;
                   11903:        /* ncovv++; */
                   11904:        /* TvarVV[ncovv]=Tvardk[k][1]; */
                   11905:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11906:        /* ncovv++; */
                   11907:        /* TvarVV[ncovv]=Tvardk[k][2]; */
                   11908:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11909:        modell[k].maintype= FTYPE;
                   11910:        TvarF[ncovf]=Tvar[k];
                   11911:        /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
                   11912:        TvarFind[ncovf]=k;
                   11913:        TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11914:        TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11915:       }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  */
                   11916:        /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11917:        /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   11918:        /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11919:        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 */
                   11920:        ncovvt++;
                   11921:        TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   11922:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11923:        ncovvt++;
                   11924:        TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   11925:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11926:        
                   11927:        /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   11928:        /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   11929:        
                   11930:        if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   11931:          if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
                   11932:            Fixed[k]= 1;
                   11933:            Dummy[k]= 0;
                   11934:            modell[k].maintype= FTYPE;
                   11935:            modell[k].subtype= FPDD;            /*      Product fixed dummy * fixed dummy */
                   11936:            ncovf++; /* Fixed variables without age */
                   11937:            TvarF[ncovf]=Tvar[k];
                   11938:            TvarFind[ncovf]=k;
                   11939:          }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
                   11940:            Fixed[k]= 0;  /* Fixed product */
                   11941:            Dummy[k]= 1;
                   11942:            modell[k].maintype= FTYPE;
                   11943:            modell[k].subtype= FPDQ;            /*      Product fixed dummy * fixed quantitative */
                   11944:            ncovf++; /* Varying variables without age */
                   11945:            TvarF[ncovf]=Tvar[k];
                   11946:            TvarFind[ncovf]=k;
                   11947:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
                   11948:            Fixed[k]= 1;
                   11949:            Dummy[k]= 0;
                   11950:            modell[k].maintype= VTYPE;
                   11951:            modell[k].subtype= VPDD;            /*      Product fixed dummy * varying dummy */
                   11952:            ncovv++; /* Varying variables without age */
                   11953:            TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   11954:            TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
                   11955:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
                   11956:            Fixed[k]= 1;
                   11957:            Dummy[k]= 1;
                   11958:            modell[k].maintype= VTYPE;
                   11959:            modell[k].subtype= VPDQ;            /*      Product fixed dummy * varying quantitative */
                   11960:            ncovv++; /* Varying variables without age */
                   11961:            TvarV[ncovv]=Tvar[k];
                   11962:            TvarVind[ncovv]=k;
                   11963:          }
                   11964:        }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   11965:          if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
                   11966:            Fixed[k]= 0;  /*  Fixed product */
                   11967:            Dummy[k]= 1;
                   11968:            modell[k].maintype= FTYPE;
                   11969:            modell[k].subtype= FPDQ;            /*      Product fixed quantitative * fixed dummy */
                   11970:            ncovf++; /* Fixed variables without age */
                   11971:            TvarF[ncovf]=Tvar[k];
                   11972:            TvarFind[ncovf]=k;
                   11973:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
                   11974:            Fixed[k]= 1;
                   11975:            Dummy[k]= 1;
                   11976:            modell[k].maintype= VTYPE;
                   11977:            modell[k].subtype= VPDQ;            /*      Product fixed quantitative * varying dummy */
                   11978:            ncovv++; /* Varying variables without age */
                   11979:            TvarV[ncovv]=Tvar[k];
                   11980:            TvarVind[ncovv]=k;
                   11981:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
                   11982:            Fixed[k]= 1;
                   11983:            Dummy[k]= 1;
                   11984:            modell[k].maintype= VTYPE;
                   11985:            modell[k].subtype= VPQQ;            /*      Product fixed quantitative * varying quantitative */
                   11986:            ncovv++; /* Varying variables without age */
                   11987:            TvarV[ncovv]=Tvar[k];
                   11988:            TvarVind[ncovv]=k;
                   11989:            ncovv++; /* Varying variables without age */
                   11990:            TvarV[ncovv]=Tvar[k];
                   11991:            TvarVind[ncovv]=k;
                   11992:          }
                   11993:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
                   11994:          if(Tvard[k1][2] <=ncovcol){
                   11995:            Fixed[k]= 1;
                   11996:            Dummy[k]= 1;
                   11997:            modell[k].maintype= VTYPE;
                   11998:            modell[k].subtype= VPDD;            /*      Product time varying dummy * fixed dummy */
                   11999:            ncovv++; /* Varying variables without age */
                   12000:            TvarV[ncovv]=Tvar[k];
                   12001:            TvarVind[ncovv]=k;
                   12002:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   12003:            Fixed[k]= 1;
                   12004:            Dummy[k]= 1;
                   12005:            modell[k].maintype= VTYPE;
                   12006:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * fixed quantitative */
                   12007:            ncovv++; /* Varying variables without age */
                   12008:            TvarV[ncovv]=Tvar[k];
                   12009:            TvarVind[ncovv]=k;
                   12010:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   12011:            Fixed[k]= 1;
                   12012:            Dummy[k]= 0;
                   12013:            modell[k].maintype= VTYPE;
                   12014:            modell[k].subtype= VPDD;            /*      Product time varying dummy * time varying dummy */
                   12015:            ncovv++; /* Varying variables without age */
                   12016:            TvarV[ncovv]=Tvar[k];
                   12017:            TvarVind[ncovv]=k;
                   12018:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   12019:            Fixed[k]= 1;
                   12020:            Dummy[k]= 1;
                   12021:            modell[k].maintype= VTYPE;
                   12022:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * time varying quantitative */
                   12023:            ncovv++; /* Varying variables without age */
                   12024:            TvarV[ncovv]=Tvar[k];
                   12025:            TvarVind[ncovv]=k;
                   12026:          }
                   12027:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
                   12028:          if(Tvard[k1][2] <=ncovcol){
                   12029:            Fixed[k]= 1;
                   12030:            Dummy[k]= 1;
                   12031:            modell[k].maintype= VTYPE;
                   12032:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * fixed dummy */
                   12033:            ncovv++; /* Varying variables without age */
                   12034:            TvarV[ncovv]=Tvar[k];
                   12035:            TvarVind[ncovv]=k;
                   12036:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   12037:            Fixed[k]= 1;
                   12038:            Dummy[k]= 1;
                   12039:            modell[k].maintype= VTYPE;
                   12040:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * fixed quantitative */
                   12041:            ncovv++; /* Varying variables without age */
                   12042:            TvarV[ncovv]=Tvar[k];
                   12043:            TvarVind[ncovv]=k;
                   12044:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   12045:            Fixed[k]= 1;
                   12046:            Dummy[k]= 1;
                   12047:            modell[k].maintype= VTYPE;
                   12048:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * time varying dummy */
                   12049:            ncovv++; /* Varying variables without age */
                   12050:            TvarV[ncovv]=Tvar[k];
                   12051:            TvarVind[ncovv]=k;
                   12052:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   12053:            Fixed[k]= 1;
                   12054:            Dummy[k]= 1;
                   12055:            modell[k].maintype= VTYPE;
                   12056:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * time varying quantitative */
                   12057:            ncovv++; /* Varying variables without age */
                   12058:            TvarV[ncovv]=Tvar[k];
                   12059:            TvarVind[ncovv]=k;
                   12060:          }
                   12061:        }else{
                   12062:          printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12063:          fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12064:        } /*end k1*/
                   12065:       }
                   12066:     }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  12067:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  12068:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   12069:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   12070:       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 */
                   12071:       ncova++;
                   12072:       TvarA[ncova]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   12073:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   12074:       ncova++;
                   12075:       TvarA[ncova]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   12076:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
1.339     brouard  12077: 
1.349     brouard  12078:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   12079:       /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   12080:       if( FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){
                   12081:        ncovta++;
                   12082:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12083:        TvarAVVAind[ncovta]=k;
                   12084:        ncovta++;
                   12085:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12086:        TvarAVVAind[ncovta]=k;
                   12087:       }else{
                   12088:        ncovva++;  /* HERY  reached */
                   12089:        TvarVVA[ncovva]=Tvard[k1][1]; /*  age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4  */
                   12090:        TvarVVAind[ncovva]=k;
                   12091:        ncovva++;
                   12092:        TvarVVA[ncovva]=Tvard[k1][2]; /*   */
                   12093:        TvarVVAind[ncovva]=k;
                   12094:        ncovta++;
                   12095:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12096:        TvarAVVAind[ncovta]=k;
                   12097:        ncovta++;
                   12098:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12099:        TvarAVVAind[ncovta]=k;
                   12100:       }
1.339     brouard  12101:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   12102:        if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
1.349     brouard  12103:          Fixed[k]= 2;
                   12104:          Dummy[k]= 2;
1.240     brouard  12105:          modell[k].maintype= FTYPE;
                   12106:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
1.349     brouard  12107:          /* TvarF[ncova]=Tvar[k];   /\* Problem to solve *\/ */
                   12108:          /* TvarFind[ncova]=k; */
1.339     brouard  12109:        }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
1.349     brouard  12110:          Fixed[k]= 2;  /* Fixed product */
                   12111:          Dummy[k]= 3;
1.240     brouard  12112:          modell[k].maintype= FTYPE;
                   12113:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
1.349     brouard  12114:          /* TvarF[ncova]=Tvar[k]; */
                   12115:          /* TvarFind[ncova]=k; */
1.339     brouard  12116:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
1.349     brouard  12117:          Fixed[k]= 3;
                   12118:          Dummy[k]= 2;
1.240     brouard  12119:          modell[k].maintype= VTYPE;
                   12120:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
1.349     brouard  12121:          TvarV[ncova]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   12122:          TvarVind[ncova]=k;/* TvarVind[1]=5 */ 
1.339     brouard  12123:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
1.349     brouard  12124:          Fixed[k]= 3;
                   12125:          Dummy[k]= 3;
1.240     brouard  12126:          modell[k].maintype= VTYPE;
                   12127:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
1.349     brouard  12128:          /* ncovv++; /\* Varying variables without age *\/ */
                   12129:          /* TvarV[ncovv]=Tvar[k]; */
                   12130:          /* TvarVind[ncovv]=k; */
1.240     brouard  12131:        }
1.339     brouard  12132:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   12133:        if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
1.349     brouard  12134:          Fixed[k]= 2;  /*  Fixed product */
                   12135:          Dummy[k]= 2;
1.240     brouard  12136:          modell[k].maintype= FTYPE;
                   12137:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
1.349     brouard  12138:          /* ncova++; /\* Fixed variables with age *\/ */
                   12139:          /* TvarF[ncovf]=Tvar[k]; */
                   12140:          /* TvarFind[ncovf]=k; */
1.339     brouard  12141:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
1.349     brouard  12142:          Fixed[k]= 2;
                   12143:          Dummy[k]= 3;
1.240     brouard  12144:          modell[k].maintype= VTYPE;
                   12145:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
1.349     brouard  12146:          /* ncova++; /\* Varying variables with age *\/ */
                   12147:          /* TvarV[ncova]=Tvar[k]; */
                   12148:          /* TvarVind[ncova]=k; */
1.339     brouard  12149:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
1.349     brouard  12150:          Fixed[k]= 3;
                   12151:          Dummy[k]= 2;
1.240     brouard  12152:          modell[k].maintype= VTYPE;
                   12153:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
1.349     brouard  12154:          ncova++; /* Varying variables without age */
                   12155:          TvarV[ncova]=Tvar[k];
                   12156:          TvarVind[ncova]=k;
                   12157:          /* ncova++; /\* Varying variables without age *\/ */
                   12158:          /* TvarV[ncova]=Tvar[k]; */
                   12159:          /* TvarVind[ncova]=k; */
1.240     brouard  12160:        }
1.339     brouard  12161:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
1.240     brouard  12162:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  12163:          Fixed[k]= 2;
                   12164:          Dummy[k]= 2;
1.240     brouard  12165:          modell[k].maintype= VTYPE;
                   12166:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
1.349     brouard  12167:          /* ncova++; /\* Varying variables with age *\/ */
                   12168:          /* TvarV[ncova]=Tvar[k]; */
                   12169:          /* TvarVind[ncova]=k; */
1.240     brouard  12170:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  12171:          Fixed[k]= 2;
                   12172:          Dummy[k]= 3;
1.240     brouard  12173:          modell[k].maintype= VTYPE;
                   12174:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
1.349     brouard  12175:          /* ncova++; /\* Varying variables with age *\/ */
                   12176:          /* TvarV[ncova]=Tvar[k]; */
                   12177:          /* TvarVind[ncova]=k; */
1.240     brouard  12178:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349     brouard  12179:          Fixed[k]= 3;
                   12180:          Dummy[k]= 2;
1.240     brouard  12181:          modell[k].maintype= VTYPE;
                   12182:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
1.349     brouard  12183:          /* ncova++; /\* Varying variables with age *\/ */
                   12184:          /* TvarV[ncova]=Tvar[k]; */
                   12185:          /* TvarVind[ncova]=k; */
1.240     brouard  12186:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  12187:          Fixed[k]= 3;
                   12188:          Dummy[k]= 3;
1.240     brouard  12189:          modell[k].maintype= VTYPE;
                   12190:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
1.349     brouard  12191:          /* ncova++; /\* Varying variables with age *\/ */
                   12192:          /* TvarV[ncova]=Tvar[k]; */
                   12193:          /* TvarVind[ncova]=k; */
1.240     brouard  12194:        }
1.339     brouard  12195:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
1.240     brouard  12196:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  12197:          Fixed[k]= 2;
                   12198:          Dummy[k]= 2;
1.240     brouard  12199:          modell[k].maintype= VTYPE;
                   12200:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
1.349     brouard  12201:          /* ncova++; /\* Varying variables with age *\/ */
                   12202:          /* TvarV[ncova]=Tvar[k]; */
                   12203:          /* TvarVind[ncova]=k; */
1.240     brouard  12204:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  12205:          Fixed[k]= 2;
                   12206:          Dummy[k]= 3;
1.240     brouard  12207:          modell[k].maintype= VTYPE;
                   12208:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
1.349     brouard  12209:          /* ncova++; /\* Varying variables with age *\/ */
                   12210:          /* TvarV[ncova]=Tvar[k]; */
                   12211:          /* TvarVind[ncova]=k; */
1.240     brouard  12212:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349     brouard  12213:          Fixed[k]= 3;
                   12214:          Dummy[k]= 2;
1.240     brouard  12215:          modell[k].maintype= VTYPE;
                   12216:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
1.349     brouard  12217:          /* ncova++; /\* Varying variables with age *\/ */
                   12218:          /* TvarV[ncova]=Tvar[k]; */
                   12219:          /* TvarVind[ncova]=k; */
1.240     brouard  12220:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  12221:          Fixed[k]= 3;
                   12222:          Dummy[k]= 3;
1.240     brouard  12223:          modell[k].maintype= VTYPE;
                   12224:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
1.349     brouard  12225:          /* ncova++; /\* Varying variables with age *\/ */
                   12226:          /* TvarV[ncova]=Tvar[k]; */
                   12227:          /* TvarVind[ncova]=k; */
1.240     brouard  12228:        }
1.227     brouard  12229:       }else{
1.240     brouard  12230:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12231:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12232:       } /*end k1*/
1.349     brouard  12233:     } else{
1.226     brouard  12234:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   12235:       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  12236:     }
1.342     brouard  12237:     /* 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]); */
                   12238:     /* printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype); */
1.227     brouard  12239:     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]);
                   12240:   }
1.349     brouard  12241:   ncovvta=ncovva;
1.227     brouard  12242:   /* Searching for doublons in the model */
                   12243:   for(k1=1; k1<= cptcovt;k1++){
                   12244:     for(k2=1; k2 <k1;k2++){
1.285     brouard  12245:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   12246:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  12247:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   12248:          if(Tvar[k1]==Tvar[k2]){
1.338     brouard  12249:            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]);
                   12250:            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  12251:            return(1);
                   12252:          }
                   12253:        }else if (Typevar[k1] ==2){
                   12254:          k3=Tposprod[k1];
                   12255:          k4=Tposprod[k2];
                   12256:          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  12257:            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]]);
                   12258:            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  12259:            return(1);
                   12260:          }
                   12261:        }
1.227     brouard  12262:       }
                   12263:     }
1.225     brouard  12264:   }
                   12265:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   12266:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  12267:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   12268:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.349     brouard  12269: 
                   12270:   free_imatrix(existcomb,1,NCOVMAX,1,NCOVMAX);
1.137     brouard  12271:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  12272:   /*endread:*/
1.225     brouard  12273:   printf("Exiting decodemodel: ");
                   12274:   return (1);
1.136     brouard  12275: }
                   12276: 
1.169     brouard  12277: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  12278: {/* Check ages at death */
1.136     brouard  12279:   int i, m;
1.218     brouard  12280:   int firstone=0;
                   12281:   
1.136     brouard  12282:   for (i=1; i<=imx; i++) {
                   12283:     for(m=2; (m<= maxwav); m++) {
                   12284:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   12285:        anint[m][i]=9999;
1.216     brouard  12286:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   12287:          s[m][i]=-1;
1.136     brouard  12288:       }
                   12289:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  12290:        *nberr = *nberr + 1;
1.218     brouard  12291:        if(firstone == 0){
                   12292:          firstone=1;
1.260     brouard  12293:        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  12294:        }
1.262     brouard  12295:        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  12296:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  12297:       }
                   12298:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  12299:        (*nberr)++;
1.259     brouard  12300:        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  12301:        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  12302:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  12303:       }
                   12304:     }
                   12305:   }
                   12306: 
                   12307:   for (i=1; i<=imx; i++)  {
                   12308:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   12309:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  12310:       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  12311:        if (s[m][i] >= nlstate+1) {
1.169     brouard  12312:          if(agedc[i]>0){
                   12313:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  12314:              agev[m][i]=agedc[i];
1.214     brouard  12315:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  12316:            }else {
1.136     brouard  12317:              if ((int)andc[i]!=9999){
                   12318:                nbwarn++;
                   12319:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   12320:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   12321:                agev[m][i]=-1;
                   12322:              }
                   12323:            }
1.169     brouard  12324:          } /* agedc > 0 */
1.214     brouard  12325:        } /* end if */
1.136     brouard  12326:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   12327:                                 years but with the precision of a month */
                   12328:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   12329:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   12330:            agev[m][i]=1;
                   12331:          else if(agev[m][i] < *agemin){ 
                   12332:            *agemin=agev[m][i];
                   12333:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   12334:          }
                   12335:          else if(agev[m][i] >*agemax){
                   12336:            *agemax=agev[m][i];
1.156     brouard  12337:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  12338:          }
                   12339:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   12340:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  12341:        } /* en if 9*/
1.136     brouard  12342:        else { /* =9 */
1.214     brouard  12343:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  12344:          agev[m][i]=1;
                   12345:          s[m][i]=-1;
                   12346:        }
                   12347:       }
1.214     brouard  12348:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  12349:        agev[m][i]=1;
1.214     brouard  12350:       else{
                   12351:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   12352:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   12353:        agev[m][i]=0;
                   12354:       }
                   12355:     } /* End for lastpass */
                   12356:   }
1.136     brouard  12357:     
                   12358:   for (i=1; i<=imx; i++)  {
                   12359:     for(m=firstpass; (m<=lastpass); m++){
                   12360:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  12361:        (*nberr)++;
1.136     brouard  12362:        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);     
                   12363:        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);     
                   12364:        return 1;
                   12365:       }
                   12366:     }
                   12367:   }
                   12368: 
                   12369:   /*for (i=1; i<=imx; i++){
                   12370:   for (m=firstpass; (m<lastpass); m++){
                   12371:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   12372: }
                   12373: 
                   12374: }*/
                   12375: 
                   12376: 
1.139     brouard  12377:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   12378:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  12379: 
                   12380:   return (0);
1.164     brouard  12381:  /* endread:*/
1.136     brouard  12382:     printf("Exiting calandcheckages: ");
                   12383:     return (1);
                   12384: }
                   12385: 
1.172     brouard  12386: #if defined(_MSC_VER)
                   12387: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   12388: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   12389: //#include "stdafx.h"
                   12390: //#include <stdio.h>
                   12391: //#include <tchar.h>
                   12392: //#include <windows.h>
                   12393: //#include <iostream>
                   12394: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   12395: 
                   12396: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   12397: 
                   12398: BOOL IsWow64()
                   12399: {
                   12400:        BOOL bIsWow64 = FALSE;
                   12401: 
                   12402:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   12403:        //  (HANDLE, PBOOL);
                   12404: 
                   12405:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   12406: 
                   12407:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   12408:        const char funcName[] = "IsWow64Process";
                   12409:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   12410:                GetProcAddress(module, funcName);
                   12411: 
                   12412:        if (NULL != fnIsWow64Process)
                   12413:        {
                   12414:                if (!fnIsWow64Process(GetCurrentProcess(),
                   12415:                        &bIsWow64))
                   12416:                        //throw std::exception("Unknown error");
                   12417:                        printf("Unknown error\n");
                   12418:        }
                   12419:        return bIsWow64 != FALSE;
                   12420: }
                   12421: #endif
1.177     brouard  12422: 
1.191     brouard  12423: void syscompilerinfo(int logged)
1.292     brouard  12424: {
                   12425: #include <stdint.h>
                   12426: 
                   12427:   /* #include "syscompilerinfo.h"*/
1.185     brouard  12428:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   12429:    /* /GS /W3 /Gy
                   12430:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   12431:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   12432:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  12433:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   12434:    */ 
                   12435:    /* 64 bits */
1.185     brouard  12436:    /*
                   12437:      /GS /W3 /Gy
                   12438:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   12439:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   12440:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   12441:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   12442:    /* Optimization are useless and O3 is slower than O2 */
                   12443:    /*
                   12444:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   12445:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   12446:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   12447:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   12448:    */
1.186     brouard  12449:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  12450:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   12451:       /PDB:"visual studio
                   12452:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   12453:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   12454:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   12455:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   12456:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   12457:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   12458:       uiAccess='false'"
                   12459:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   12460:       /NOLOGO /TLBID:1
                   12461:    */
1.292     brouard  12462: 
                   12463: 
1.177     brouard  12464: #if defined __INTEL_COMPILER
1.178     brouard  12465: #if defined(__GNUC__)
                   12466:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   12467: #endif
1.177     brouard  12468: #elif defined(__GNUC__) 
1.179     brouard  12469: #ifndef  __APPLE__
1.174     brouard  12470: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  12471: #endif
1.177     brouard  12472:    struct utsname sysInfo;
1.178     brouard  12473:    int cross = CROSS;
                   12474:    if (cross){
                   12475:           printf("Cross-");
1.191     brouard  12476:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  12477:    }
1.174     brouard  12478: #endif
                   12479: 
1.191     brouard  12480:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  12481: #if defined(__clang__)
1.191     brouard  12482:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  12483: #endif
                   12484: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  12485:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  12486: #endif
                   12487: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  12488:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  12489: #endif
                   12490: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  12491:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  12492: #endif
                   12493: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  12494:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  12495: #endif
                   12496: #if defined(_MSC_VER)
1.191     brouard  12497:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  12498: #endif
                   12499: #if defined(__PGI)
1.191     brouard  12500:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  12501: #endif
                   12502: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  12503:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  12504: #endif
1.191     brouard  12505:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  12506:    
1.167     brouard  12507: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   12508: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   12509:     // Windows (x64 and x86)
1.191     brouard  12510:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  12511: #elif __unix__ // all unices, not all compilers
                   12512:     // Unix
1.191     brouard  12513:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  12514: #elif __linux__
                   12515:     // linux
1.191     brouard  12516:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  12517: #elif __APPLE__
1.174     brouard  12518:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  12519:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  12520: #endif
                   12521: 
                   12522: /*  __MINGW32__          */
                   12523: /*  __CYGWIN__  */
                   12524: /* __MINGW64__  */
                   12525: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   12526: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   12527: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   12528: /* _WIN64  // Defined for applications for Win64. */
                   12529: /* _M_X64 // Defined for compilations that target x64 processors. */
                   12530: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  12531: 
1.167     brouard  12532: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  12533:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  12534: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  12535:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  12536: #else
1.191     brouard  12537:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  12538: #endif
                   12539: 
1.169     brouard  12540: #if defined(__GNUC__)
                   12541: # if defined(__GNUC_PATCHLEVEL__)
                   12542: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   12543:                             + __GNUC_MINOR__ * 100 \
                   12544:                             + __GNUC_PATCHLEVEL__)
                   12545: # else
                   12546: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   12547:                             + __GNUC_MINOR__ * 100)
                   12548: # endif
1.174     brouard  12549:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  12550:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  12551: 
                   12552:    if (uname(&sysInfo) != -1) {
                   12553:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  12554:         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  12555:    }
                   12556:    else
                   12557:       perror("uname() error");
1.179     brouard  12558:    //#ifndef __INTEL_COMPILER 
                   12559: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  12560:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  12561:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  12562: #endif
1.169     brouard  12563: #endif
1.172     brouard  12564: 
1.286     brouard  12565:    //   void main ()
1.172     brouard  12566:    //   {
1.169     brouard  12567: #if defined(_MSC_VER)
1.174     brouard  12568:    if (IsWow64()){
1.191     brouard  12569:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   12570:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  12571:    }
                   12572:    else{
1.191     brouard  12573:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   12574:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  12575:    }
1.172     brouard  12576:    //     printf("\nPress Enter to continue...");
                   12577:    //     getchar();
                   12578:    //   }
                   12579: 
1.169     brouard  12580: #endif
                   12581:    
1.167     brouard  12582: 
1.219     brouard  12583: }
1.136     brouard  12584: 
1.219     brouard  12585: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  12586:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  12587:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  12588:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  12589:   /* double ftolpl = 1.e-10; */
1.180     brouard  12590:   double age, agebase, agelim;
1.203     brouard  12591:   double tot;
1.180     brouard  12592: 
1.202     brouard  12593:   strcpy(filerespl,"PL_");
                   12594:   strcat(filerespl,fileresu);
                   12595:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  12596:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   12597:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  12598:   }
1.288     brouard  12599:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   12600:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  12601:   pstamp(ficrespl);
1.288     brouard  12602:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  12603:   fprintf(ficrespl,"#Age ");
                   12604:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   12605:   fprintf(ficrespl,"\n");
1.180     brouard  12606:   
1.219     brouard  12607:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  12608: 
1.219     brouard  12609:   agebase=ageminpar;
                   12610:   agelim=agemaxpar;
1.180     brouard  12611: 
1.227     brouard  12612:   /* i1=pow(2,ncoveff); */
1.234     brouard  12613:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  12614:   if (cptcovn < 1){i1=1;}
1.180     brouard  12615: 
1.337     brouard  12616:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
1.238     brouard  12617:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  12618:       k=TKresult[nres];
1.338     brouard  12619:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12620:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
                   12621:       /*       continue; */
1.235     brouard  12622: 
1.238     brouard  12623:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12624:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   12625:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   12626:       /* k=k+1; */
                   12627:       /* to clean */
1.332     brouard  12628:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  12629:       fprintf(ficrespl,"#******");
                   12630:       printf("#******");
                   12631:       fprintf(ficlog,"#******");
1.337     brouard  12632:       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  12633:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
1.337     brouard  12634:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12635:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12636:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12637:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12638:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12639:       }
                   12640:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   12641:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12642:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12643:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12644:       /* } */
1.238     brouard  12645:       fprintf(ficrespl,"******\n");
                   12646:       printf("******\n");
                   12647:       fprintf(ficlog,"******\n");
                   12648:       if(invalidvarcomb[k]){
                   12649:        printf("\nCombination (%d) ignored because no case \n",k); 
                   12650:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   12651:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   12652:        continue;
                   12653:       }
1.219     brouard  12654: 
1.238     brouard  12655:       fprintf(ficrespl,"#Age ");
1.337     brouard  12656:       /* for(j=1;j<=cptcoveff;j++) { */
                   12657:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12658:       /* } */
                   12659:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
                   12660:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12661:       }
                   12662:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   12663:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  12664:     
1.238     brouard  12665:       for (age=agebase; age<=agelim; age++){
                   12666:        /* for (age=agebase; age<=agebase; age++){ */
1.337     brouard  12667:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
                   12668:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
1.238     brouard  12669:        fprintf(ficrespl,"%.0f ",age );
1.337     brouard  12670:        /* for(j=1;j<=cptcoveff;j++) */
                   12671:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12672:        for(j=1;j<=cptcovs;j++)
                   12673:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12674:        tot=0.;
                   12675:        for(i=1; i<=nlstate;i++){
                   12676:          tot +=  prlim[i][i];
                   12677:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   12678:        }
                   12679:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   12680:       } /* Age */
                   12681:       /* was end of cptcod */
1.337     brouard  12682:     } /* nres */
                   12683:   /* } /\* for each combination *\/ */
1.219     brouard  12684:   return 0;
1.180     brouard  12685: }
                   12686: 
1.218     brouard  12687: 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  12688:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  12689:        
                   12690:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   12691:    * at any age between ageminpar and agemaxpar
                   12692:         */
1.235     brouard  12693:   int i, j, k, i1, nres=0 ;
1.217     brouard  12694:   /* double ftolpl = 1.e-10; */
                   12695:   double age, agebase, agelim;
                   12696:   double tot;
1.218     brouard  12697:   /* double ***mobaverage; */
                   12698:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  12699: 
                   12700:   strcpy(fileresplb,"PLB_");
                   12701:   strcat(fileresplb,fileresu);
                   12702:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  12703:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   12704:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  12705:   }
1.288     brouard  12706:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   12707:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  12708:   pstamp(ficresplb);
1.288     brouard  12709:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  12710:   fprintf(ficresplb,"#Age ");
                   12711:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   12712:   fprintf(ficresplb,"\n");
                   12713:   
1.218     brouard  12714:   
                   12715:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   12716:   
                   12717:   agebase=ageminpar;
                   12718:   agelim=agemaxpar;
                   12719:   
                   12720:   
1.227     brouard  12721:   i1=pow(2,cptcoveff);
1.218     brouard  12722:   if (cptcovn < 1){i1=1;}
1.227     brouard  12723:   
1.238     brouard  12724:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.338     brouard  12725:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12726:       k=TKresult[nres];
                   12727:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   12728:      /* if(i1 != 1 && TKresult[nres]!= k) */
                   12729:      /*        continue; */
                   12730:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
1.238     brouard  12731:       fprintf(ficresplb,"#******");
                   12732:       printf("#******");
                   12733:       fprintf(ficlog,"#******");
1.338     brouard  12734:       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) */
                   12735:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12736:        fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12737:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12738:       }
1.338     brouard  12739:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
                   12740:       /*       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12741:       /*       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12742:       /*       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12743:       /* } */
                   12744:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12745:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12746:       /*       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12747:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12748:       /* } */
1.238     brouard  12749:       fprintf(ficresplb,"******\n");
                   12750:       printf("******\n");
                   12751:       fprintf(ficlog,"******\n");
                   12752:       if(invalidvarcomb[k]){
                   12753:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   12754:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   12755:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   12756:        continue;
                   12757:       }
1.218     brouard  12758:     
1.238     brouard  12759:       fprintf(ficresplb,"#Age ");
1.338     brouard  12760:       for(j=1;j<=cptcovs;j++) {
                   12761:        fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12762:       }
                   12763:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   12764:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  12765:     
                   12766:     
1.238     brouard  12767:       for (age=agebase; age<=agelim; age++){
                   12768:        /* for (age=agebase; age<=agebase; age++){ */
                   12769:        if(mobilavproj > 0){
                   12770:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   12771:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12772:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  12773:        }else if (mobilavproj == 0){
                   12774:          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);
                   12775:          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);
                   12776:          exit(1);
                   12777:        }else{
                   12778:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12779:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  12780:          /* printf("TOTOT\n"); */
                   12781:           /* exit(1); */
1.238     brouard  12782:        }
                   12783:        fprintf(ficresplb,"%.0f ",age );
1.338     brouard  12784:        for(j=1;j<=cptcovs;j++)
                   12785:          fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12786:        tot=0.;
                   12787:        for(i=1; i<=nlstate;i++){
                   12788:          tot +=  bprlim[i][i];
                   12789:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   12790:        }
                   12791:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   12792:       } /* Age */
                   12793:       /* was end of cptcod */
1.255     brouard  12794:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.338     brouard  12795:     /* } /\* end of any combination *\/ */
1.238     brouard  12796:   } /* end of nres */  
1.218     brouard  12797:   /* hBijx(p, bage, fage); */
                   12798:   /* fclose(ficrespijb); */
                   12799:   
                   12800:   return 0;
1.217     brouard  12801: }
1.218     brouard  12802:  
1.180     brouard  12803: int hPijx(double *p, int bage, int fage){
                   12804:     /*------------- h Pij x at various ages ------------*/
1.336     brouard  12805:   /* to be optimized with precov */
1.180     brouard  12806:   int stepsize;
                   12807:   int agelim;
                   12808:   int hstepm;
                   12809:   int nhstepm;
1.235     brouard  12810:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  12811: 
                   12812:   double agedeb;
                   12813:   double ***p3mat;
                   12814: 
1.337     brouard  12815:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   12816:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   12817:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12818:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12819:   }
                   12820:   printf("Computing pij: result on file '%s' \n", filerespij);
                   12821:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   12822:   
                   12823:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12824:   /*if (stepm<=24) stepsize=2;*/
                   12825:   
                   12826:   agelim=AGESUP;
                   12827:   hstepm=stepsize*YEARM; /* Every year of age */
                   12828:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   12829:   
                   12830:   /* hstepm=1;   aff par mois*/
                   12831:   pstamp(ficrespij);
                   12832:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   12833:   i1= pow(2,cptcoveff);
                   12834:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12835:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12836:   /*   k=k+1;  */
                   12837:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   12838:     k=TKresult[nres];
1.338     brouard  12839:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12840:     /* for(k=1; k<=i1;k++){ */
                   12841:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   12842:     /*         continue; */
                   12843:     fprintf(ficrespij,"\n#****** ");
                   12844:     for(j=1;j<=cptcovs;j++){
                   12845:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12846:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12847:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   12848:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12849:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12850:     }
                   12851:     fprintf(ficrespij,"******\n");
                   12852:     
                   12853:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   12854:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   12855:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   12856:       
                   12857:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12858:       
                   12859:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12860:       oldm=oldms;savm=savms;
                   12861:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
                   12862:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   12863:       for(i=1; i<=nlstate;i++)
                   12864:        for(j=1; j<=nlstate+ndeath;j++)
                   12865:          fprintf(ficrespij," %1d-%1d",i,j);
                   12866:       fprintf(ficrespij,"\n");
                   12867:       for (h=0; h<=nhstepm; h++){
                   12868:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12869:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.183     brouard  12870:        for(i=1; i<=nlstate;i++)
                   12871:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12872:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.183     brouard  12873:        fprintf(ficrespij,"\n");
                   12874:       }
1.337     brouard  12875:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12876:       fprintf(ficrespij,"\n");
1.180     brouard  12877:     }
1.337     brouard  12878:   }
                   12879:   /*}*/
                   12880:   return 0;
1.180     brouard  12881: }
1.218     brouard  12882:  
                   12883:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  12884:     /*------------- h Bij x at various ages ------------*/
1.336     brouard  12885:     /* To be optimized with precov */
1.217     brouard  12886:   int stepsize;
1.218     brouard  12887:   /* int agelim; */
                   12888:        int ageminl;
1.217     brouard  12889:   int hstepm;
                   12890:   int nhstepm;
1.238     brouard  12891:   int h, i, i1, j, k, nres;
1.218     brouard  12892:        
1.217     brouard  12893:   double agedeb;
                   12894:   double ***p3mat;
1.218     brouard  12895:        
                   12896:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   12897:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   12898:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12899:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12900:   }
                   12901:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   12902:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   12903:   
                   12904:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12905:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  12906:   
1.218     brouard  12907:   /* agelim=AGESUP; */
1.289     brouard  12908:   ageminl=AGEINF; /* was 30 */
1.218     brouard  12909:   hstepm=stepsize*YEARM; /* Every year of age */
                   12910:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   12911:   
                   12912:   /* hstepm=1;   aff par mois*/
                   12913:   pstamp(ficrespijb);
1.255     brouard  12914:   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  12915:   i1= pow(2,cptcoveff);
1.218     brouard  12916:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12917:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12918:   /*   k=k+1;  */
1.238     brouard  12919:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  12920:     k=TKresult[nres];
1.338     brouard  12921:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12922:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12923:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   12924:     /*         continue; */
                   12925:     fprintf(ficrespijb,"\n#****** ");
                   12926:     for(j=1;j<=cptcovs;j++){
1.338     brouard  12927:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.337     brouard  12928:       /* for(j=1;j<=cptcoveff;j++) */
                   12929:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12930:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12931:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12932:     }
                   12933:     fprintf(ficrespijb,"******\n");
                   12934:     if(invalidvarcomb[k]){  /* Is it necessary here? */
                   12935:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   12936:       continue;
                   12937:     }
                   12938:     
                   12939:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   12940:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   12941:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   12942:       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 */
                   12943:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
                   12944:       
                   12945:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12946:       
                   12947:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   12948:       /* and memory limitations if stepm is small */
                   12949:       
                   12950:       /* oldm=oldms;savm=savms; */
                   12951:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   12952:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
                   12953:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   12954:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
                   12955:       for(i=1; i<=nlstate;i++)
                   12956:        for(j=1; j<=nlstate+ndeath;j++)
                   12957:          fprintf(ficrespijb," %1d-%1d",i,j);
                   12958:       fprintf(ficrespijb,"\n");
                   12959:       for (h=0; h<=nhstepm; h++){
                   12960:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12961:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   12962:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  12963:        for(i=1; i<=nlstate;i++)
                   12964:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12965:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.217     brouard  12966:        fprintf(ficrespijb,"\n");
1.337     brouard  12967:       }
                   12968:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12969:       fprintf(ficrespijb,"\n");
                   12970:     } /* end age deb */
                   12971:     /* } /\* end combination *\/ */
1.238     brouard  12972:   } /* end nres */
1.218     brouard  12973:   return 0;
                   12974:  } /*  hBijx */
1.217     brouard  12975: 
1.180     brouard  12976: 
1.136     brouard  12977: /***********************************************/
                   12978: /**************** Main Program *****************/
                   12979: /***********************************************/
                   12980: 
                   12981: int main(int argc, char *argv[])
                   12982: {
                   12983: #ifdef GSL
                   12984:   const gsl_multimin_fminimizer_type *T;
                   12985:   size_t iteri = 0, it;
                   12986:   int rval = GSL_CONTINUE;
                   12987:   int status = GSL_SUCCESS;
                   12988:   double ssval;
                   12989: #endif
                   12990:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  12991:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   12992:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  12993:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  12994:   int jj, ll, li, lj, lk;
1.136     brouard  12995:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  12996:   int num_filled;
1.136     brouard  12997:   int itimes;
                   12998:   int NDIM=2;
                   12999:   int vpopbased=0;
1.235     brouard  13000:   int nres=0;
1.258     brouard  13001:   int endishere=0;
1.277     brouard  13002:   int noffset=0;
1.274     brouard  13003:   int ncurrv=0; /* Temporary variable */
                   13004:   
1.164     brouard  13005:   char ca[32], cb[32];
1.136     brouard  13006:   /*  FILE *fichtm; *//* Html File */
                   13007:   /* FILE *ficgp;*/ /*Gnuplot File */
                   13008:   struct stat info;
1.191     brouard  13009:   double agedeb=0.;
1.194     brouard  13010: 
                   13011:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  13012:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  13013: 
1.165     brouard  13014:   double fret;
1.191     brouard  13015:   double dum=0.; /* Dummy variable */
1.136     brouard  13016:   double ***p3mat;
1.218     brouard  13017:   /* double ***mobaverage; */
1.319     brouard  13018:   double wald;
1.164     brouard  13019: 
1.351     brouard  13020:   char line[MAXLINE], linetmp[MAXLINE];
1.197     brouard  13021:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   13022: 
1.234     brouard  13023:   char  modeltemp[MAXLINE];
1.332     brouard  13024:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  13025:   
1.136     brouard  13026:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  13027:   char *tok, *val; /* pathtot */
1.334     brouard  13028:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.195     brouard  13029:   int c,  h , cpt, c2;
1.191     brouard  13030:   int jl=0;
                   13031:   int i1, j1, jk, stepsize=0;
1.194     brouard  13032:   int count=0;
                   13033: 
1.164     brouard  13034:   int *tab; 
1.136     brouard  13035:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  13036:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   13037:   /* double anprojf, mprojf, jprojf; */
                   13038:   /* double jintmean,mintmean,aintmean;   */
                   13039:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   13040:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   13041:   double yrfproj= 10.0; /* Number of years of forward projections */
                   13042:   double yrbproj= 10.0; /* Number of years of backward projections */
                   13043:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  13044:   int mobilav=0,popforecast=0;
1.191     brouard  13045:   int hstepm=0, nhstepm=0;
1.136     brouard  13046:   int agemortsup;
                   13047:   float  sumlpop=0.;
                   13048:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   13049:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   13050: 
1.191     brouard  13051:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  13052:   double ftolpl=FTOL;
                   13053:   double **prlim;
1.217     brouard  13054:   double **bprlim;
1.317     brouard  13055:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   13056:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  13057:   double ***paramstart; /* Matrix of starting parameter values */
                   13058:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  13059:   double **matcov; /* Matrix of covariance */
1.203     brouard  13060:   double **hess; /* Hessian matrix */
1.136     brouard  13061:   double ***delti3; /* Scale */
                   13062:   double *delti; /* Scale */
                   13063:   double ***eij, ***vareij;
                   13064:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  13065: 
1.136     brouard  13066:   double *epj, vepp;
1.164     brouard  13067: 
1.273     brouard  13068:   double dateprev1, dateprev2;
1.296     brouard  13069:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   13070:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   13071: 
1.217     brouard  13072: 
1.136     brouard  13073:   double **ximort;
1.145     brouard  13074:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  13075:   int *dcwave;
                   13076: 
1.164     brouard  13077:   char z[1]="c";
1.136     brouard  13078: 
                   13079:   /*char  *strt;*/
                   13080:   char strtend[80];
1.126     brouard  13081: 
1.164     brouard  13082: 
1.126     brouard  13083: /*   setlocale (LC_ALL, ""); */
                   13084: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   13085: /*   textdomain (PACKAGE); */
                   13086: /*   setlocale (LC_CTYPE, ""); */
                   13087: /*   setlocale (LC_MESSAGES, ""); */
                   13088: 
                   13089:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  13090:   rstart_time = time(NULL);  
                   13091:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   13092:   start_time = *localtime(&rstart_time);
1.126     brouard  13093:   curr_time=start_time;
1.157     brouard  13094:   /*tml = *localtime(&start_time.tm_sec);*/
                   13095:   /* strcpy(strstart,asctime(&tml)); */
                   13096:   strcpy(strstart,asctime(&start_time));
1.126     brouard  13097: 
                   13098: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  13099: /*  tp.tm_sec = tp.tm_sec +86400; */
                   13100: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  13101: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   13102: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   13103: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  13104: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  13105: /*   strt=asctime(&tmg); */
                   13106: /*   printf("Time(after) =%s",strstart);  */
                   13107: /*  (void) time (&time_value);
                   13108: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   13109: *  tm = *localtime(&time_value);
                   13110: *  strstart=asctime(&tm);
                   13111: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   13112: */
                   13113: 
                   13114:   nberr=0; /* Number of errors and warnings */
                   13115:   nbwarn=0;
1.184     brouard  13116: #ifdef WIN32
                   13117:   _getcwd(pathcd, size);
                   13118: #else
1.126     brouard  13119:   getcwd(pathcd, size);
1.184     brouard  13120: #endif
1.191     brouard  13121:   syscompilerinfo(0);
1.196     brouard  13122:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  13123:   if(argc <=1){
                   13124:     printf("\nEnter the parameter file name: ");
1.205     brouard  13125:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   13126:       printf("ERROR Empty parameter file name\n");
                   13127:       goto end;
                   13128:     }
1.126     brouard  13129:     i=strlen(pathr);
                   13130:     if(pathr[i-1]=='\n')
                   13131:       pathr[i-1]='\0';
1.156     brouard  13132:     i=strlen(pathr);
1.205     brouard  13133:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  13134:       pathr[i-1]='\0';
1.205     brouard  13135:     }
                   13136:     i=strlen(pathr);
                   13137:     if( i==0 ){
                   13138:       printf("ERROR Empty parameter file name\n");
                   13139:       goto end;
                   13140:     }
                   13141:     for (tok = pathr; tok != NULL; ){
1.126     brouard  13142:       printf("Pathr |%s|\n",pathr);
                   13143:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   13144:       printf("val= |%s| pathr=%s\n",val,pathr);
                   13145:       strcpy (pathtot, val);
                   13146:       if(pathr[0] == '\0') break; /* Dirty */
                   13147:     }
                   13148:   }
1.281     brouard  13149:   else if (argc<=2){
                   13150:     strcpy(pathtot,argv[1]);
                   13151:   }
1.126     brouard  13152:   else{
                   13153:     strcpy(pathtot,argv[1]);
1.281     brouard  13154:     strcpy(z,argv[2]);
                   13155:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  13156:   }
                   13157:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   13158:   /*cygwin_split_path(pathtot,path,optionfile);
                   13159:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   13160:   /* cutv(path,optionfile,pathtot,'\\');*/
                   13161: 
                   13162:   /* Split argv[0], imach program to get pathimach */
                   13163:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   13164:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   13165:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   13166:  /*   strcpy(pathimach,argv[0]); */
                   13167:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   13168:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   13169:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  13170: #ifdef WIN32
                   13171:   _chdir(path); /* Can be a relative path */
                   13172:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   13173: #else
1.126     brouard  13174:   chdir(path); /* Can be a relative path */
1.184     brouard  13175:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   13176: #endif
                   13177:   printf("Current directory %s!\n",pathcd);
1.126     brouard  13178:   strcpy(command,"mkdir ");
                   13179:   strcat(command,optionfilefiname);
                   13180:   if((outcmd=system(command)) != 0){
1.169     brouard  13181:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  13182:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   13183:     /* fclose(ficlog); */
                   13184: /*     exit(1); */
                   13185:   }
                   13186: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   13187: /*     perror("mkdir"); */
                   13188: /*   } */
                   13189: 
                   13190:   /*-------- arguments in the command line --------*/
                   13191: 
1.186     brouard  13192:   /* Main Log file */
1.126     brouard  13193:   strcat(filelog, optionfilefiname);
                   13194:   strcat(filelog,".log");    /* */
                   13195:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   13196:     printf("Problem with logfile %s\n",filelog);
                   13197:     goto end;
                   13198:   }
                   13199:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  13200:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  13201:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   13202:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   13203:  path=%s \n\
                   13204:  optionfile=%s\n\
                   13205:  optionfilext=%s\n\
1.156     brouard  13206:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  13207: 
1.197     brouard  13208:   syscompilerinfo(1);
1.167     brouard  13209: 
1.126     brouard  13210:   printf("Local time (at start):%s",strstart);
                   13211:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   13212:   fflush(ficlog);
                   13213: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  13214: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  13215: 
                   13216:   /* */
                   13217:   strcpy(fileres,"r");
                   13218:   strcat(fileres, optionfilefiname);
1.201     brouard  13219:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  13220:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  13221:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  13222: 
1.186     brouard  13223:   /* Main ---------arguments file --------*/
1.126     brouard  13224: 
                   13225:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  13226:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   13227:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  13228:     fflush(ficlog);
1.149     brouard  13229:     /* goto end; */
                   13230:     exit(70); 
1.126     brouard  13231:   }
                   13232: 
                   13233:   strcpy(filereso,"o");
1.201     brouard  13234:   strcat(filereso,fileresu);
1.126     brouard  13235:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   13236:     printf("Problem with Output resultfile: %s\n", filereso);
                   13237:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   13238:     fflush(ficlog);
                   13239:     goto end;
                   13240:   }
1.278     brouard  13241:       /*-------- Rewriting parameter file ----------*/
                   13242:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   13243:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   13244:   strcat(rfileres,".");    /* */
                   13245:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   13246:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   13247:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   13248:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   13249:     fflush(ficlog);
                   13250:     goto end;
                   13251:   }
                   13252:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  13253: 
1.278     brouard  13254:                                      
1.126     brouard  13255:   /* Reads comments: lines beginning with '#' */
                   13256:   numlinepar=0;
1.277     brouard  13257:   /* Is it a BOM UTF-8 Windows file? */
                   13258:   /* First parameter line */
1.197     brouard  13259:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  13260:     noffset=0;
                   13261:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   13262:     {
                   13263:       noffset=noffset+3;
                   13264:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   13265:     }
1.302     brouard  13266: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   13267:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  13268:     {
                   13269:       noffset=noffset+2;
                   13270:       printf("# File is an UTF16BE BOM file\n");
                   13271:     }
                   13272:     else if( line[0] == 0 && line[1] == 0)
                   13273:     {
                   13274:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   13275:        noffset=noffset+4;
                   13276:        printf("# File is an UTF16BE BOM file\n");
                   13277:       }
                   13278:     } else{
                   13279:       ;/*printf(" Not a BOM file\n");*/
                   13280:     }
                   13281:   
1.197     brouard  13282:     /* If line starts with a # it is a comment */
1.277     brouard  13283:     if (line[noffset] == '#') {
1.197     brouard  13284:       numlinepar++;
                   13285:       fputs(line,stdout);
                   13286:       fputs(line,ficparo);
1.278     brouard  13287:       fputs(line,ficres);
1.197     brouard  13288:       fputs(line,ficlog);
                   13289:       continue;
                   13290:     }else
                   13291:       break;
                   13292:   }
                   13293:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   13294:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   13295:     if (num_filled != 5) {
                   13296:       printf("Should be 5 parameters\n");
1.283     brouard  13297:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  13298:     }
1.126     brouard  13299:     numlinepar++;
1.197     brouard  13300:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  13301:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   13302:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   13303:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  13304:   }
                   13305:   /* Second parameter line */
                   13306:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  13307:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   13308:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  13309:     if (line[0] == '#') {
                   13310:       numlinepar++;
1.283     brouard  13311:       printf("%s",line);
                   13312:       fprintf(ficres,"%s",line);
                   13313:       fprintf(ficparo,"%s",line);
                   13314:       fprintf(ficlog,"%s",line);
1.197     brouard  13315:       continue;
                   13316:     }else
                   13317:       break;
                   13318:   }
1.223     brouard  13319:   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", \
                   13320:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   13321:     if (num_filled != 11) {
                   13322:       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  13323:       printf("but line=%s\n",line);
1.283     brouard  13324:       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");
                   13325:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  13326:     }
1.286     brouard  13327:     if( lastpass > maxwav){
                   13328:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   13329:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   13330:       fflush(ficlog);
                   13331:       goto end;
                   13332:     }
                   13333:       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  13334:     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  13335:     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  13336:     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  13337:   }
1.203     brouard  13338:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  13339:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  13340:   /* Third parameter line */
                   13341:   while(fgets(line, MAXLINE, ficpar)) {
                   13342:     /* If line starts with a # it is a comment */
                   13343:     if (line[0] == '#') {
                   13344:       numlinepar++;
1.283     brouard  13345:       printf("%s",line);
                   13346:       fprintf(ficres,"%s",line);
                   13347:       fprintf(ficparo,"%s",line);
                   13348:       fprintf(ficlog,"%s",line);
1.197     brouard  13349:       continue;
                   13350:     }else
                   13351:       break;
                   13352:   }
1.351     brouard  13353:   if((num_filled=sscanf(line,"model=%[^.\n]", model)) !=EOF){ /* Every character after model but dot and  return */
                   13354:     if (num_filled != 1){
                   13355:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   13356:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   13357:       model[0]='\0';
                   13358:       goto end;
                   13359:     }else{
                   13360:       trimbtab(linetmp,line); /* Trims multiple blanks in line */
                   13361:       strcpy(line, linetmp);
                   13362:     }
                   13363:   }
                   13364:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){ /* Every character after 1+age but dot and  return */
1.279     brouard  13365:     if (num_filled != 1){
1.302     brouard  13366:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   13367:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  13368:       model[0]='\0';
                   13369:       goto end;
                   13370:     }
                   13371:     else{
                   13372:       if (model[0]=='+'){
                   13373:        for(i=1; i<=strlen(model);i++)
                   13374:          modeltemp[i-1]=model[i];
1.201     brouard  13375:        strcpy(model,modeltemp); 
1.197     brouard  13376:       }
                   13377:     }
1.338     brouard  13378:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  13379:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  13380:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   13381:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   13382:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  13383:   }
                   13384:   /* 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); */
                   13385:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   13386:   /* 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  13387:   /* 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); */
                   13388:   /* 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  13389:   fflush(ficlog);
1.190     brouard  13390:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   13391:   if(model[0]=='#'){
1.279     brouard  13392:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   13393:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   13394:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  13395:     if(mle != -1){
1.279     brouard  13396:       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  13397:       exit(1);
                   13398:     }
                   13399:   }
1.126     brouard  13400:   while((c=getc(ficpar))=='#' && c!= EOF){
                   13401:     ungetc(c,ficpar);
                   13402:     fgets(line, MAXLINE, ficpar);
                   13403:     numlinepar++;
1.195     brouard  13404:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   13405:       z[0]=line[1];
1.342     brouard  13406:     }else if(line[1]=='d'){ /* For debugging individual values of covariates in ficresilk */
1.343     brouard  13407:       debugILK=1;printf("DebugILK\n");
1.195     brouard  13408:     }
                   13409:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  13410:     fputs(line, stdout);
                   13411:     //puts(line);
1.126     brouard  13412:     fputs(line,ficparo);
                   13413:     fputs(line,ficlog);
                   13414:   }
                   13415:   ungetc(c,ficpar);
                   13416: 
                   13417:    
1.290     brouard  13418:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   13419:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   13420:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
1.341     brouard  13421:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /\**< Time varying covariate (dummy and quantitative)*\/ */
                   13422:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /**< Might be better */
1.136     brouard  13423:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   13424:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   13425:      v1+v2*age+v2*v3 makes cptcovn = 3
                   13426:   */
                   13427:   if (strlen(model)>1) 
1.187     brouard  13428:     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  13429:   else
1.187     brouard  13430:     ncovmodel=2; /* Constant and age */
1.133     brouard  13431:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   13432:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  13433:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   13434:     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);
                   13435:     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);
                   13436:     fflush(stdout);
                   13437:     fclose (ficlog);
                   13438:     goto end;
                   13439:   }
1.126     brouard  13440:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   13441:   delti=delti3[1][1];
                   13442:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   13443:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  13444: /* We could also provide initial parameters values giving by simple logistic regression 
                   13445:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   13446:       /* for(i=1;i<nlstate;i++){ */
                   13447:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   13448:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   13449:       /* } */
1.126     brouard  13450:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  13451:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   13452:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  13453:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   13454:     fclose (ficparo);
                   13455:     fclose (ficlog);
                   13456:     goto end;
                   13457:     exit(0);
1.220     brouard  13458:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  13459:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  13460:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   13461:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  13462:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   13463:     matcov=matrix(1,npar,1,npar);
1.203     brouard  13464:     hess=matrix(1,npar,1,npar);
1.220     brouard  13465:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  13466:     /* Read guessed parameters */
1.126     brouard  13467:     /* Reads comments: lines beginning with '#' */
                   13468:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13469:       ungetc(c,ficpar);
                   13470:       fgets(line, MAXLINE, ficpar);
                   13471:       numlinepar++;
1.141     brouard  13472:       fputs(line,stdout);
1.126     brouard  13473:       fputs(line,ficparo);
                   13474:       fputs(line,ficlog);
                   13475:     }
                   13476:     ungetc(c,ficpar);
                   13477:     
                   13478:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  13479:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  13480:     for(i=1; i <=nlstate; i++){
1.234     brouard  13481:       j=0;
1.126     brouard  13482:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  13483:        if(jj==i) continue;
                   13484:        j++;
1.292     brouard  13485:        while((c=getc(ficpar))=='#' && c!= EOF){
                   13486:          ungetc(c,ficpar);
                   13487:          fgets(line, MAXLINE, ficpar);
                   13488:          numlinepar++;
                   13489:          fputs(line,stdout);
                   13490:          fputs(line,ficparo);
                   13491:          fputs(line,ficlog);
                   13492:        }
                   13493:        ungetc(c,ficpar);
1.234     brouard  13494:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   13495:        if ((i1 != i) || (j1 != jj)){
                   13496:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  13497: It might be a problem of design; if ncovcol and the model are correct\n \
                   13498: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  13499:          exit(1);
                   13500:        }
                   13501:        fprintf(ficparo,"%1d%1d",i1,j1);
                   13502:        if(mle==1)
                   13503:          printf("%1d%1d",i,jj);
                   13504:        fprintf(ficlog,"%1d%1d",i,jj);
                   13505:        for(k=1; k<=ncovmodel;k++){
                   13506:          fscanf(ficpar," %lf",&param[i][j][k]);
                   13507:          if(mle==1){
                   13508:            printf(" %lf",param[i][j][k]);
                   13509:            fprintf(ficlog," %lf",param[i][j][k]);
                   13510:          }
                   13511:          else
                   13512:            fprintf(ficlog," %lf",param[i][j][k]);
                   13513:          fprintf(ficparo," %lf",param[i][j][k]);
                   13514:        }
                   13515:        fscanf(ficpar,"\n");
                   13516:        numlinepar++;
                   13517:        if(mle==1)
                   13518:          printf("\n");
                   13519:        fprintf(ficlog,"\n");
                   13520:        fprintf(ficparo,"\n");
1.126     brouard  13521:       }
                   13522:     }  
                   13523:     fflush(ficlog);
1.234     brouard  13524:     
1.251     brouard  13525:     /* Reads parameters values */
1.126     brouard  13526:     p=param[1][1];
1.251     brouard  13527:     pstart=paramstart[1][1];
1.126     brouard  13528:     
                   13529:     /* Reads comments: lines beginning with '#' */
                   13530:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13531:       ungetc(c,ficpar);
                   13532:       fgets(line, MAXLINE, ficpar);
                   13533:       numlinepar++;
1.141     brouard  13534:       fputs(line,stdout);
1.126     brouard  13535:       fputs(line,ficparo);
                   13536:       fputs(line,ficlog);
                   13537:     }
                   13538:     ungetc(c,ficpar);
                   13539: 
                   13540:     for(i=1; i <=nlstate; i++){
                   13541:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  13542:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   13543:        if ( (i1-i) * (j1-j) != 0){
                   13544:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   13545:          exit(1);
                   13546:        }
                   13547:        printf("%1d%1d",i,j);
                   13548:        fprintf(ficparo,"%1d%1d",i1,j1);
                   13549:        fprintf(ficlog,"%1d%1d",i1,j1);
                   13550:        for(k=1; k<=ncovmodel;k++){
                   13551:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   13552:          printf(" %le",delti3[i][j][k]);
                   13553:          fprintf(ficparo," %le",delti3[i][j][k]);
                   13554:          fprintf(ficlog," %le",delti3[i][j][k]);
                   13555:        }
                   13556:        fscanf(ficpar,"\n");
                   13557:        numlinepar++;
                   13558:        printf("\n");
                   13559:        fprintf(ficparo,"\n");
                   13560:        fprintf(ficlog,"\n");
1.126     brouard  13561:       }
                   13562:     }
                   13563:     fflush(ficlog);
1.234     brouard  13564:     
1.145     brouard  13565:     /* Reads covariance matrix */
1.126     brouard  13566:     delti=delti3[1][1];
1.220     brouard  13567:                
                   13568:                
1.126     brouard  13569:     /* 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  13570:                
1.126     brouard  13571:     /* Reads comments: lines beginning with '#' */
                   13572:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13573:       ungetc(c,ficpar);
                   13574:       fgets(line, MAXLINE, ficpar);
                   13575:       numlinepar++;
1.141     brouard  13576:       fputs(line,stdout);
1.126     brouard  13577:       fputs(line,ficparo);
                   13578:       fputs(line,ficlog);
                   13579:     }
                   13580:     ungetc(c,ficpar);
1.220     brouard  13581:                
1.126     brouard  13582:     matcov=matrix(1,npar,1,npar);
1.203     brouard  13583:     hess=matrix(1,npar,1,npar);
1.131     brouard  13584:     for(i=1; i <=npar; i++)
                   13585:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  13586:                
1.194     brouard  13587:     /* Scans npar lines */
1.126     brouard  13588:     for(i=1; i <=npar; i++){
1.226     brouard  13589:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  13590:       if(count != 3){
1.226     brouard  13591:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  13592: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   13593: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  13594:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  13595: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   13596: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  13597:        exit(1);
1.220     brouard  13598:       }else{
1.226     brouard  13599:        if(mle==1)
                   13600:          printf("%1d%1d%d",i1,j1,jk);
                   13601:       }
                   13602:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   13603:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  13604:       for(j=1; j <=i; j++){
1.226     brouard  13605:        fscanf(ficpar," %le",&matcov[i][j]);
                   13606:        if(mle==1){
                   13607:          printf(" %.5le",matcov[i][j]);
                   13608:        }
                   13609:        fprintf(ficlog," %.5le",matcov[i][j]);
                   13610:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  13611:       }
                   13612:       fscanf(ficpar,"\n");
                   13613:       numlinepar++;
                   13614:       if(mle==1)
1.220     brouard  13615:                                printf("\n");
1.126     brouard  13616:       fprintf(ficlog,"\n");
                   13617:       fprintf(ficparo,"\n");
                   13618:     }
1.194     brouard  13619:     /* End of read covariance matrix npar lines */
1.126     brouard  13620:     for(i=1; i <=npar; i++)
                   13621:       for(j=i+1;j<=npar;j++)
1.226     brouard  13622:        matcov[i][j]=matcov[j][i];
1.126     brouard  13623:     
                   13624:     if(mle==1)
                   13625:       printf("\n");
                   13626:     fprintf(ficlog,"\n");
                   13627:     
                   13628:     fflush(ficlog);
                   13629:     
                   13630:   }    /* End of mle != -3 */
1.218     brouard  13631:   
1.186     brouard  13632:   /*  Main data
                   13633:    */
1.290     brouard  13634:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   13635:   /* num=lvector(1,n); */
                   13636:   /* moisnais=vector(1,n); */
                   13637:   /* annais=vector(1,n); */
                   13638:   /* moisdc=vector(1,n); */
                   13639:   /* andc=vector(1,n); */
                   13640:   /* weight=vector(1,n); */
                   13641:   /* agedc=vector(1,n); */
                   13642:   /* cod=ivector(1,n); */
                   13643:   /* for(i=1;i<=n;i++){ */
                   13644:   num=lvector(firstobs,lastobs);
                   13645:   moisnais=vector(firstobs,lastobs);
                   13646:   annais=vector(firstobs,lastobs);
                   13647:   moisdc=vector(firstobs,lastobs);
                   13648:   andc=vector(firstobs,lastobs);
                   13649:   weight=vector(firstobs,lastobs);
                   13650:   agedc=vector(firstobs,lastobs);
                   13651:   cod=ivector(firstobs,lastobs);
                   13652:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  13653:     num[i]=0;
                   13654:     moisnais[i]=0;
                   13655:     annais[i]=0;
                   13656:     moisdc[i]=0;
                   13657:     andc[i]=0;
                   13658:     agedc[i]=0;
                   13659:     cod[i]=0;
                   13660:     weight[i]=1.0; /* Equal weights, 1 by default */
                   13661:   }
1.290     brouard  13662:   mint=matrix(1,maxwav,firstobs,lastobs);
                   13663:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  13664:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
1.336     brouard  13665:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
1.126     brouard  13666:   tab=ivector(1,NCOVMAX);
1.144     brouard  13667:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  13668:   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  13669: 
1.136     brouard  13670:   /* Reads data from file datafile */
                   13671:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   13672:     goto end;
                   13673: 
                   13674:   /* Calculation of the number of parameters from char model */
1.234     brouard  13675:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  13676:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   13677:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   13678:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   13679:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  13680:   */
                   13681:   
                   13682:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   13683:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  13684:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335     brouard  13685:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  13686:   TvarsD=ivector(1,NCOVMAX); /*  */
                   13687:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   13688:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  13689:   TvarF=ivector(1,NCOVMAX); /*  */
                   13690:   TvarFind=ivector(1,NCOVMAX); /*  */
                   13691:   TvarV=ivector(1,NCOVMAX); /*  */
                   13692:   TvarVind=ivector(1,NCOVMAX); /*  */
                   13693:   TvarA=ivector(1,NCOVMAX); /*  */
                   13694:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  13695:   TvarFD=ivector(1,NCOVMAX); /*  */
                   13696:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   13697:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   13698:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   13699:   TvarVD=ivector(1,NCOVMAX); /*  */
                   13700:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   13701:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   13702:   TvarVQind=ivector(1,NCOVMAX); /*  */
1.339     brouard  13703:   TvarVV=ivector(1,NCOVMAX); /*  */
                   13704:   TvarVVind=ivector(1,NCOVMAX); /*  */
1.349     brouard  13705:   TvarVVA=ivector(1,NCOVMAX); /*  */
                   13706:   TvarVVAind=ivector(1,NCOVMAX); /*  */
                   13707:   TvarAVVA=ivector(1,NCOVMAX); /*  */
                   13708:   TvarAVVAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  13709: 
1.230     brouard  13710:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  13711:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  13712:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   13713:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   13714:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.349     brouard  13715:   DummyV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   13716:   FixedV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   13717: 
1.137     brouard  13718:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   13719:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   13720:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   13721:   */
                   13722:   /* For model-covariate k tells which data-covariate to use but
                   13723:     because this model-covariate is a construction we invent a new column
                   13724:     ncovcol + k1
                   13725:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   13726:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  13727:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   13728:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  13729:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   13730:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  13731:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  13732:   */
1.145     brouard  13733:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   13734:   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  13735:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   13736:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.351     brouard  13737:   Tvardk=imatrix(0,NCOVMAX,1,2);
1.145     brouard  13738:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  13739:                         4 covariates (3 plus signs)
                   13740:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  13741:                           */  
                   13742:   for(i=1;i<NCOVMAX;i++)
                   13743:     Tage[i]=0;
1.230     brouard  13744:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  13745:                                * individual dummy, fixed or varying:
                   13746:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   13747:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  13748:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   13749:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   13750:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   13751:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   13752:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  13753:                                * individual quantitative, fixed or varying:
                   13754:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   13755:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   13756:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.349     brouard  13757: 
                   13758: /* Probably useless zeroes */
                   13759:   for(i=1;i<NCOVMAX;i++){
                   13760:     DummyV[i]=0;
                   13761:     FixedV[i]=0;
                   13762:   }
                   13763: 
                   13764:   for(i=1; i <=ncovcol;i++){
                   13765:     DummyV[i]=0;
                   13766:     FixedV[i]=0;
                   13767:   }
                   13768:   for(i=ncovcol+1; i <=ncovcol+nqv;i++){
                   13769:     DummyV[i]=1;
                   13770:     FixedV[i]=0;
                   13771:   }
                   13772:   for(i=ncovcol+nqv+1; i <=ncovcol+nqv+ntv;i++){
                   13773:     DummyV[i]=0;
                   13774:     FixedV[i]=1;
                   13775:   }
                   13776:   for(i=ncovcol+nqv+ntv+1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   13777:     DummyV[i]=1;
                   13778:     FixedV[i]=1;
                   13779:   }
                   13780:   for(i=1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   13781:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",i,i,DummyV[i],i,FixedV[i]);
                   13782:     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]);
                   13783:   }
                   13784: 
                   13785: 
                   13786: 
1.186     brouard  13787: /* Main decodemodel */
                   13788: 
1.187     brouard  13789: 
1.223     brouard  13790:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  13791:     goto end;
                   13792: 
1.137     brouard  13793:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   13794:     nbwarn++;
                   13795:     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); 
                   13796:     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); 
                   13797:   }
1.136     brouard  13798:     /*  if(mle==1){*/
1.137     brouard  13799:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   13800:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  13801:   }
                   13802: 
                   13803:     /*-calculation of age at interview from date of interview and age at death -*/
                   13804:   agev=matrix(1,maxwav,1,imx);
                   13805: 
                   13806:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   13807:     goto end;
                   13808: 
1.126     brouard  13809: 
1.136     brouard  13810:   agegomp=(int)agemin;
1.290     brouard  13811:   free_vector(moisnais,firstobs,lastobs);
                   13812:   free_vector(annais,firstobs,lastobs);
1.126     brouard  13813:   /* free_matrix(mint,1,maxwav,1,n);
                   13814:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  13815:   /* free_vector(moisdc,1,n); */
                   13816:   /* free_vector(andc,1,n); */
1.145     brouard  13817:   /* */
                   13818:   
1.126     brouard  13819:   wav=ivector(1,imx);
1.214     brouard  13820:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13821:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13822:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13823:   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.*/
                   13824:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   13825:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  13826:    
                   13827:   /* Concatenates waves */
1.214     brouard  13828:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   13829:      Death is a valid wave (if date is known).
                   13830:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   13831:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   13832:      and mw[mi+1][i]. dh depends on stepm.
                   13833:   */
                   13834: 
1.126     brouard  13835:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  13836:   /* Concatenates waves */
1.145     brouard  13837:  
1.290     brouard  13838:   free_vector(moisdc,firstobs,lastobs);
                   13839:   free_vector(andc,firstobs,lastobs);
1.215     brouard  13840: 
1.126     brouard  13841:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   13842:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   13843:   ncodemax[1]=1;
1.145     brouard  13844:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  13845:   cptcoveff=0;
1.220     brouard  13846:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335     brouard  13847:     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  13848:   }
                   13849:   
                   13850:   ncovcombmax=pow(2,cptcoveff);
1.338     brouard  13851:   invalidvarcomb=ivector(0, ncovcombmax); 
                   13852:   for(i=0;i<ncovcombmax;i++)
1.227     brouard  13853:     invalidvarcomb[i]=0;
                   13854:   
1.211     brouard  13855:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  13856:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  13857:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  13858:   
1.200     brouard  13859:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  13860:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  13861:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  13862:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   13863:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   13864:    * (currently 0 or 1) in the data.
                   13865:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   13866:    * corresponding modality (h,j).
                   13867:    */
                   13868: 
1.145     brouard  13869:   h=0;
                   13870:   /*if (cptcovn > 0) */
1.126     brouard  13871:   m=pow(2,cptcoveff);
                   13872:  
1.144     brouard  13873:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  13874:           * For k=4 covariates, h goes from 1 to m=2**k
                   13875:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   13876:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  13877:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   13878:           *______________________________   *______________________
                   13879:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   13880:           *     2     2     1     1     1   *     1     0  0  0  1 
                   13881:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   13882:           *     4     2     2     1     1   *     3     0  0  1  1 
                   13883:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   13884:           *     6     2     1     2     1   *     5     0  1  0  1 
                   13885:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   13886:           *     8     2     2     2     1   *     7     0  1  1  1 
                   13887:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   13888:           *    10     2     1     1     2   *     9     1  0  0  1 
                   13889:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   13890:           *    12     2     2     1     2   *    11     1  0  1  1 
                   13891:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   13892:           *    14     2     1     2     2   *    13     1  1  0  1 
                   13893:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   13894:           *    16     2     2     2     2   *    15     1  1  1  1          
                   13895:           */                                     
1.212     brouard  13896:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  13897:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   13898:      * and the value of each covariate?
                   13899:      * V1=1, V2=1, V3=2, V4=1 ?
                   13900:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   13901:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   13902:      * In order to get the real value in the data, we use nbcode
                   13903:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   13904:      * We are keeping this crazy system in order to be able (in the future?) 
                   13905:      * to have more than 2 values (0 or 1) for a covariate.
                   13906:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   13907:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   13908:      *              bbbbbbbb
                   13909:      *              76543210     
                   13910:      *   h-1        00000101 (6-1=5)
1.219     brouard  13911:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  13912:      *           &
                   13913:      *     1        00000001 (1)
1.219     brouard  13914:      *              00000000        = 1 & ((h-1) >> (k-1))
                   13915:      *          +1= 00000001 =1 
1.211     brouard  13916:      *
                   13917:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   13918:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   13919:      *    >>k'            11
                   13920:      *          &   00000001
                   13921:      *            = 00000001
                   13922:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   13923:      * Reverse h=6 and m=16?
                   13924:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   13925:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   13926:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   13927:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   13928:      * V3=decodtabm(14,3,2**4)=2
                   13929:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   13930:      *(h-1) >> (j-1)    0011 =13 >> 2
                   13931:      *          &1 000000001
                   13932:      *           = 000000001
                   13933:      *         +1= 000000010 =2
                   13934:      *                  2211
                   13935:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   13936:      *                  V3=2
1.220     brouard  13937:                 * codtabm and decodtabm are identical
1.211     brouard  13938:      */
                   13939: 
1.145     brouard  13940: 
                   13941:  free_ivector(Ndum,-1,NCOVMAX);
                   13942: 
                   13943: 
1.126     brouard  13944:     
1.186     brouard  13945:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  13946:   strcpy(optionfilegnuplot,optionfilefiname);
                   13947:   if(mle==-3)
1.201     brouard  13948:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  13949:   strcat(optionfilegnuplot,".gp");
                   13950: 
                   13951:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   13952:     printf("Problem with file %s",optionfilegnuplot);
                   13953:   }
                   13954:   else{
1.204     brouard  13955:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  13956:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  13957:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   13958:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  13959:   }
                   13960:   /*  fclose(ficgp);*/
1.186     brouard  13961: 
                   13962: 
                   13963:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  13964: 
                   13965:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   13966:   if(mle==-3)
1.201     brouard  13967:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  13968:   strcat(optionfilehtm,".htm");
                   13969:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  13970:     printf("Problem with %s \n",optionfilehtm);
                   13971:     exit(0);
1.126     brouard  13972:   }
                   13973: 
                   13974:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   13975:   strcat(optionfilehtmcov,"-cov.htm");
                   13976:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   13977:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   13978:   }
                   13979:   else{
                   13980:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   13981: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13982: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  13983:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   13984:   }
                   13985: 
1.335     brouard  13986:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   13987: <title>IMaCh %s</title></head>\n\
                   13988:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   13989: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   13990: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   13991: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   13992: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   13993:   
                   13994:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13995: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  13996: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.337     brouard  13997: 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  13998: \n\
                   13999: <hr  size=\"2\" color=\"#EC5E5E\">\
                   14000:  <ul><li><h4>Parameter files</h4>\n\
                   14001:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   14002:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   14003:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   14004:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   14005:  - Date and time at start: %s</ul>\n",\
1.335     brouard  14006:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  14007:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   14008:          fileres,fileres,\
                   14009:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   14010:   fflush(fichtm);
                   14011: 
                   14012:   strcpy(pathr,path);
                   14013:   strcat(pathr,optionfilefiname);
1.184     brouard  14014: #ifdef WIN32
                   14015:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   14016: #else
1.126     brouard  14017:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  14018: #endif
                   14019:          
1.126     brouard  14020:   
1.220     brouard  14021:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   14022:                 and for any valid combination of covariates
1.126     brouard  14023:      and prints on file fileres'p'. */
1.251     brouard  14024:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  14025:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  14026: 
                   14027:   fprintf(fichtm,"\n");
1.286     brouard  14028:   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  14029:          ftol, stepm);
                   14030:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   14031:   ncurrv=1;
                   14032:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   14033:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   14034:   ncurrv=i;
                   14035:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  14036:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  14037:   ncurrv=i;
                   14038:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  14039:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  14040:   ncurrv=i;
                   14041:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   14042:   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", \
                   14043:           nlstate, ndeath, maxwav, mle, weightopt);
                   14044: 
                   14045:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   14046: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   14047: 
                   14048:   
1.317     brouard  14049:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  14050: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   14051: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  14052:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  14053:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  14054:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14055:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14056:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14057:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  14058: 
1.126     brouard  14059:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   14060:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   14061:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   14062: 
                   14063:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  14064:   /* For mortality only */
1.126     brouard  14065:   if (mle==-3){
1.136     brouard  14066:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  14067:     for(i=1;i<=NDIM;i++)
                   14068:       for(j=1;j<=NDIM;j++)
                   14069:        ximort[i][j]=0.;
1.186     brouard  14070:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  14071:     cens=ivector(firstobs,lastobs);
                   14072:     ageexmed=vector(firstobs,lastobs);
                   14073:     agecens=vector(firstobs,lastobs);
                   14074:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  14075:                
1.126     brouard  14076:     for (i=1; i<=imx; i++){
                   14077:       dcwave[i]=-1;
                   14078:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  14079:        if (s[m][i]>nlstate) {
                   14080:          dcwave[i]=m;
                   14081:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   14082:          break;
                   14083:        }
1.126     brouard  14084:     }
1.226     brouard  14085:     
1.126     brouard  14086:     for (i=1; i<=imx; i++) {
                   14087:       if (wav[i]>0){
1.226     brouard  14088:        ageexmed[i]=agev[mw[1][i]][i];
                   14089:        j=wav[i];
                   14090:        agecens[i]=1.; 
                   14091:        
                   14092:        if (ageexmed[i]> 1 && wav[i] > 0){
                   14093:          agecens[i]=agev[mw[j][i]][i];
                   14094:          cens[i]= 1;
                   14095:        }else if (ageexmed[i]< 1) 
                   14096:          cens[i]= -1;
                   14097:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   14098:          cens[i]=0 ;
1.126     brouard  14099:       }
                   14100:       else cens[i]=-1;
                   14101:     }
                   14102:     
                   14103:     for (i=1;i<=NDIM;i++) {
                   14104:       for (j=1;j<=NDIM;j++)
1.226     brouard  14105:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  14106:     }
                   14107:     
1.302     brouard  14108:     p[1]=0.0268; p[NDIM]=0.083;
                   14109:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  14110:     
                   14111:     
1.136     brouard  14112: #ifdef GSL
                   14113:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  14114: #else
1.126     brouard  14115:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  14116: #endif
1.201     brouard  14117:     strcpy(filerespow,"POW-MORT_"); 
                   14118:     strcat(filerespow,fileresu);
1.126     brouard  14119:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   14120:       printf("Problem with resultfile: %s\n", filerespow);
                   14121:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   14122:     }
1.136     brouard  14123: #ifdef GSL
                   14124:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  14125: #else
1.126     brouard  14126:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  14127: #endif
1.126     brouard  14128:     /*  for (i=1;i<=nlstate;i++)
                   14129:        for(j=1;j<=nlstate+ndeath;j++)
                   14130:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   14131:     */
                   14132:     fprintf(ficrespow,"\n");
1.136     brouard  14133: #ifdef GSL
                   14134:     /* gsl starts here */ 
                   14135:     T = gsl_multimin_fminimizer_nmsimplex;
                   14136:     gsl_multimin_fminimizer *sfm = NULL;
                   14137:     gsl_vector *ss, *x;
                   14138:     gsl_multimin_function minex_func;
                   14139: 
                   14140:     /* Initial vertex size vector */
                   14141:     ss = gsl_vector_alloc (NDIM);
                   14142:     
                   14143:     if (ss == NULL){
                   14144:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   14145:     }
                   14146:     /* Set all step sizes to 1 */
                   14147:     gsl_vector_set_all (ss, 0.001);
                   14148: 
                   14149:     /* Starting point */
1.126     brouard  14150:     
1.136     brouard  14151:     x = gsl_vector_alloc (NDIM);
                   14152:     
                   14153:     if (x == NULL){
                   14154:       gsl_vector_free(ss);
                   14155:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   14156:     }
                   14157:   
                   14158:     /* Initialize method and iterate */
                   14159:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  14160:     /*     gsl_vector_set(x, 0, 0.0268); */
                   14161:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  14162:     gsl_vector_set(x, 0, p[1]);
                   14163:     gsl_vector_set(x, 1, p[2]);
                   14164: 
                   14165:     minex_func.f = &gompertz_f;
                   14166:     minex_func.n = NDIM;
                   14167:     minex_func.params = (void *)&p; /* ??? */
                   14168:     
                   14169:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   14170:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   14171:     
                   14172:     printf("Iterations beginning .....\n\n");
                   14173:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   14174: 
                   14175:     iteri=0;
                   14176:     while (rval == GSL_CONTINUE){
                   14177:       iteri++;
                   14178:       status = gsl_multimin_fminimizer_iterate(sfm);
                   14179:       
                   14180:       if (status) printf("error: %s\n", gsl_strerror (status));
                   14181:       fflush(0);
                   14182:       
                   14183:       if (status) 
                   14184:         break;
                   14185:       
                   14186:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   14187:       ssval = gsl_multimin_fminimizer_size (sfm);
                   14188:       
                   14189:       if (rval == GSL_SUCCESS)
                   14190:         printf ("converged to a local maximum at\n");
                   14191:       
                   14192:       printf("%5d ", iteri);
                   14193:       for (it = 0; it < NDIM; it++){
                   14194:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   14195:       }
                   14196:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   14197:     }
                   14198:     
                   14199:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   14200:     
                   14201:     gsl_vector_free(x); /* initial values */
                   14202:     gsl_vector_free(ss); /* inital step size */
                   14203:     for (it=0; it<NDIM; it++){
                   14204:       p[it+1]=gsl_vector_get(sfm->x,it);
                   14205:       fprintf(ficrespow," %.12lf", p[it]);
                   14206:     }
                   14207:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   14208: #endif
                   14209: #ifdef POWELL
                   14210:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   14211: #endif  
1.126     brouard  14212:     fclose(ficrespow);
                   14213:     
1.203     brouard  14214:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  14215: 
                   14216:     for(i=1; i <=NDIM; i++)
                   14217:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  14218:                                matcov[i][j]=matcov[j][i];
1.126     brouard  14219:     
                   14220:     printf("\nCovariance matrix\n ");
1.203     brouard  14221:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  14222:     for(i=1; i <=NDIM; i++) {
                   14223:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  14224:                                printf("%f ",matcov[i][j]);
                   14225:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  14226:       }
1.203     brouard  14227:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  14228:     }
                   14229:     
                   14230:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  14231:     for (i=1;i<=NDIM;i++) {
1.126     brouard  14232:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  14233:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   14234:     }
1.302     brouard  14235:     lsurv=vector(agegomp,AGESUP);
                   14236:     lpop=vector(agegomp,AGESUP);
                   14237:     tpop=vector(agegomp,AGESUP);
1.126     brouard  14238:     lsurv[agegomp]=100000;
                   14239:     
                   14240:     for (k=agegomp;k<=AGESUP;k++) {
                   14241:       agemortsup=k;
                   14242:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   14243:     }
                   14244:     
                   14245:     for (k=agegomp;k<agemortsup;k++)
                   14246:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   14247:     
                   14248:     for (k=agegomp;k<agemortsup;k++){
                   14249:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   14250:       sumlpop=sumlpop+lpop[k];
                   14251:     }
                   14252:     
                   14253:     tpop[agegomp]=sumlpop;
                   14254:     for (k=agegomp;k<(agemortsup-3);k++){
                   14255:       /*  tpop[k+1]=2;*/
                   14256:       tpop[k+1]=tpop[k]-lpop[k];
                   14257:     }
                   14258:     
                   14259:     
                   14260:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   14261:     for (k=agegomp;k<(agemortsup-2);k++) 
                   14262:       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]);
                   14263:     
                   14264:     
                   14265:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  14266:                ageminpar=50;
                   14267:                agemaxpar=100;
1.194     brouard  14268:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   14269:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   14270: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14271: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   14272:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   14273: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14274: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  14275:     }else{
                   14276:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   14277:                        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  14278:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  14279:                }
1.201     brouard  14280:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  14281:                     stepm, weightopt,\
                   14282:                     model,imx,p,matcov,agemortsup);
                   14283:     
1.302     brouard  14284:     free_vector(lsurv,agegomp,AGESUP);
                   14285:     free_vector(lpop,agegomp,AGESUP);
                   14286:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  14287:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  14288:     free_ivector(dcwave,firstobs,lastobs);
                   14289:     free_vector(agecens,firstobs,lastobs);
                   14290:     free_vector(ageexmed,firstobs,lastobs);
                   14291:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  14292: #ifdef GSL
1.136     brouard  14293: #endif
1.186     brouard  14294:   } /* Endof if mle==-3 mortality only */
1.205     brouard  14295:   /* Standard  */
                   14296:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   14297:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   14298:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  14299:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  14300:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   14301:     for (k=1; k<=npar;k++)
                   14302:       printf(" %d %8.5f",k,p[k]);
                   14303:     printf("\n");
1.205     brouard  14304:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   14305:       /* mlikeli uses func not funcone */
1.247     brouard  14306:       /* for(i=1;i<nlstate;i++){ */
                   14307:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   14308:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   14309:       /* } */
1.205     brouard  14310:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   14311:     }
                   14312:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   14313:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   14314:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   14315:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   14316:     }
                   14317:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  14318:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   14319:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335     brouard  14320:           /* exit(0); */
1.126     brouard  14321:     for (k=1; k<=npar;k++)
                   14322:       printf(" %d %8.5f",k,p[k]);
                   14323:     printf("\n");
                   14324:     
                   14325:     /*--------- results files --------------*/
1.283     brouard  14326:     /* 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  14327:     
                   14328:     
                   14329:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  14330:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  14331:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  14332: 
                   14333:     printf("#model=  1      +     age ");
                   14334:     fprintf(ficres,"#model=  1      +     age ");
                   14335:     fprintf(ficlog,"#model=  1      +     age ");
                   14336:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   14337: </ul>", model);
                   14338: 
                   14339:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   14340:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   14341:     if(nagesqr==1){
                   14342:       printf("  + age*age  ");
                   14343:       fprintf(ficres,"  + age*age  ");
                   14344:       fprintf(ficlog,"  + age*age  ");
                   14345:       fprintf(fichtm, "<th>+ age*age</th>");
                   14346:     }
                   14347:     for(j=1;j <=ncovmodel-2;j++){
                   14348:       if(Typevar[j]==0) {
                   14349:        printf("  +      V%d  ",Tvar[j]);
                   14350:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   14351:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   14352:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   14353:       }else if(Typevar[j]==1) {
                   14354:        printf("  +    V%d*age ",Tvar[j]);
                   14355:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   14356:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   14357:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   14358:       }else if(Typevar[j]==2) {
                   14359:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14360:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14361:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14362:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  14363:       }else if(Typevar[j]==3) { /* TO VERIFY */
                   14364:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14365:        fprintf(ficres,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14366:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14367:        fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  14368:       }
                   14369:     }
                   14370:     printf("\n");
                   14371:     fprintf(ficres,"\n");
                   14372:     fprintf(ficlog,"\n");
                   14373:     fprintf(fichtm, "</tr>");
                   14374:     fprintf(fichtm, "\n");
                   14375:     
                   14376:     
1.126     brouard  14377:     for(i=1,jk=1; i <=nlstate; i++){
                   14378:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  14379:        if (k != i) {
1.319     brouard  14380:          fprintf(fichtm, "<tr>");
1.225     brouard  14381:          printf("%d%d ",i,k);
                   14382:          fprintf(ficlog,"%d%d ",i,k);
                   14383:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  14384:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  14385:          for(j=1; j <=ncovmodel; j++){
                   14386:            printf("%12.7f ",p[jk]);
                   14387:            fprintf(ficlog,"%12.7f ",p[jk]);
                   14388:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  14389:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  14390:            jk++; 
                   14391:          }
                   14392:          printf("\n");
                   14393:          fprintf(ficlog,"\n");
                   14394:          fprintf(ficres,"\n");
1.319     brouard  14395:          fprintf(fichtm, "</tr>\n");
1.225     brouard  14396:        }
1.126     brouard  14397:       }
                   14398:     }
1.319     brouard  14399:     /* fprintf(fichtm,"</tr>\n"); */
                   14400:     fprintf(fichtm,"</table>\n");
                   14401:     fprintf(fichtm, "\n");
                   14402: 
1.203     brouard  14403:     if(mle != 0){
                   14404:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  14405:       ftolhess=ftol; /* Usually correct */
1.203     brouard  14406:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   14407:       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");
                   14408:       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  14409:       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  14410:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   14411:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   14412:       if(nagesqr==1){
                   14413:        printf("  + age*age  ");
                   14414:        fprintf(ficres,"  + age*age  ");
                   14415:        fprintf(ficlog,"  + age*age  ");
                   14416:        fprintf(fichtm, "<th>+ age*age</th>");
                   14417:       }
                   14418:       for(j=1;j <=ncovmodel-2;j++){
                   14419:        if(Typevar[j]==0) {
                   14420:          printf("  +      V%d  ",Tvar[j]);
                   14421:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   14422:        }else if(Typevar[j]==1) {
                   14423:          printf("  +    V%d*age ",Tvar[j]);
                   14424:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   14425:        }else if(Typevar[j]==2) {
                   14426:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  14427:        }else if(Typevar[j]==3) { /* TO VERIFY */
                   14428:          fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  14429:        }
                   14430:       }
                   14431:       fprintf(fichtm, "</tr>\n");
                   14432:  
1.203     brouard  14433:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  14434:        for(k=1; k <=(nlstate+ndeath); k++){
                   14435:          if (k != i) {
1.319     brouard  14436:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  14437:            printf("%d%d ",i,k);
                   14438:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  14439:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  14440:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  14441:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  14442:              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]));
                   14443:              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  14444:              if(fabs(wald) > 1.96){
1.321     brouard  14445:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  14446:              }else{
                   14447:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   14448:              }
1.324     brouard  14449:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  14450:              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  14451:              jk++; 
                   14452:            }
                   14453:            printf("\n");
                   14454:            fprintf(ficlog,"\n");
1.319     brouard  14455:            fprintf(fichtm, "</tr>\n");
1.225     brouard  14456:          }
                   14457:        }
1.193     brouard  14458:       }
1.203     brouard  14459:     } /* end of hesscov and Wald tests */
1.319     brouard  14460:     fprintf(fichtm,"</table>\n");
1.225     brouard  14461:     
1.203     brouard  14462:     /*  */
1.126     brouard  14463:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   14464:     printf("# Scales (for hessian or gradient estimation)\n");
                   14465:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   14466:     for(i=1,jk=1; i <=nlstate; i++){
                   14467:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  14468:        if (j!=i) {
                   14469:          fprintf(ficres,"%1d%1d",i,j);
                   14470:          printf("%1d%1d",i,j);
                   14471:          fprintf(ficlog,"%1d%1d",i,j);
                   14472:          for(k=1; k<=ncovmodel;k++){
                   14473:            printf(" %.5e",delti[jk]);
                   14474:            fprintf(ficlog," %.5e",delti[jk]);
                   14475:            fprintf(ficres," %.5e",delti[jk]);
                   14476:            jk++;
                   14477:          }
                   14478:          printf("\n");
                   14479:          fprintf(ficlog,"\n");
                   14480:          fprintf(ficres,"\n");
                   14481:        }
1.126     brouard  14482:       }
                   14483:     }
                   14484:     
                   14485:     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  14486:     if(mle >= 1) /* Too big for the screen */
1.126     brouard  14487:       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");
                   14488:     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");
                   14489:     /* # 121 Var(a12)\n\ */
                   14490:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   14491:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   14492:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   14493:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   14494:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   14495:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   14496:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   14497:     
                   14498:     
                   14499:     /* Just to have a covariance matrix which will be more understandable
                   14500:        even is we still don't want to manage dictionary of variables
                   14501:     */
                   14502:     for(itimes=1;itimes<=2;itimes++){
                   14503:       jj=0;
                   14504:       for(i=1; i <=nlstate; i++){
1.225     brouard  14505:        for(j=1; j <=nlstate+ndeath; j++){
                   14506:          if(j==i) continue;
                   14507:          for(k=1; k<=ncovmodel;k++){
                   14508:            jj++;
                   14509:            ca[0]= k+'a'-1;ca[1]='\0';
                   14510:            if(itimes==1){
                   14511:              if(mle>=1)
                   14512:                printf("#%1d%1d%d",i,j,k);
                   14513:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   14514:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   14515:            }else{
                   14516:              if(mle>=1)
                   14517:                printf("%1d%1d%d",i,j,k);
                   14518:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   14519:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   14520:            }
                   14521:            ll=0;
                   14522:            for(li=1;li <=nlstate; li++){
                   14523:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   14524:                if(lj==li) continue;
                   14525:                for(lk=1;lk<=ncovmodel;lk++){
                   14526:                  ll++;
                   14527:                  if(ll<=jj){
                   14528:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   14529:                    if(ll<jj){
                   14530:                      if(itimes==1){
                   14531:                        if(mle>=1)
                   14532:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14533:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14534:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14535:                      }else{
                   14536:                        if(mle>=1)
                   14537:                          printf(" %.5e",matcov[jj][ll]); 
                   14538:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   14539:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   14540:                      }
                   14541:                    }else{
                   14542:                      if(itimes==1){
                   14543:                        if(mle>=1)
                   14544:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   14545:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   14546:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   14547:                      }else{
                   14548:                        if(mle>=1)
                   14549:                          printf(" %.7e",matcov[jj][ll]); 
                   14550:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   14551:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   14552:                      }
                   14553:                    }
                   14554:                  }
                   14555:                } /* end lk */
                   14556:              } /* end lj */
                   14557:            } /* end li */
                   14558:            if(mle>=1)
                   14559:              printf("\n");
                   14560:            fprintf(ficlog,"\n");
                   14561:            fprintf(ficres,"\n");
                   14562:            numlinepar++;
                   14563:          } /* end k*/
                   14564:        } /*end j */
1.126     brouard  14565:       } /* end i */
                   14566:     } /* end itimes */
                   14567:     
                   14568:     fflush(ficlog);
                   14569:     fflush(ficres);
1.225     brouard  14570:     while(fgets(line, MAXLINE, ficpar)) {
                   14571:       /* If line starts with a # it is a comment */
                   14572:       if (line[0] == '#') {
                   14573:        numlinepar++;
                   14574:        fputs(line,stdout);
                   14575:        fputs(line,ficparo);
                   14576:        fputs(line,ficlog);
1.299     brouard  14577:        fputs(line,ficres);
1.225     brouard  14578:        continue;
                   14579:       }else
                   14580:        break;
                   14581:     }
                   14582:     
1.209     brouard  14583:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   14584:     /*   ungetc(c,ficpar); */
                   14585:     /*   fgets(line, MAXLINE, ficpar); */
                   14586:     /*   fputs(line,stdout); */
                   14587:     /*   fputs(line,ficparo); */
                   14588:     /* } */
                   14589:     /* ungetc(c,ficpar); */
1.126     brouard  14590:     
                   14591:     estepm=0;
1.209     brouard  14592:     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  14593:       
                   14594:       if (num_filled != 6) {
                   14595:        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);
                   14596:        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);
                   14597:        goto end;
                   14598:       }
                   14599:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   14600:     }
                   14601:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   14602:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   14603:     
1.209     brouard  14604:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  14605:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   14606:     if (fage <= 2) {
                   14607:       bage = ageminpar;
                   14608:       fage = agemaxpar;
                   14609:     }
                   14610:     
                   14611:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  14612:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   14613:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  14614:                
1.186     brouard  14615:     /* Other stuffs, more or less useful */    
1.254     brouard  14616:     while(fgets(line, MAXLINE, ficpar)) {
                   14617:       /* If line starts with a # it is a comment */
                   14618:       if (line[0] == '#') {
                   14619:        numlinepar++;
                   14620:        fputs(line,stdout);
                   14621:        fputs(line,ficparo);
                   14622:        fputs(line,ficlog);
1.299     brouard  14623:        fputs(line,ficres);
1.254     brouard  14624:        continue;
                   14625:       }else
                   14626:        break;
                   14627:     }
                   14628: 
                   14629:     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){
                   14630:       
                   14631:       if (num_filled != 7) {
                   14632:        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);
                   14633:        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);
                   14634:        goto end;
                   14635:       }
                   14636:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   14637:       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);
                   14638:       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);
                   14639:       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  14640:     }
1.254     brouard  14641: 
                   14642:     while(fgets(line, MAXLINE, ficpar)) {
                   14643:       /* If line starts with a # it is a comment */
                   14644:       if (line[0] == '#') {
                   14645:        numlinepar++;
                   14646:        fputs(line,stdout);
                   14647:        fputs(line,ficparo);
                   14648:        fputs(line,ficlog);
1.299     brouard  14649:        fputs(line,ficres);
1.254     brouard  14650:        continue;
                   14651:       }else
                   14652:        break;
1.126     brouard  14653:     }
                   14654:     
                   14655:     
                   14656:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   14657:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   14658:     
1.254     brouard  14659:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   14660:       if (num_filled != 1) {
                   14661:        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);
                   14662:        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);
                   14663:        goto end;
                   14664:       }
                   14665:       printf("pop_based=%d\n",popbased);
                   14666:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   14667:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   14668:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   14669:     }
                   14670:      
1.258     brouard  14671:     /* Results */
1.332     brouard  14672:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
                   14673:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   14674:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  14675:     endishere=0;
1.258     brouard  14676:     nresult=0;
1.308     brouard  14677:     parameterline=0;
1.258     brouard  14678:     do{
                   14679:       if(!fgets(line, MAXLINE, ficpar)){
                   14680:        endishere=1;
1.308     brouard  14681:        parameterline=15;
1.258     brouard  14682:       }else if (line[0] == '#') {
                   14683:        /* If line starts with a # it is a comment */
1.254     brouard  14684:        numlinepar++;
                   14685:        fputs(line,stdout);
                   14686:        fputs(line,ficparo);
                   14687:        fputs(line,ficlog);
1.299     brouard  14688:        fputs(line,ficres);
1.254     brouard  14689:        continue;
1.258     brouard  14690:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   14691:        parameterline=11;
1.296     brouard  14692:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  14693:        parameterline=12;
1.307     brouard  14694:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  14695:        parameterline=13;
1.307     brouard  14696:       }
1.258     brouard  14697:       else{
                   14698:        parameterline=14;
1.254     brouard  14699:       }
1.308     brouard  14700:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  14701:       case 11:
1.296     brouard  14702:        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)){
                   14703:                  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  14704:          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);
                   14705:          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);
                   14706:          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);
                   14707:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  14708:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   14709:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  14710:           prvforecast = 1;
                   14711:        } 
                   14712:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  14713:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   14714:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   14715:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  14716:           prvforecast = 2;
                   14717:        }
                   14718:        else {
                   14719:          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);
                   14720:          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);
                   14721:          goto end;
1.258     brouard  14722:        }
1.254     brouard  14723:        break;
1.258     brouard  14724:       case 12:
1.296     brouard  14725:        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)){
                   14726:           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);
                   14727:          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);
                   14728:          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);
                   14729:          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);
                   14730:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  14731:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   14732:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  14733:           prvbackcast = 1;
                   14734:        } 
                   14735:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  14736:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   14737:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   14738:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  14739:           prvbackcast = 2;
                   14740:        }
                   14741:        else {
                   14742:          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);
                   14743:          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);
                   14744:          goto end;
1.258     brouard  14745:        }
1.230     brouard  14746:        break;
1.258     brouard  14747:       case 13:
1.332     brouard  14748:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  14749:        nresult++; /* Sum of resultlines */
1.342     brouard  14750:        /* printf("Result %d: result:%s\n",nresult, resultlineori); */
1.332     brouard  14751:        /* removefirstspace(&resultlineori); */
                   14752:        
                   14753:        if(strstr(resultlineori,"v") !=0){
                   14754:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   14755:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   14756:          return 1;
                   14757:        }
                   14758:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
1.342     brouard  14759:        /* printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori); */
1.318     brouard  14760:        if(nresult > MAXRESULTLINESPONE-1){
                   14761:          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);
                   14762:          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  14763:          goto end;
                   14764:        }
1.332     brouard  14765:        
1.310     brouard  14766:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  14767:          fprintf(ficparo,"result: %s\n",resultline);
                   14768:          fprintf(ficres,"result: %s\n",resultline);
                   14769:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  14770:        } else
                   14771:          goto end;
1.307     brouard  14772:        break;
                   14773:       case 14:
                   14774:        printf("Error: Unknown command '%s'\n",line);
                   14775:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  14776:        if(line[0] == ' ' || line[0] == '\n'){
                   14777:          printf("It should not be an empty line '%s'\n",line);
                   14778:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   14779:        }         
1.307     brouard  14780:        if(ncovmodel >=2 && nresult==0 ){
                   14781:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   14782:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  14783:        }
1.307     brouard  14784:        /* goto end; */
                   14785:        break;
1.308     brouard  14786:       case 15:
                   14787:        printf("End of resultlines.\n");
                   14788:        fprintf(ficlog,"End of resultlines.\n");
                   14789:        break;
                   14790:       default: /* parameterline =0 */
1.307     brouard  14791:        nresult=1;
                   14792:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  14793:       } /* End switch parameterline */
                   14794:     }while(endishere==0); /* End do */
1.126     brouard  14795:     
1.230     brouard  14796:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  14797:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  14798:     
                   14799:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  14800:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  14801:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14802: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14803: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  14804:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14805: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14806: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  14807:     }else{
1.270     brouard  14808:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  14809:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   14810:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   14811:       if(prvforecast==1){
                   14812:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   14813:         jprojd=jproj1;
                   14814:         mprojd=mproj1;
                   14815:         anprojd=anproj1;
                   14816:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   14817:         jprojf=jproj2;
                   14818:         mprojf=mproj2;
                   14819:         anprojf=anproj2;
                   14820:       } else if(prvforecast == 2){
                   14821:         dateprojd=dateintmean;
                   14822:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   14823:         dateprojf=dateintmean+yrfproj;
                   14824:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   14825:       }
                   14826:       if(prvbackcast==1){
                   14827:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   14828:         jbackd=jback1;
                   14829:         mbackd=mback1;
                   14830:         anbackd=anback1;
                   14831:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   14832:         jbackf=jback2;
                   14833:         mbackf=mback2;
                   14834:         anbackf=anback2;
                   14835:       } else if(prvbackcast == 2){
                   14836:         datebackd=dateintmean;
                   14837:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   14838:         datebackf=dateintmean-yrbproj;
                   14839:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   14840:       }
                   14841:       
1.350     brouard  14842:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);/* HERE valgrind Tvard*/
1.220     brouard  14843:     }
                   14844:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  14845:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   14846:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  14847:                
1.225     brouard  14848:     /*------------ free_vector  -------------*/
                   14849:     /*  chdir(path); */
1.220     brouard  14850:                
1.215     brouard  14851:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   14852:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   14853:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   14854:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  14855:     free_lvector(num,firstobs,lastobs);
                   14856:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  14857:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   14858:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   14859:     fclose(ficparo);
                   14860:     fclose(ficres);
1.220     brouard  14861:                
                   14862:                
1.186     brouard  14863:     /* Other results (useful)*/
1.220     brouard  14864:                
                   14865:                
1.126     brouard  14866:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  14867:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   14868:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  14869:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  14870:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  14871:     fclose(ficrespl);
                   14872: 
                   14873:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  14874:     /*#include "hpijx.h"*/
1.332     brouard  14875:     /** 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?*/
                   14876:     /* calls hpxij with combination k */
1.180     brouard  14877:     hPijx(p, bage, fage);
1.145     brouard  14878:     fclose(ficrespij);
1.227     brouard  14879:     
1.220     brouard  14880:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  14881:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  14882:     k=1;
1.126     brouard  14883:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  14884:     
1.269     brouard  14885:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   14886:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14887:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  14888:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  14889:        for(k=1;k<=ncovcombmax;k++)
                   14890:          probs[i][j][k]=0.;
1.269     brouard  14891:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   14892:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  14893:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  14894:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14895:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  14896:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  14897:          for(k=1;k<=ncovcombmax;k++)
                   14898:            mobaverages[i][j][k]=0.;
1.219     brouard  14899:       mobaverage=mobaverages;
                   14900:       if (mobilav!=0) {
1.235     brouard  14901:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  14902:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  14903:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   14904:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   14905:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   14906:        }
1.269     brouard  14907:       } else if (mobilavproj !=0) {
1.235     brouard  14908:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  14909:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  14910:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   14911:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14912:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14913:        }
1.269     brouard  14914:       }else{
                   14915:        printf("Internal error moving average\n");
                   14916:        fflush(stdout);
                   14917:        exit(1);
1.219     brouard  14918:       }
                   14919:     }/* end if moving average */
1.227     brouard  14920:     
1.126     brouard  14921:     /*---------- Forecasting ------------------*/
1.296     brouard  14922:     if(prevfcast==1){ 
                   14923:       /*   /\*    if(stepm ==1){*\/ */
                   14924:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14925:       /*This done previously after freqsummary.*/
                   14926:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   14927:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   14928:       
                   14929:       /* } else if (prvforecast==2){ */
                   14930:       /*   /\*    if(stepm ==1){*\/ */
                   14931:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14932:       /* } */
                   14933:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   14934:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  14935:     }
1.269     brouard  14936: 
1.296     brouard  14937:     /* Prevbcasting */
                   14938:     if(prevbcast==1){
1.219     brouard  14939:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14940:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14941:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   14942: 
                   14943:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   14944: 
                   14945:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  14946: 
1.219     brouard  14947:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   14948:       fclose(ficresplb);
                   14949: 
1.222     brouard  14950:       hBijx(p, bage, fage, mobaverage);
                   14951:       fclose(ficrespijb);
1.219     brouard  14952: 
1.296     brouard  14953:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   14954:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   14955:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   14956:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   14957:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   14958:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   14959: 
                   14960:       
1.269     brouard  14961:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14962: 
                   14963:       
1.269     brouard  14964:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  14965:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14966:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14967:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  14968:     }    /* end  Prevbcasting */
1.268     brouard  14969:  
1.186     brouard  14970:  
                   14971:     /* ------ Other prevalence ratios------------ */
1.126     brouard  14972: 
1.215     brouard  14973:     free_ivector(wav,1,imx);
                   14974:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   14975:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   14976:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  14977:                
                   14978:                
1.127     brouard  14979:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  14980:                
1.201     brouard  14981:     strcpy(filerese,"E_");
                   14982:     strcat(filerese,fileresu);
1.126     brouard  14983:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   14984:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14985:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14986:     }
1.208     brouard  14987:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   14988:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  14989: 
                   14990:     pstamp(ficreseij);
1.219     brouard  14991:                
1.351     brouard  14992:     /* i1=pow(2,cptcoveff); /\* Number of combination of dummy covariates *\/ */
                   14993:     /* if (cptcovn < 1){i1=1;} */
1.235     brouard  14994:     
1.351     brouard  14995:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   14996:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   14997:       /* if(i1 != 1 && TKresult[nres]!= k) */
                   14998:       /*       continue; */
1.219     brouard  14999:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  15000:       printf("\n#****** ");
1.351     brouard  15001:       for(j=1;j<=cptcovs;j++){
                   15002:       /* for(j=1;j<=cptcoveff;j++) { */
                   15003:        /* fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15004:        fprintf(ficreseij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   15005:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   15006:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.235     brouard  15007:       }
                   15008:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.337     brouard  15009:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   15010:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  15011:       }
                   15012:       fprintf(ficreseij,"******\n");
1.235     brouard  15013:       printf("******\n");
1.219     brouard  15014:       
                   15015:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15016:       oldm=oldms;savm=savms;
1.330     brouard  15017:       /* 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  15018:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  15019:       
1.219     brouard  15020:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  15021:     }
                   15022:     fclose(ficreseij);
1.208     brouard  15023:     printf("done evsij\n");fflush(stdout);
                   15024:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  15025: 
1.218     brouard  15026:                
1.227     brouard  15027:     /*---------- State-specific expectancies and variances ------------*/
1.336     brouard  15028:     /* Should be moved in a function */                
1.201     brouard  15029:     strcpy(filerest,"T_");
                   15030:     strcat(filerest,fileresu);
1.127     brouard  15031:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   15032:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   15033:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   15034:     }
1.208     brouard  15035:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   15036:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  15037:     strcpy(fileresstde,"STDE_");
                   15038:     strcat(fileresstde,fileresu);
1.126     brouard  15039:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  15040:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   15041:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  15042:     }
1.227     brouard  15043:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   15044:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  15045: 
1.201     brouard  15046:     strcpy(filerescve,"CVE_");
                   15047:     strcat(filerescve,fileresu);
1.126     brouard  15048:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  15049:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   15050:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  15051:     }
1.227     brouard  15052:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   15053:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  15054: 
1.201     brouard  15055:     strcpy(fileresv,"V_");
                   15056:     strcat(fileresv,fileresu);
1.126     brouard  15057:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   15058:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   15059:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   15060:     }
1.227     brouard  15061:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   15062:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  15063: 
1.235     brouard  15064:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   15065:     if (cptcovn < 1){i1=1;}
                   15066:     
1.334     brouard  15067:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   15068:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   15069:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   15070:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   15071:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   15072:       /* */
                   15073:       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  15074:        continue;
1.350     brouard  15075:       printf("\n# model %s \n#****** Result for:", model);  /* HERE model is empty */
1.321     brouard  15076:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   15077:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.334     brouard  15078:       /* It might not be a good idea to mix dummies and quantitative */
                   15079:       /* 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 *\/ */
                   15080:       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 */
                   15081:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   15082:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   15083:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   15084:         * (V5 is quanti) V4 and V3 are dummies
                   15085:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   15086:         *                                                              l=1 l=2
                   15087:         *                                                           k=1  1   1   0   0
                   15088:         *                                                           k=2  2   1   1   0
                   15089:         *                                                           k=3 [1] [2]  0   1
                   15090:         *                                                           k=4  2   2   1   1
                   15091:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   15092:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   15093:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   15094:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   15095:         */
                   15096:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   15097:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   15098: /* We give up with the combinations!! */
1.342     brouard  15099:        /* if(debugILK) */
                   15100:        /*   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  15101: 
                   15102:        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  15103:          /* 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] */
                   15104:          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  */
                   15105:          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  */
                   15106:          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  15107:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   15108:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   15109:          }else{
                   15110:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   15111:          }
                   15112:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15113:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15114:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   15115:          /* For each selected (single) quantitative value */
1.337     brouard  15116:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   15117:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   15118:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
1.334     brouard  15119:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   15120:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   15121:          }else{
                   15122:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   15123:          }
                   15124:        }else{
                   15125:          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 */
                   15126:          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 */
                   15127:          exit(1);
                   15128:        }
1.335     brouard  15129:       } /* End loop for each variable in the resultline */
1.334     brouard  15130:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   15131:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   15132:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   15133:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   15134:       /* }      */
1.208     brouard  15135:       fprintf(ficrest,"******\n");
1.227     brouard  15136:       fprintf(ficlog,"******\n");
                   15137:       printf("******\n");
1.208     brouard  15138:       
                   15139:       fprintf(ficresstdeij,"\n#****** ");
                   15140:       fprintf(ficrescveij,"\n#****** ");
1.337     brouard  15141:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
                   15142:       /* But it won't be sorted and depends on how the resultline is ordered */
1.225     brouard  15143:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  15144:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   15145:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15146:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15147:       }
                   15148:       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  15149:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   15150:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  15151:       }        
1.208     brouard  15152:       fprintf(ficresstdeij,"******\n");
                   15153:       fprintf(ficrescveij,"******\n");
                   15154:       
                   15155:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  15156:       /* pstamp(ficresvij); */
1.225     brouard  15157:       for(j=1;j<=cptcoveff;j++) 
1.335     brouard  15158:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   15159:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  15160:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  15161:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
1.337     brouard  15162:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  15163:       }        
1.208     brouard  15164:       fprintf(ficresvij,"******\n");
                   15165:       
                   15166:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15167:       oldm=oldms;savm=savms;
1.235     brouard  15168:       printf(" cvevsij ");
                   15169:       fprintf(ficlog, " cvevsij ");
                   15170:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  15171:       printf(" end cvevsij \n ");
                   15172:       fprintf(ficlog, " end cvevsij \n ");
                   15173:       
                   15174:       /*
                   15175:        */
                   15176:       /* goto endfree; */
                   15177:       
                   15178:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15179:       pstamp(ficrest);
                   15180:       
1.269     brouard  15181:       epj=vector(1,nlstate+1);
1.208     brouard  15182:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  15183:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   15184:        cptcod= 0; /* To be deleted */
                   15185:        printf("varevsij vpopbased=%d \n",vpopbased);
                   15186:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  15187:        varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart, nres); /* cptcod not initialized Intel */
1.227     brouard  15188:        fprintf(ficrest,"# Total life expectancy with std error and decomposition into time to be expected in each health state\n#  (weighted average of eij where weights are ");
                   15189:        if(vpopbased==1)
                   15190:          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);
                   15191:        else
1.288     brouard  15192:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.335     brouard  15193:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  15194:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   15195:        fprintf(ficrest,"\n");
                   15196:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  15197:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   15198:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  15199:        for(age=bage; age <=fage ;age++){
1.235     brouard  15200:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  15201:          if (vpopbased==1) {
                   15202:            if(mobilav ==0){
                   15203:              for(i=1; i<=nlstate;i++)
                   15204:                prlim[i][i]=probs[(int)age][i][k];
                   15205:            }else{ /* mobilav */ 
                   15206:              for(i=1; i<=nlstate;i++)
                   15207:                prlim[i][i]=mobaverage[(int)age][i][k];
                   15208:            }
                   15209:          }
1.219     brouard  15210:          
1.227     brouard  15211:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   15212:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   15213:          /* printf(" age %4.0f ",age); */
                   15214:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   15215:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   15216:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   15217:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   15218:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   15219:            }
                   15220:            epj[nlstate+1] +=epj[j];
                   15221:          }
                   15222:          /* printf(" age %4.0f \n",age); */
1.219     brouard  15223:          
1.227     brouard  15224:          for(i=1, vepp=0.;i <=nlstate;i++)
                   15225:            for(j=1;j <=nlstate;j++)
                   15226:              vepp += vareij[i][j][(int)age];
                   15227:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   15228:          for(j=1;j <=nlstate;j++){
                   15229:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   15230:          }
                   15231:          fprintf(ficrest,"\n");
                   15232:        }
1.208     brouard  15233:       } /* End vpopbased */
1.269     brouard  15234:       free_vector(epj,1,nlstate+1);
1.208     brouard  15235:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   15236:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  15237:       printf("done selection\n");fflush(stdout);
                   15238:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  15239:       
1.335     brouard  15240:     } /* End k selection or end covariate selection for nres */
1.227     brouard  15241: 
                   15242:     printf("done State-specific expectancies\n");fflush(stdout);
                   15243:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   15244: 
1.335     brouard  15245:     /* variance-covariance of forward period prevalence */
1.269     brouard  15246:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  15247: 
1.227     brouard  15248:     
1.290     brouard  15249:     free_vector(weight,firstobs,lastobs);
1.351     brouard  15250:     free_imatrix(Tvardk,0,NCOVMAX,1,2);
1.227     brouard  15251:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  15252:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   15253:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   15254:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   15255:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  15256:     free_ivector(tab,1,NCOVMAX);
                   15257:     fclose(ficresstdeij);
                   15258:     fclose(ficrescveij);
                   15259:     fclose(ficresvij);
                   15260:     fclose(ficrest);
                   15261:     fclose(ficpar);
                   15262:     
                   15263:     
1.126     brouard  15264:     /*---------- End : free ----------------*/
1.219     brouard  15265:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  15266:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   15267:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  15268:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   15269:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  15270:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  15271:   /* endfree:*/
                   15272:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   15273:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   15274:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.341     brouard  15275:   /* if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs); */
                   15276:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);
1.290     brouard  15277:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   15278:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   15279:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  15280:   free_matrix(matcov,1,npar,1,npar);
                   15281:   free_matrix(hess,1,npar,1,npar);
                   15282:   /*free_vector(delti,1,npar);*/
                   15283:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   15284:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  15285:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  15286:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   15287:   
                   15288:   free_ivector(ncodemax,1,NCOVMAX);
                   15289:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   15290:   free_ivector(Dummy,-1,NCOVMAX);
                   15291:   free_ivector(Fixed,-1,NCOVMAX);
1.349     brouard  15292:   free_ivector(DummyV,-1,NCOVMAX);
                   15293:   free_ivector(FixedV,-1,NCOVMAX);
1.227     brouard  15294:   free_ivector(Typevar,-1,NCOVMAX);
                   15295:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  15296:   free_ivector(TvarsQ,1,NCOVMAX);
                   15297:   free_ivector(TvarsQind,1,NCOVMAX);
                   15298:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  15299:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  15300:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  15301:   free_ivector(TvarFD,1,NCOVMAX);
                   15302:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  15303:   free_ivector(TvarF,1,NCOVMAX);
                   15304:   free_ivector(TvarFind,1,NCOVMAX);
                   15305:   free_ivector(TvarV,1,NCOVMAX);
                   15306:   free_ivector(TvarVind,1,NCOVMAX);
                   15307:   free_ivector(TvarA,1,NCOVMAX);
                   15308:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  15309:   free_ivector(TvarFQ,1,NCOVMAX);
                   15310:   free_ivector(TvarFQind,1,NCOVMAX);
                   15311:   free_ivector(TvarVD,1,NCOVMAX);
                   15312:   free_ivector(TvarVDind,1,NCOVMAX);
                   15313:   free_ivector(TvarVQ,1,NCOVMAX);
                   15314:   free_ivector(TvarVQind,1,NCOVMAX);
1.349     brouard  15315:   free_ivector(TvarAVVA,1,NCOVMAX);
                   15316:   free_ivector(TvarAVVAind,1,NCOVMAX);
                   15317:   free_ivector(TvarVVA,1,NCOVMAX);
                   15318:   free_ivector(TvarVVAind,1,NCOVMAX);
1.339     brouard  15319:   free_ivector(TvarVV,1,NCOVMAX);
                   15320:   free_ivector(TvarVVind,1,NCOVMAX);
                   15321:   
1.230     brouard  15322:   free_ivector(Tvarsel,1,NCOVMAX);
                   15323:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  15324:   free_ivector(Tposprod,1,NCOVMAX);
                   15325:   free_ivector(Tprod,1,NCOVMAX);
                   15326:   free_ivector(Tvaraff,1,NCOVMAX);
1.338     brouard  15327:   free_ivector(invalidvarcomb,0,ncovcombmax);
1.227     brouard  15328:   free_ivector(Tage,1,NCOVMAX);
                   15329:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  15330:   free_ivector(TmodelInvind,1,NCOVMAX);
                   15331:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  15332: 
                   15333:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
                   15334: 
1.227     brouard  15335:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   15336:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  15337:   fflush(fichtm);
                   15338:   fflush(ficgp);
                   15339:   
1.227     brouard  15340:   
1.126     brouard  15341:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  15342:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   15343:     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  15344:   }else{
                   15345:     printf("End of Imach\n");
                   15346:     fprintf(ficlog,"End of Imach\n");
                   15347:   }
                   15348:   printf("See log file on %s\n",filelog);
                   15349:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  15350:   /*(void) gettimeofday(&end_time,&tzp);*/
                   15351:   rend_time = time(NULL);  
                   15352:   end_time = *localtime(&rend_time);
                   15353:   /* tml = *localtime(&end_time.tm_sec); */
                   15354:   strcpy(strtend,asctime(&end_time));
1.126     brouard  15355:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   15356:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  15357:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  15358:   
1.157     brouard  15359:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   15360:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   15361:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  15362:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   15363: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   15364:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   15365:   fclose(fichtm);
                   15366:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   15367:   fclose(fichtmcov);
                   15368:   fclose(ficgp);
                   15369:   fclose(ficlog);
                   15370:   /*------ End -----------*/
1.227     brouard  15371:   
1.281     brouard  15372: 
                   15373: /* Executes gnuplot */
1.227     brouard  15374:   
                   15375:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  15376: #ifdef WIN32
1.227     brouard  15377:   if (_chdir(pathcd) != 0)
                   15378:     printf("Can't move to directory %s!\n",path);
                   15379:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  15380: #else
1.227     brouard  15381:     if(chdir(pathcd) != 0)
                   15382:       printf("Can't move to directory %s!\n", path);
                   15383:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  15384: #endif 
1.126     brouard  15385:     printf("Current directory %s!\n",pathcd);
                   15386:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   15387:   sprintf(plotcmd,"gnuplot");
1.157     brouard  15388: #ifdef _WIN32
1.126     brouard  15389:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   15390: #endif
                   15391:   if(!stat(plotcmd,&info)){
1.158     brouard  15392:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  15393:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  15394:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  15395:     }else
                   15396:       strcpy(pplotcmd,plotcmd);
1.157     brouard  15397: #ifdef __unix
1.126     brouard  15398:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   15399:     if(!stat(plotcmd,&info)){
1.158     brouard  15400:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  15401:     }else
                   15402:       strcpy(pplotcmd,plotcmd);
                   15403: #endif
                   15404:   }else
                   15405:     strcpy(pplotcmd,plotcmd);
                   15406:   
                   15407:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  15408:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  15409:   strcpy(pplotcmd,plotcmd);
1.227     brouard  15410:   
1.126     brouard  15411:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  15412:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  15413:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  15414:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  15415:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  15416:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  15417:       strcpy(plotcmd,pplotcmd);
                   15418:     }
1.126     brouard  15419:   }
1.158     brouard  15420:   printf(" Successful, please wait...");
1.126     brouard  15421:   while (z[0] != 'q') {
                   15422:     /* chdir(path); */
1.154     brouard  15423:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  15424:     scanf("%s",z);
                   15425: /*     if (z[0] == 'c') system("./imach"); */
                   15426:     if (z[0] == 'e') {
1.158     brouard  15427: #ifdef __APPLE__
1.152     brouard  15428:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  15429: #elif __linux
                   15430:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  15431: #else
1.152     brouard  15432:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  15433: #endif
                   15434:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   15435:       system(pplotcmd);
1.126     brouard  15436:     }
                   15437:     else if (z[0] == 'g') system(plotcmd);
                   15438:     else if (z[0] == 'q') exit(0);
                   15439:   }
1.227     brouard  15440: end:
1.126     brouard  15441:   while (z[0] != 'q') {
1.195     brouard  15442:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  15443:     scanf("%s",z);
                   15444:   }
1.283     brouard  15445:   printf("End\n");
1.282     brouard  15446:   exit(0);
1.126     brouard  15447: }

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