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

1.353   ! brouard     1: /* $Id: imach.c,v 1.352 2023/04/29 10:46:21 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.353   ! brouard     4:   Revision 1.352  2023/04/29 10:46:21  brouard
        !             5:   *** empty log message ***
        !             6: 
1.352     brouard     7:   Revision 1.351  2023/04/29 10:43:47  brouard
                      8:   Summary: 099r45
                      9: 
1.351     brouard    10:   Revision 1.350  2023/04/24 11:38:06  brouard
                     11:   *** empty log message ***
                     12: 
1.350     brouard    13:   Revision 1.349  2023/01/31 09:19:37  brouard
                     14:   Summary: Improvements in models with age*Vn*Vm
                     15: 
1.348     brouard    16:   Revision 1.347  2022/09/18 14:36:44  brouard
                     17:   Summary: version 0.99r42
                     18: 
1.347     brouard    19:   Revision 1.346  2022/09/16 13:52:36  brouard
                     20:   * src/imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     21: 
1.346     brouard    22:   Revision 1.345  2022/09/16 13:40:11  brouard
                     23:   Summary: Version 0.99r41
                     24: 
                     25:   * imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     26: 
1.345     brouard    27:   Revision 1.344  2022/09/14 19:33:30  brouard
                     28:   Summary: version 0.99r40
                     29: 
                     30:   * imach.c (Module): Fixing names of variables in T_ (thanks to Feinuo)
                     31: 
1.344     brouard    32:   Revision 1.343  2022/09/14 14:22:16  brouard
                     33:   Summary: version 0.99r39
                     34: 
                     35:   * imach.c (Module): Version 0.99r39 with colored dummy covariates
                     36:   (fixed or time varying), using new last columns of
                     37:   ILK_parameter.txt file.
                     38: 
1.343     brouard    39:   Revision 1.342  2022/09/11 19:54:09  brouard
                     40:   Summary: 0.99r38
                     41: 
                     42:   * imach.c (Module): Adding timevarying products of any kinds,
                     43:   should work before shifting cotvar from ncovcol+nqv columns in
                     44:   order to have a correspondance between the column of cotvar and
                     45:   the id of column.
                     46:   (Module): Some cleaning and adding covariates in ILK.txt
                     47: 
1.342     brouard    48:   Revision 1.341  2022/09/11 07:58:42  brouard
                     49:   Summary: Version 0.99r38
                     50: 
                     51:   After adding change in cotvar.
                     52: 
1.341     brouard    53:   Revision 1.340  2022/09/11 07:53:11  brouard
                     54:   Summary: Version imach 0.99r37
                     55: 
                     56:   * imach.c (Module): Adding timevarying products of any kinds,
                     57:   should work before shifting cotvar from ncovcol+nqv columns in
                     58:   order to have a correspondance between the column of cotvar and
                     59:   the id of column.
                     60: 
1.340     brouard    61:   Revision 1.339  2022/09/09 17:55:22  brouard
                     62:   Summary: version 0.99r37
                     63: 
                     64:   * imach.c (Module): Many improvements for fixing products of fixed
                     65:   timevarying as well as fixed * fixed, and test with quantitative
                     66:   covariate.
                     67: 
1.339     brouard    68:   Revision 1.338  2022/09/04 17:40:33  brouard
                     69:   Summary: 0.99r36
                     70: 
                     71:   * imach.c (Module): Now the easy runs i.e. without result or
                     72:   model=1+age only did not work. The defautl combination should be 1
                     73:   and not 0 because everything hasn't been tranformed yet.
                     74: 
1.338     brouard    75:   Revision 1.337  2022/09/02 14:26:02  brouard
                     76:   Summary: version 0.99r35
                     77: 
                     78:   * src/imach.c: Version 0.99r35 because it outputs same results with
                     79:   1+age+V1+V1*age for females and 1+age for females only
                     80:   (education=1 noweight)
                     81: 
1.337     brouard    82:   Revision 1.336  2022/08/31 09:52:36  brouard
                     83:   *** empty log message ***
                     84: 
1.336     brouard    85:   Revision 1.335  2022/08/31 08:23:16  brouard
                     86:   Summary: improvements...
                     87: 
1.335     brouard    88:   Revision 1.334  2022/08/25 09:08:41  brouard
                     89:   Summary: In progress for quantitative
                     90: 
1.334     brouard    91:   Revision 1.333  2022/08/21 09:10:30  brouard
                     92:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     93:   reassigning covariates: my first idea was that people will always
                     94:   use the first covariate V1 into the model but in fact they are
                     95:   producing data with many covariates and can use an equation model
                     96:   with some of the covariate; it means that in a model V2+V3 instead
                     97:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                     98:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                     99:   the equation model is restricted to two variables only (V2, V3)
                    100:   and the combination for V2 should be codtabm(k,1) instead of
                    101:   (codtabm(k,2), and the code should be
                    102:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    103:   made. All of these should be simplified once a day like we did in
                    104:   hpxij() for example by using precov[nres] which is computed in
                    105:   decoderesult for each nres of each resultline. Loop should be done
                    106:   on the equation model globally by distinguishing only product with
                    107:   age (which are changing with age) and no more on type of
                    108:   covariates, single dummies, single covariates.
                    109: 
1.333     brouard   110:   Revision 1.332  2022/08/21 09:06:25  brouard
                    111:   Summary: Version 0.99r33
                    112: 
                    113:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                    114:   reassigning covariates: my first idea was that people will always
                    115:   use the first covariate V1 into the model but in fact they are
                    116:   producing data with many covariates and can use an equation model
                    117:   with some of the covariate; it means that in a model V2+V3 instead
                    118:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    119:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    120:   the equation model is restricted to two variables only (V2, V3)
                    121:   and the combination for V2 should be codtabm(k,1) instead of
                    122:   (codtabm(k,2), and the code should be
                    123:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    124:   made. All of these should be simplified once a day like we did in
                    125:   hpxij() for example by using precov[nres] which is computed in
                    126:   decoderesult for each nres of each resultline. Loop should be done
                    127:   on the equation model globally by distinguishing only product with
                    128:   age (which are changing with age) and no more on type of
                    129:   covariates, single dummies, single covariates.
                    130: 
1.332     brouard   131:   Revision 1.331  2022/08/07 05:40:09  brouard
                    132:   *** empty log message ***
                    133: 
1.331     brouard   134:   Revision 1.330  2022/08/06 07:18:25  brouard
                    135:   Summary: last 0.99r31
                    136: 
                    137:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                    138: 
1.330     brouard   139:   Revision 1.329  2022/08/03 17:29:54  brouard
                    140:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                    141: 
1.329     brouard   142:   Revision 1.328  2022/07/27 17:40:48  brouard
                    143:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                    144: 
1.328     brouard   145:   Revision 1.327  2022/07/27 14:47:35  brouard
                    146:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                    147: 
1.327     brouard   148:   Revision 1.326  2022/07/26 17:33:55  brouard
                    149:   Summary: some test with nres=1
                    150: 
1.326     brouard   151:   Revision 1.325  2022/07/25 14:27:23  brouard
                    152:   Summary: r30
                    153: 
                    154:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                    155:   coredumped, revealed by Feiuno, thank you.
                    156: 
1.325     brouard   157:   Revision 1.324  2022/07/23 17:44:26  brouard
                    158:   *** empty log message ***
                    159: 
1.324     brouard   160:   Revision 1.323  2022/07/22 12:30:08  brouard
                    161:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    162: 
1.323     brouard   163:   Revision 1.322  2022/07/22 12:27:48  brouard
                    164:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    165: 
1.322     brouard   166:   Revision 1.321  2022/07/22 12:04:24  brouard
                    167:   Summary: r28
                    168: 
                    169:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    170: 
1.321     brouard   171:   Revision 1.320  2022/06/02 05:10:11  brouard
                    172:   *** empty log message ***
                    173: 
1.320     brouard   174:   Revision 1.319  2022/06/02 04:45:11  brouard
                    175:   * imach.c (Module): Adding the Wald tests from the log to the main
                    176:   htm for better display of the maximum likelihood estimators.
                    177: 
1.319     brouard   178:   Revision 1.318  2022/05/24 08:10:59  brouard
                    179:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                    180:   of confidencce intervals with product in the equation modelC
                    181: 
1.318     brouard   182:   Revision 1.317  2022/05/15 15:06:23  brouard
                    183:   * imach.c (Module):  Some minor improvements
                    184: 
1.317     brouard   185:   Revision 1.316  2022/05/11 15:11:31  brouard
                    186:   Summary: r27
                    187: 
1.316     brouard   188:   Revision 1.315  2022/05/11 15:06:32  brouard
                    189:   *** empty log message ***
                    190: 
1.315     brouard   191:   Revision 1.314  2022/04/13 17:43:09  brouard
                    192:   * imach.c (Module): Adding link to text data files
                    193: 
1.314     brouard   194:   Revision 1.313  2022/04/11 15:57:42  brouard
                    195:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    196: 
1.313     brouard   197:   Revision 1.312  2022/04/05 21:24:39  brouard
                    198:   *** empty log message ***
                    199: 
1.312     brouard   200:   Revision 1.311  2022/04/05 21:03:51  brouard
                    201:   Summary: Fixed quantitative covariates
                    202: 
                    203:          Fixed covariates (dummy or quantitative)
                    204:        with missing values have never been allowed but are ERRORS and
                    205:        program quits. Standard deviations of fixed covariates were
                    206:        wrongly computed. Mean and standard deviations of time varying
                    207:        covariates are still not computed.
                    208: 
1.311     brouard   209:   Revision 1.310  2022/03/17 08:45:53  brouard
                    210:   Summary: 99r25
                    211: 
                    212:   Improving detection of errors: result lines should be compatible with
                    213:   the model.
                    214: 
1.310     brouard   215:   Revision 1.309  2021/05/20 12:39:14  brouard
                    216:   Summary: Version 0.99r24
                    217: 
1.309     brouard   218:   Revision 1.308  2021/03/31 13:11:57  brouard
                    219:   Summary: Version 0.99r23
                    220: 
                    221: 
                    222:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    223: 
1.308     brouard   224:   Revision 1.307  2021/03/08 18:11:32  brouard
                    225:   Summary: 0.99r22 fixed bug on result:
                    226: 
1.307     brouard   227:   Revision 1.306  2021/02/20 15:44:02  brouard
                    228:   Summary: Version 0.99r21
                    229: 
                    230:   * imach.c (Module): Fix bug on quitting after result lines!
                    231:   (Module): Version 0.99r21
                    232: 
1.306     brouard   233:   Revision 1.305  2021/02/20 15:28:30  brouard
                    234:   * imach.c (Module): Fix bug on quitting after result lines!
                    235: 
1.305     brouard   236:   Revision 1.304  2021/02/12 11:34:20  brouard
                    237:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    238: 
1.304     brouard   239:   Revision 1.303  2021/02/11 19:50:15  brouard
                    240:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    241: 
1.303     brouard   242:   Revision 1.302  2020/02/22 21:00:05  brouard
                    243:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    244:   and life table from the data without any state)
                    245: 
1.302     brouard   246:   Revision 1.301  2019/06/04 13:51:20  brouard
                    247:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    248: 
1.301     brouard   249:   Revision 1.300  2019/05/22 19:09:45  brouard
                    250:   Summary: version 0.99r19 of May 2019
                    251: 
1.300     brouard   252:   Revision 1.299  2019/05/22 18:37:08  brouard
                    253:   Summary: Cleaned 0.99r19
                    254: 
1.299     brouard   255:   Revision 1.298  2019/05/22 18:19:56  brouard
                    256:   *** empty log message ***
                    257: 
1.298     brouard   258:   Revision 1.297  2019/05/22 17:56:10  brouard
                    259:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    260: 
1.297     brouard   261:   Revision 1.296  2019/05/20 13:03:18  brouard
                    262:   Summary: Projection syntax simplified
                    263: 
                    264: 
                    265:   We can now start projections, forward or backward, from the mean date
                    266:   of inteviews up to or down to a number of years of projection:
                    267:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    268:   or
                    269:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    270:   or
                    271:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    272:   or
                    273:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    274: 
1.296     brouard   275:   Revision 1.295  2019/05/18 09:52:50  brouard
                    276:   Summary: doxygen tex bug
                    277: 
1.295     brouard   278:   Revision 1.294  2019/05/16 14:54:33  brouard
                    279:   Summary: There was some wrong lines added
                    280: 
1.294     brouard   281:   Revision 1.293  2019/05/09 15:17:34  brouard
                    282:   *** empty log message ***
                    283: 
1.293     brouard   284:   Revision 1.292  2019/05/09 14:17:20  brouard
                    285:   Summary: Some updates
                    286: 
1.292     brouard   287:   Revision 1.291  2019/05/09 13:44:18  brouard
                    288:   Summary: Before ncovmax
                    289: 
1.291     brouard   290:   Revision 1.290  2019/05/09 13:39:37  brouard
                    291:   Summary: 0.99r18 unlimited number of individuals
                    292: 
                    293:   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.
                    294: 
1.290     brouard   295:   Revision 1.289  2018/12/13 09:16:26  brouard
                    296:   Summary: Bug for young ages (<-30) will be in r17
                    297: 
1.289     brouard   298:   Revision 1.288  2018/05/02 20:58:27  brouard
                    299:   Summary: Some bugs fixed
                    300: 
1.288     brouard   301:   Revision 1.287  2018/05/01 17:57:25  brouard
                    302:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    303: 
1.287     brouard   304:   Revision 1.286  2018/04/27 14:27:04  brouard
                    305:   Summary: some minor bugs
                    306: 
1.286     brouard   307:   Revision 1.285  2018/04/21 21:02:16  brouard
                    308:   Summary: Some bugs fixed, valgrind tested
                    309: 
1.285     brouard   310:   Revision 1.284  2018/04/20 05:22:13  brouard
                    311:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    312: 
1.284     brouard   313:   Revision 1.283  2018/04/19 14:49:16  brouard
                    314:   Summary: Some minor bugs fixed
                    315: 
1.283     brouard   316:   Revision 1.282  2018/02/27 22:50:02  brouard
                    317:   *** empty log message ***
                    318: 
1.282     brouard   319:   Revision 1.281  2018/02/27 19:25:23  brouard
                    320:   Summary: Adding second argument for quitting
                    321: 
1.281     brouard   322:   Revision 1.280  2018/02/21 07:58:13  brouard
                    323:   Summary: 0.99r15
                    324: 
                    325:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    326: 
1.280     brouard   327:   Revision 1.279  2017/07/20 13:35:01  brouard
                    328:   Summary: temporary working
                    329: 
1.279     brouard   330:   Revision 1.278  2017/07/19 14:09:02  brouard
                    331:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    332: 
1.278     brouard   333:   Revision 1.277  2017/07/17 08:53:49  brouard
                    334:   Summary: BOM files can be read now
                    335: 
1.277     brouard   336:   Revision 1.276  2017/06/30 15:48:31  brouard
                    337:   Summary: Graphs improvements
                    338: 
1.276     brouard   339:   Revision 1.275  2017/06/30 13:39:33  brouard
                    340:   Summary: Saito's color
                    341: 
1.275     brouard   342:   Revision 1.274  2017/06/29 09:47:08  brouard
                    343:   Summary: Version 0.99r14
                    344: 
1.274     brouard   345:   Revision 1.273  2017/06/27 11:06:02  brouard
                    346:   Summary: More documentation on projections
                    347: 
1.273     brouard   348:   Revision 1.272  2017/06/27 10:22:40  brouard
                    349:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    350: 
1.272     brouard   351:   Revision 1.271  2017/06/27 10:17:50  brouard
                    352:   Summary: Some bug with rint
                    353: 
1.271     brouard   354:   Revision 1.270  2017/05/24 05:45:29  brouard
                    355:   *** empty log message ***
                    356: 
1.270     brouard   357:   Revision 1.269  2017/05/23 08:39:25  brouard
                    358:   Summary: Code into subroutine, cleanings
                    359: 
1.269     brouard   360:   Revision 1.268  2017/05/18 20:09:32  brouard
                    361:   Summary: backprojection and confidence intervals of backprevalence
                    362: 
1.268     brouard   363:   Revision 1.267  2017/05/13 10:25:05  brouard
                    364:   Summary: temporary save for backprojection
                    365: 
1.267     brouard   366:   Revision 1.266  2017/05/13 07:26:12  brouard
                    367:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    368: 
1.266     brouard   369:   Revision 1.265  2017/04/26 16:22:11  brouard
                    370:   Summary: imach 0.99r13 Some bugs fixed
                    371: 
1.265     brouard   372:   Revision 1.264  2017/04/26 06:01:29  brouard
                    373:   Summary: Labels in graphs
                    374: 
1.264     brouard   375:   Revision 1.263  2017/04/24 15:23:15  brouard
                    376:   Summary: to save
                    377: 
1.263     brouard   378:   Revision 1.262  2017/04/18 16:48:12  brouard
                    379:   *** empty log message ***
                    380: 
1.262     brouard   381:   Revision 1.261  2017/04/05 10:14:09  brouard
                    382:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    383: 
1.261     brouard   384:   Revision 1.260  2017/04/04 17:46:59  brouard
                    385:   Summary: Gnuplot indexations fixed (humm)
                    386: 
1.260     brouard   387:   Revision 1.259  2017/04/04 13:01:16  brouard
                    388:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    389: 
1.259     brouard   390:   Revision 1.258  2017/04/03 10:17:47  brouard
                    391:   Summary: Version 0.99r12
                    392: 
                    393:   Some cleanings, conformed with updated documentation.
                    394: 
1.258     brouard   395:   Revision 1.257  2017/03/29 16:53:30  brouard
                    396:   Summary: Temp
                    397: 
1.257     brouard   398:   Revision 1.256  2017/03/27 05:50:23  brouard
                    399:   Summary: Temporary
                    400: 
1.256     brouard   401:   Revision 1.255  2017/03/08 16:02:28  brouard
                    402:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    403: 
1.255     brouard   404:   Revision 1.254  2017/03/08 07:13:00  brouard
                    405:   Summary: Fixing data parameter line
                    406: 
1.254     brouard   407:   Revision 1.253  2016/12/15 11:59:41  brouard
                    408:   Summary: 0.99 in progress
                    409: 
1.253     brouard   410:   Revision 1.252  2016/09/15 21:15:37  brouard
                    411:   *** empty log message ***
                    412: 
1.252     brouard   413:   Revision 1.251  2016/09/15 15:01:13  brouard
                    414:   Summary: not working
                    415: 
1.251     brouard   416:   Revision 1.250  2016/09/08 16:07:27  brouard
                    417:   Summary: continue
                    418: 
1.250     brouard   419:   Revision 1.249  2016/09/07 17:14:18  brouard
                    420:   Summary: Starting values from frequencies
                    421: 
1.249     brouard   422:   Revision 1.248  2016/09/07 14:10:18  brouard
                    423:   *** empty log message ***
                    424: 
1.248     brouard   425:   Revision 1.247  2016/09/02 11:11:21  brouard
                    426:   *** empty log message ***
                    427: 
1.247     brouard   428:   Revision 1.246  2016/09/02 08:49:22  brouard
                    429:   *** empty log message ***
                    430: 
1.246     brouard   431:   Revision 1.245  2016/09/02 07:25:01  brouard
                    432:   *** empty log message ***
                    433: 
1.245     brouard   434:   Revision 1.244  2016/09/02 07:17:34  brouard
                    435:   *** empty log message ***
                    436: 
1.244     brouard   437:   Revision 1.243  2016/09/02 06:45:35  brouard
                    438:   *** empty log message ***
                    439: 
1.243     brouard   440:   Revision 1.242  2016/08/30 15:01:20  brouard
                    441:   Summary: Fixing a lots
                    442: 
1.242     brouard   443:   Revision 1.241  2016/08/29 17:17:25  brouard
                    444:   Summary: gnuplot problem in Back projection to fix
                    445: 
1.241     brouard   446:   Revision 1.240  2016/08/29 07:53:18  brouard
                    447:   Summary: Better
                    448: 
1.240     brouard   449:   Revision 1.239  2016/08/26 15:51:03  brouard
                    450:   Summary: Improvement in Powell output in order to copy and paste
                    451: 
                    452:   Author:
                    453: 
1.239     brouard   454:   Revision 1.238  2016/08/26 14:23:35  brouard
                    455:   Summary: Starting tests of 0.99
                    456: 
1.238     brouard   457:   Revision 1.237  2016/08/26 09:20:19  brouard
                    458:   Summary: to valgrind
                    459: 
1.237     brouard   460:   Revision 1.236  2016/08/25 10:50:18  brouard
                    461:   *** empty log message ***
                    462: 
1.236     brouard   463:   Revision 1.235  2016/08/25 06:59:23  brouard
                    464:   *** empty log message ***
                    465: 
1.235     brouard   466:   Revision 1.234  2016/08/23 16:51:20  brouard
                    467:   *** empty log message ***
                    468: 
1.234     brouard   469:   Revision 1.233  2016/08/23 07:40:50  brouard
                    470:   Summary: not working
                    471: 
1.233     brouard   472:   Revision 1.232  2016/08/22 14:20:21  brouard
                    473:   Summary: not working
                    474: 
1.232     brouard   475:   Revision 1.231  2016/08/22 07:17:15  brouard
                    476:   Summary: not working
                    477: 
1.231     brouard   478:   Revision 1.230  2016/08/22 06:55:53  brouard
                    479:   Summary: Not working
                    480: 
1.230     brouard   481:   Revision 1.229  2016/07/23 09:45:53  brouard
                    482:   Summary: Completing for func too
                    483: 
1.229     brouard   484:   Revision 1.228  2016/07/22 17:45:30  brouard
                    485:   Summary: Fixing some arrays, still debugging
                    486: 
1.227     brouard   487:   Revision 1.226  2016/07/12 18:42:34  brouard
                    488:   Summary: temp
                    489: 
1.226     brouard   490:   Revision 1.225  2016/07/12 08:40:03  brouard
                    491:   Summary: saving but not running
                    492: 
1.225     brouard   493:   Revision 1.224  2016/07/01 13:16:01  brouard
                    494:   Summary: Fixes
                    495: 
1.224     brouard   496:   Revision 1.223  2016/02/19 09:23:35  brouard
                    497:   Summary: temporary
                    498: 
1.223     brouard   499:   Revision 1.222  2016/02/17 08:14:50  brouard
                    500:   Summary: Probably last 0.98 stable version 0.98r6
                    501: 
1.222     brouard   502:   Revision 1.221  2016/02/15 23:35:36  brouard
                    503:   Summary: minor bug
                    504: 
1.220     brouard   505:   Revision 1.219  2016/02/15 00:48:12  brouard
                    506:   *** empty log message ***
                    507: 
1.219     brouard   508:   Revision 1.218  2016/02/12 11:29:23  brouard
                    509:   Summary: 0.99 Back projections
                    510: 
1.218     brouard   511:   Revision 1.217  2015/12/23 17:18:31  brouard
                    512:   Summary: Experimental backcast
                    513: 
1.217     brouard   514:   Revision 1.216  2015/12/18 17:32:11  brouard
                    515:   Summary: 0.98r4 Warning and status=-2
                    516: 
                    517:   Version 0.98r4 is now:
                    518:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    519:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    520:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    521: 
1.216     brouard   522:   Revision 1.215  2015/12/16 08:52:24  brouard
                    523:   Summary: 0.98r4 working
                    524: 
1.215     brouard   525:   Revision 1.214  2015/12/16 06:57:54  brouard
                    526:   Summary: temporary not working
                    527: 
1.214     brouard   528:   Revision 1.213  2015/12/11 18:22:17  brouard
                    529:   Summary: 0.98r4
                    530: 
1.213     brouard   531:   Revision 1.212  2015/11/21 12:47:24  brouard
                    532:   Summary: minor typo
                    533: 
1.212     brouard   534:   Revision 1.211  2015/11/21 12:41:11  brouard
                    535:   Summary: 0.98r3 with some graph of projected cross-sectional
                    536: 
                    537:   Author: Nicolas Brouard
                    538: 
1.211     brouard   539:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   540:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   541:   Summary: Adding ftolpl parameter
                    542:   Author: N Brouard
                    543: 
                    544:   We had difficulties to get smoothed confidence intervals. It was due
                    545:   to the period prevalence which wasn't computed accurately. The inner
                    546:   parameter ftolpl is now an outer parameter of the .imach parameter
                    547:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    548:   computation are long.
                    549: 
1.209     brouard   550:   Revision 1.208  2015/11/17 14:31:57  brouard
                    551:   Summary: temporary
                    552: 
1.208     brouard   553:   Revision 1.207  2015/10/27 17:36:57  brouard
                    554:   *** empty log message ***
                    555: 
1.207     brouard   556:   Revision 1.206  2015/10/24 07:14:11  brouard
                    557:   *** empty log message ***
                    558: 
1.206     brouard   559:   Revision 1.205  2015/10/23 15:50:53  brouard
                    560:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    561: 
1.205     brouard   562:   Revision 1.204  2015/10/01 16:20:26  brouard
                    563:   Summary: Some new graphs of contribution to likelihood
                    564: 
1.204     brouard   565:   Revision 1.203  2015/09/30 17:45:14  brouard
                    566:   Summary: looking at better estimation of the hessian
                    567: 
                    568:   Also a better criteria for convergence to the period prevalence And
                    569:   therefore adding the number of years needed to converge. (The
                    570:   prevalence in any alive state shold sum to one
                    571: 
1.203     brouard   572:   Revision 1.202  2015/09/22 19:45:16  brouard
                    573:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    574: 
1.202     brouard   575:   Revision 1.201  2015/09/15 17:34:58  brouard
                    576:   Summary: 0.98r0
                    577: 
                    578:   - Some new graphs like suvival functions
                    579:   - Some bugs fixed like model=1+age+V2.
                    580: 
1.201     brouard   581:   Revision 1.200  2015/09/09 16:53:55  brouard
                    582:   Summary: Big bug thanks to Flavia
                    583: 
                    584:   Even model=1+age+V2. did not work anymore
                    585: 
1.200     brouard   586:   Revision 1.199  2015/09/07 14:09:23  brouard
                    587:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    588: 
1.199     brouard   589:   Revision 1.198  2015/09/03 07:14:39  brouard
                    590:   Summary: 0.98q5 Flavia
                    591: 
1.198     brouard   592:   Revision 1.197  2015/09/01 18:24:39  brouard
                    593:   *** empty log message ***
                    594: 
1.197     brouard   595:   Revision 1.196  2015/08/18 23:17:52  brouard
                    596:   Summary: 0.98q5
                    597: 
1.196     brouard   598:   Revision 1.195  2015/08/18 16:28:39  brouard
                    599:   Summary: Adding a hack for testing purpose
                    600: 
                    601:   After reading the title, ftol and model lines, if the comment line has
                    602:   a q, starting with #q, the answer at the end of the run is quit. It
                    603:   permits to run test files in batch with ctest. The former workaround was
                    604:   $ echo q | imach foo.imach
                    605: 
1.195     brouard   606:   Revision 1.194  2015/08/18 13:32:00  brouard
                    607:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    608: 
1.194     brouard   609:   Revision 1.193  2015/08/04 07:17:42  brouard
                    610:   Summary: 0.98q4
                    611: 
1.193     brouard   612:   Revision 1.192  2015/07/16 16:49:02  brouard
                    613:   Summary: Fixing some outputs
                    614: 
1.192     brouard   615:   Revision 1.191  2015/07/14 10:00:33  brouard
                    616:   Summary: Some fixes
                    617: 
1.191     brouard   618:   Revision 1.190  2015/05/05 08:51:13  brouard
                    619:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    620: 
                    621:   Fix 1+age+.
                    622: 
1.190     brouard   623:   Revision 1.189  2015/04/30 14:45:16  brouard
                    624:   Summary: 0.98q2
                    625: 
1.189     brouard   626:   Revision 1.188  2015/04/30 08:27:53  brouard
                    627:   *** empty log message ***
                    628: 
1.188     brouard   629:   Revision 1.187  2015/04/29 09:11:15  brouard
                    630:   *** empty log message ***
                    631: 
1.187     brouard   632:   Revision 1.186  2015/04/23 12:01:52  brouard
                    633:   Summary: V1*age is working now, version 0.98q1
                    634: 
                    635:   Some codes had been disabled in order to simplify and Vn*age was
                    636:   working in the optimization phase, ie, giving correct MLE parameters,
                    637:   but, as usual, outputs were not correct and program core dumped.
                    638: 
1.186     brouard   639:   Revision 1.185  2015/03/11 13:26:42  brouard
                    640:   Summary: Inclusion of compile and links command line for Intel Compiler
                    641: 
1.185     brouard   642:   Revision 1.184  2015/03/11 11:52:39  brouard
                    643:   Summary: Back from Windows 8. Intel Compiler
                    644: 
1.184     brouard   645:   Revision 1.183  2015/03/10 20:34:32  brouard
                    646:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    647: 
                    648:   We use directest instead of original Powell test; probably no
                    649:   incidence on the results, but better justifications;
                    650:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    651:   wrong results.
                    652: 
1.183     brouard   653:   Revision 1.182  2015/02/12 08:19:57  brouard
                    654:   Summary: Trying to keep directest which seems simpler and more general
                    655:   Author: Nicolas Brouard
                    656: 
1.182     brouard   657:   Revision 1.181  2015/02/11 23:22:24  brouard
                    658:   Summary: Comments on Powell added
                    659: 
                    660:   Author:
                    661: 
1.181     brouard   662:   Revision 1.180  2015/02/11 17:33:45  brouard
                    663:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    664: 
1.180     brouard   665:   Revision 1.179  2015/01/04 09:57:06  brouard
                    666:   Summary: back to OS/X
                    667: 
1.179     brouard   668:   Revision 1.178  2015/01/04 09:35:48  brouard
                    669:   *** empty log message ***
                    670: 
1.178     brouard   671:   Revision 1.177  2015/01/03 18:40:56  brouard
                    672:   Summary: Still testing ilc32 on OSX
                    673: 
1.177     brouard   674:   Revision 1.176  2015/01/03 16:45:04  brouard
                    675:   *** empty log message ***
                    676: 
1.176     brouard   677:   Revision 1.175  2015/01/03 16:33:42  brouard
                    678:   *** empty log message ***
                    679: 
1.175     brouard   680:   Revision 1.174  2015/01/03 16:15:49  brouard
                    681:   Summary: Still in cross-compilation
                    682: 
1.174     brouard   683:   Revision 1.173  2015/01/03 12:06:26  brouard
                    684:   Summary: trying to detect cross-compilation
                    685: 
1.173     brouard   686:   Revision 1.172  2014/12/27 12:07:47  brouard
                    687:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    688: 
1.172     brouard   689:   Revision 1.171  2014/12/23 13:26:59  brouard
                    690:   Summary: Back from Visual C
                    691: 
                    692:   Still problem with utsname.h on Windows
                    693: 
1.171     brouard   694:   Revision 1.170  2014/12/23 11:17:12  brouard
                    695:   Summary: Cleaning some \%% back to %%
                    696: 
                    697:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    698: 
1.170     brouard   699:   Revision 1.169  2014/12/22 23:08:31  brouard
                    700:   Summary: 0.98p
                    701: 
                    702:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    703: 
1.169     brouard   704:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   705:   Summary: update
1.169     brouard   706: 
1.168     brouard   707:   Revision 1.167  2014/12/22 13:50:56  brouard
                    708:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    709: 
                    710:   Testing on Linux 64
                    711: 
1.167     brouard   712:   Revision 1.166  2014/12/22 11:40:47  brouard
                    713:   *** empty log message ***
                    714: 
1.166     brouard   715:   Revision 1.165  2014/12/16 11:20:36  brouard
                    716:   Summary: After compiling on Visual C
                    717: 
                    718:   * imach.c (Module): Merging 1.61 to 1.162
                    719: 
1.165     brouard   720:   Revision 1.164  2014/12/16 10:52:11  brouard
                    721:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    722: 
                    723:   * imach.c (Module): Merging 1.61 to 1.162
                    724: 
1.164     brouard   725:   Revision 1.163  2014/12/16 10:30:11  brouard
                    726:   * imach.c (Module): Merging 1.61 to 1.162
                    727: 
1.163     brouard   728:   Revision 1.162  2014/09/25 11:43:39  brouard
                    729:   Summary: temporary backup 0.99!
                    730: 
1.162     brouard   731:   Revision 1.1  2014/09/16 11:06:58  brouard
                    732:   Summary: With some code (wrong) for nlopt
                    733: 
                    734:   Author:
                    735: 
                    736:   Revision 1.161  2014/09/15 20:41:41  brouard
                    737:   Summary: Problem with macro SQR on Intel compiler
                    738: 
1.161     brouard   739:   Revision 1.160  2014/09/02 09:24:05  brouard
                    740:   *** empty log message ***
                    741: 
1.160     brouard   742:   Revision 1.159  2014/09/01 10:34:10  brouard
                    743:   Summary: WIN32
                    744:   Author: Brouard
                    745: 
1.159     brouard   746:   Revision 1.158  2014/08/27 17:11:51  brouard
                    747:   *** empty log message ***
                    748: 
1.158     brouard   749:   Revision 1.157  2014/08/27 16:26:55  brouard
                    750:   Summary: Preparing windows Visual studio version
                    751:   Author: Brouard
                    752: 
                    753:   In order to compile on Visual studio, time.h is now correct and time_t
                    754:   and tm struct should be used. difftime should be used but sometimes I
                    755:   just make the differences in raw time format (time(&now).
                    756:   Trying to suppress #ifdef LINUX
                    757:   Add xdg-open for __linux in order to open default browser.
                    758: 
1.157     brouard   759:   Revision 1.156  2014/08/25 20:10:10  brouard
                    760:   *** empty log message ***
                    761: 
1.156     brouard   762:   Revision 1.155  2014/08/25 18:32:34  brouard
                    763:   Summary: New compile, minor changes
                    764:   Author: Brouard
                    765: 
1.155     brouard   766:   Revision 1.154  2014/06/20 17:32:08  brouard
                    767:   Summary: Outputs now all graphs of convergence to period prevalence
                    768: 
1.154     brouard   769:   Revision 1.153  2014/06/20 16:45:46  brouard
                    770:   Summary: If 3 live state, convergence to period prevalence on same graph
                    771:   Author: Brouard
                    772: 
1.153     brouard   773:   Revision 1.152  2014/06/18 17:54:09  brouard
                    774:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    775: 
1.152     brouard   776:   Revision 1.151  2014/06/18 16:43:30  brouard
                    777:   *** empty log message ***
                    778: 
1.151     brouard   779:   Revision 1.150  2014/06/18 16:42:35  brouard
                    780:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    781:   Author: brouard
                    782: 
1.150     brouard   783:   Revision 1.149  2014/06/18 15:51:14  brouard
                    784:   Summary: Some fixes in parameter files errors
                    785:   Author: Nicolas Brouard
                    786: 
1.149     brouard   787:   Revision 1.148  2014/06/17 17:38:48  brouard
                    788:   Summary: Nothing new
                    789:   Author: Brouard
                    790: 
                    791:   Just a new packaging for OS/X version 0.98nS
                    792: 
1.148     brouard   793:   Revision 1.147  2014/06/16 10:33:11  brouard
                    794:   *** empty log message ***
                    795: 
1.147     brouard   796:   Revision 1.146  2014/06/16 10:20:28  brouard
                    797:   Summary: Merge
                    798:   Author: Brouard
                    799: 
                    800:   Merge, before building revised version.
                    801: 
1.146     brouard   802:   Revision 1.145  2014/06/10 21:23:15  brouard
                    803:   Summary: Debugging with valgrind
                    804:   Author: Nicolas Brouard
                    805: 
                    806:   Lot of changes in order to output the results with some covariates
                    807:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    808:   improve the code.
                    809:   No more memory valgrind error but a lot has to be done in order to
                    810:   continue the work of splitting the code into subroutines.
                    811:   Also, decodemodel has been improved. Tricode is still not
                    812:   optimal. nbcode should be improved. Documentation has been added in
                    813:   the source code.
                    814: 
1.144     brouard   815:   Revision 1.143  2014/01/26 09:45:38  brouard
                    816:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    817: 
                    818:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    819:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    820: 
1.143     brouard   821:   Revision 1.142  2014/01/26 03:57:36  brouard
                    822:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    823: 
                    824:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    825: 
1.142     brouard   826:   Revision 1.141  2014/01/26 02:42:01  brouard
                    827:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    828: 
1.141     brouard   829:   Revision 1.140  2011/09/02 10:37:54  brouard
                    830:   Summary: times.h is ok with mingw32 now.
                    831: 
1.140     brouard   832:   Revision 1.139  2010/06/14 07:50:17  brouard
                    833:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    834:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    835: 
1.139     brouard   836:   Revision 1.138  2010/04/30 18:19:40  brouard
                    837:   *** empty log message ***
                    838: 
1.138     brouard   839:   Revision 1.137  2010/04/29 18:11:38  brouard
                    840:   (Module): Checking covariates for more complex models
                    841:   than V1+V2. A lot of change to be done. Unstable.
                    842: 
1.137     brouard   843:   Revision 1.136  2010/04/26 20:30:53  brouard
                    844:   (Module): merging some libgsl code. Fixing computation
                    845:   of likelione (using inter/intrapolation if mle = 0) in order to
                    846:   get same likelihood as if mle=1.
                    847:   Some cleaning of code and comments added.
                    848: 
1.136     brouard   849:   Revision 1.135  2009/10/29 15:33:14  brouard
                    850:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    851: 
1.135     brouard   852:   Revision 1.134  2009/10/29 13:18:53  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.134     brouard   855:   Revision 1.133  2009/07/06 10:21:25  brouard
                    856:   just nforces
                    857: 
1.133     brouard   858:   Revision 1.132  2009/07/06 08:22:05  brouard
                    859:   Many tings
                    860: 
1.132     brouard   861:   Revision 1.131  2009/06/20 16:22:47  brouard
                    862:   Some dimensions resccaled
                    863: 
1.131     brouard   864:   Revision 1.130  2009/05/26 06:44:34  brouard
                    865:   (Module): Max Covariate is now set to 20 instead of 8. A
                    866:   lot of cleaning with variables initialized to 0. Trying to make
                    867:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    868: 
1.130     brouard   869:   Revision 1.129  2007/08/31 13:49:27  lievre
                    870:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    871: 
1.129     lievre    872:   Revision 1.128  2006/06/30 13:02:05  brouard
                    873:   (Module): Clarifications on computing e.j
                    874: 
1.128     brouard   875:   Revision 1.127  2006/04/28 18:11:50  brouard
                    876:   (Module): Yes the sum of survivors was wrong since
                    877:   imach-114 because nhstepm was no more computed in the age
                    878:   loop. Now we define nhstepma in the age loop.
                    879:   (Module): In order to speed up (in case of numerous covariates) we
                    880:   compute health expectancies (without variances) in a first step
                    881:   and then all the health expectancies with variances or standard
                    882:   deviation (needs data from the Hessian matrices) which slows the
                    883:   computation.
                    884:   In the future we should be able to stop the program is only health
                    885:   expectancies and graph are needed without standard deviations.
                    886: 
1.127     brouard   887:   Revision 1.126  2006/04/28 17:23:28  brouard
                    888:   (Module): Yes the sum of survivors was wrong since
                    889:   imach-114 because nhstepm was no more computed in the age
                    890:   loop. Now we define nhstepma in the age loop.
                    891:   Version 0.98h
                    892: 
1.126     brouard   893:   Revision 1.125  2006/04/04 15:20:31  lievre
                    894:   Errors in calculation of health expectancies. Age was not initialized.
                    895:   Forecasting file added.
                    896: 
                    897:   Revision 1.124  2006/03/22 17:13:53  lievre
                    898:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    899:   The log-likelihood is printed in the log file
                    900: 
                    901:   Revision 1.123  2006/03/20 10:52:43  brouard
                    902:   * imach.c (Module): <title> changed, corresponds to .htm file
                    903:   name. <head> headers where missing.
                    904: 
                    905:   * imach.c (Module): Weights can have a decimal point as for
                    906:   English (a comma might work with a correct LC_NUMERIC environment,
                    907:   otherwise the weight is truncated).
                    908:   Modification of warning when the covariates values are not 0 or
                    909:   1.
                    910:   Version 0.98g
                    911: 
                    912:   Revision 1.122  2006/03/20 09:45:41  brouard
                    913:   (Module): Weights can have a decimal point as for
                    914:   English (a comma might work with a correct LC_NUMERIC environment,
                    915:   otherwise the weight is truncated).
                    916:   Modification of warning when the covariates values are not 0 or
                    917:   1.
                    918:   Version 0.98g
                    919: 
                    920:   Revision 1.121  2006/03/16 17:45:01  lievre
                    921:   * imach.c (Module): Comments concerning covariates added
                    922: 
                    923:   * imach.c (Module): refinements in the computation of lli if
                    924:   status=-2 in order to have more reliable computation if stepm is
                    925:   not 1 month. Version 0.98f
                    926: 
                    927:   Revision 1.120  2006/03/16 15:10:38  lievre
                    928:   (Module): refinements in the computation of lli if
                    929:   status=-2 in order to have more reliable computation if stepm is
                    930:   not 1 month. Version 0.98f
                    931: 
                    932:   Revision 1.119  2006/03/15 17:42:26  brouard
                    933:   (Module): Bug if status = -2, the loglikelihood was
                    934:   computed as likelihood omitting the logarithm. Version O.98e
                    935: 
                    936:   Revision 1.118  2006/03/14 18:20:07  brouard
                    937:   (Module): varevsij Comments added explaining the second
                    938:   table of variances if popbased=1 .
                    939:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    940:   (Module): Function pstamp added
                    941:   (Module): Version 0.98d
                    942: 
                    943:   Revision 1.117  2006/03/14 17:16:22  brouard
                    944:   (Module): varevsij Comments added explaining the second
                    945:   table of variances if popbased=1 .
                    946:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    947:   (Module): Function pstamp added
                    948:   (Module): Version 0.98d
                    949: 
                    950:   Revision 1.116  2006/03/06 10:29:27  brouard
                    951:   (Module): Variance-covariance wrong links and
                    952:   varian-covariance of ej. is needed (Saito).
                    953: 
                    954:   Revision 1.115  2006/02/27 12:17:45  brouard
                    955:   (Module): One freematrix added in mlikeli! 0.98c
                    956: 
                    957:   Revision 1.114  2006/02/26 12:57:58  brouard
                    958:   (Module): Some improvements in processing parameter
                    959:   filename with strsep.
                    960: 
                    961:   Revision 1.113  2006/02/24 14:20:24  brouard
                    962:   (Module): Memory leaks checks with valgrind and:
                    963:   datafile was not closed, some imatrix were not freed and on matrix
                    964:   allocation too.
                    965: 
                    966:   Revision 1.112  2006/01/30 09:55:26  brouard
                    967:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    968: 
                    969:   Revision 1.111  2006/01/25 20:38:18  brouard
                    970:   (Module): Lots of cleaning and bugs added (Gompertz)
                    971:   (Module): Comments can be added in data file. Missing date values
                    972:   can be a simple dot '.'.
                    973: 
                    974:   Revision 1.110  2006/01/25 00:51:50  brouard
                    975:   (Module): Lots of cleaning and bugs added (Gompertz)
                    976: 
                    977:   Revision 1.109  2006/01/24 19:37:15  brouard
                    978:   (Module): Comments (lines starting with a #) are allowed in data.
                    979: 
                    980:   Revision 1.108  2006/01/19 18:05:42  lievre
                    981:   Gnuplot problem appeared...
                    982:   To be fixed
                    983: 
                    984:   Revision 1.107  2006/01/19 16:20:37  brouard
                    985:   Test existence of gnuplot in imach path
                    986: 
                    987:   Revision 1.106  2006/01/19 13:24:36  brouard
                    988:   Some cleaning and links added in html output
                    989: 
                    990:   Revision 1.105  2006/01/05 20:23:19  lievre
                    991:   *** empty log message ***
                    992: 
                    993:   Revision 1.104  2005/09/30 16:11:43  lievre
                    994:   (Module): sump fixed, loop imx fixed, and simplifications.
                    995:   (Module): If the status is missing at the last wave but we know
                    996:   that the person is alive, then we can code his/her status as -2
                    997:   (instead of missing=-1 in earlier versions) and his/her
                    998:   contributions to the likelihood is 1 - Prob of dying from last
                    999:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                   1000:   the healthy state at last known wave). Version is 0.98
                   1001: 
                   1002:   Revision 1.103  2005/09/30 15:54:49  lievre
                   1003:   (Module): sump fixed, loop imx fixed, and simplifications.
                   1004: 
                   1005:   Revision 1.102  2004/09/15 17:31:30  brouard
                   1006:   Add the possibility to read data file including tab characters.
                   1007: 
                   1008:   Revision 1.101  2004/09/15 10:38:38  brouard
                   1009:   Fix on curr_time
                   1010: 
                   1011:   Revision 1.100  2004/07/12 18:29:06  brouard
                   1012:   Add version for Mac OS X. Just define UNIX in Makefile
                   1013: 
                   1014:   Revision 1.99  2004/06/05 08:57:40  brouard
                   1015:   *** empty log message ***
                   1016: 
                   1017:   Revision 1.98  2004/05/16 15:05:56  brouard
                   1018:   New version 0.97 . First attempt to estimate force of mortality
                   1019:   directly from the data i.e. without the need of knowing the health
                   1020:   state at each age, but using a Gompertz model: log u =a + b*age .
                   1021:   This is the basic analysis of mortality and should be done before any
                   1022:   other analysis, in order to test if the mortality estimated from the
                   1023:   cross-longitudinal survey is different from the mortality estimated
                   1024:   from other sources like vital statistic data.
                   1025: 
                   1026:   The same imach parameter file can be used but the option for mle should be -3.
                   1027: 
1.324     brouard  1028:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard  1029:   former routines in order to include the new code within the former code.
                   1030: 
                   1031:   The output is very simple: only an estimate of the intercept and of
                   1032:   the slope with 95% confident intervals.
                   1033: 
                   1034:   Current limitations:
                   1035:   A) Even if you enter covariates, i.e. with the
                   1036:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                   1037:   B) There is no computation of Life Expectancy nor Life Table.
                   1038: 
                   1039:   Revision 1.97  2004/02/20 13:25:42  lievre
                   1040:   Version 0.96d. Population forecasting command line is (temporarily)
                   1041:   suppressed.
                   1042: 
                   1043:   Revision 1.96  2003/07/15 15:38:55  brouard
                   1044:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                   1045:   rewritten within the same printf. Workaround: many printfs.
                   1046: 
                   1047:   Revision 1.95  2003/07/08 07:54:34  brouard
                   1048:   * imach.c (Repository):
                   1049:   (Repository): Using imachwizard code to output a more meaningful covariance
                   1050:   matrix (cov(a12,c31) instead of numbers.
                   1051: 
                   1052:   Revision 1.94  2003/06/27 13:00:02  brouard
                   1053:   Just cleaning
                   1054: 
                   1055:   Revision 1.93  2003/06/25 16:33:55  brouard
                   1056:   (Module): On windows (cygwin) function asctime_r doesn't
                   1057:   exist so I changed back to asctime which exists.
                   1058:   (Module): Version 0.96b
                   1059: 
                   1060:   Revision 1.92  2003/06/25 16:30:45  brouard
                   1061:   (Module): On windows (cygwin) function asctime_r doesn't
                   1062:   exist so I changed back to asctime which exists.
                   1063: 
                   1064:   Revision 1.91  2003/06/25 15:30:29  brouard
                   1065:   * imach.c (Repository): Duplicated warning errors corrected.
                   1066:   (Repository): Elapsed time after each iteration is now output. It
                   1067:   helps to forecast when convergence will be reached. Elapsed time
                   1068:   is stamped in powell.  We created a new html file for the graphs
                   1069:   concerning matrix of covariance. It has extension -cov.htm.
                   1070: 
                   1071:   Revision 1.90  2003/06/24 12:34:15  brouard
                   1072:   (Module): Some bugs corrected for windows. Also, when
                   1073:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1074:   of the covariance matrix to be input.
                   1075: 
                   1076:   Revision 1.89  2003/06/24 12:30:52  brouard
                   1077:   (Module): Some bugs corrected for windows. Also, when
                   1078:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1079:   of the covariance matrix to be input.
                   1080: 
                   1081:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1082:   * 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.
                   1083: 
                   1084:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1085:   Version 0.96
                   1086: 
                   1087:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1088:   (Module): Change position of html and gnuplot routines and added
                   1089:   routine fileappend.
                   1090: 
                   1091:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1092:   * imach.c (Repository): Check when date of death was earlier that
                   1093:   current date of interview. It may happen when the death was just
                   1094:   prior to the death. In this case, dh was negative and likelihood
                   1095:   was wrong (infinity). We still send an "Error" but patch by
                   1096:   assuming that the date of death was just one stepm after the
                   1097:   interview.
                   1098:   (Repository): Because some people have very long ID (first column)
                   1099:   we changed int to long in num[] and we added a new lvector for
                   1100:   memory allocation. But we also truncated to 8 characters (left
                   1101:   truncation)
                   1102:   (Repository): No more line truncation errors.
                   1103: 
                   1104:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1105:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1106:   place. It differs from routine "prevalence" which may be called
                   1107:   many times. Probs is memory consuming and must be used with
                   1108:   parcimony.
                   1109:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1110: 
                   1111:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1112:   *** empty log message ***
                   1113: 
                   1114:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1115:   Add log in  imach.c and  fullversion number is now printed.
                   1116: 
                   1117: */
                   1118: /*
                   1119:    Interpolated Markov Chain
                   1120: 
                   1121:   Short summary of the programme:
                   1122:   
1.227     brouard  1123:   This program computes Healthy Life Expectancies or State-specific
                   1124:   (if states aren't health statuses) Expectancies from
                   1125:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1126: 
                   1127:   -1- a first survey ("cross") where individuals from different ages
                   1128:   are interviewed on their health status or degree of disability (in
                   1129:   the case of a health survey which is our main interest)
                   1130: 
                   1131:   -2- at least a second wave of interviews ("longitudinal") which
                   1132:   measure each change (if any) in individual health status.  Health
                   1133:   expectancies are computed from the time spent in each health state
                   1134:   according to a model. More health states you consider, more time is
                   1135:   necessary to reach the Maximum Likelihood of the parameters involved
                   1136:   in the model.  The simplest model is the multinomial logistic model
                   1137:   where pij is the probability to be observed in state j at the second
                   1138:   wave conditional to be observed in state i at the first
                   1139:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1140:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1141:   have a more complex model than "constant and age", you should modify
                   1142:   the program where the markup *Covariates have to be included here
                   1143:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1144:   convergence.
                   1145: 
                   1146:   The advantage of this computer programme, compared to a simple
                   1147:   multinomial logistic model, is clear when the delay between waves is not
                   1148:   identical for each individual. Also, if a individual missed an
                   1149:   intermediate interview, the information is lost, but taken into
                   1150:   account using an interpolation or extrapolation.  
                   1151: 
                   1152:   hPijx is the probability to be observed in state i at age x+h
                   1153:   conditional to the observed state i at age x. The delay 'h' can be
                   1154:   split into an exact number (nh*stepm) of unobserved intermediate
                   1155:   states. This elementary transition (by month, quarter,
                   1156:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1157:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1158:   and the contribution of each individual to the likelihood is simply
                   1159:   hPijx.
                   1160: 
                   1161:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1162:   of the life expectancies. It also computes the period (stable) prevalence.
                   1163: 
                   1164: Back prevalence and projections:
1.227     brouard  1165: 
                   1166:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1167:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1168:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1169:    mobilavproj)
                   1170: 
                   1171:     Computes the back prevalence limit for any combination of
                   1172:     covariate values k at any age between ageminpar and agemaxpar and
                   1173:     returns it in **bprlim. In the loops,
                   1174: 
                   1175:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1176:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1177: 
                   1178:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1179:    Computes for any combination of covariates k and any age between bage and fage 
                   1180:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1181:                        oldm=oldms;savm=savms;
1.227     brouard  1182: 
1.267     brouard  1183:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1184:      Computes the transition matrix starting at age 'age' over
                   1185:      'nhstepm*hstepm*stepm' months (i.e. until
                   1186:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1187:      nhstepm*hstepm matrices. 
                   1188: 
                   1189:      Returns p3mat[i][j][h] after calling
                   1190:      p3mat[i][j][h]=matprod2(newm,
                   1191:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1192:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1193:      oldm);
1.226     brouard  1194: 
                   1195: Important routines
                   1196: 
                   1197: - func (or funcone), computes logit (pij) distinguishing
                   1198:   o fixed variables (single or product dummies or quantitative);
                   1199:   o varying variables by:
                   1200:    (1) wave (single, product dummies, quantitative), 
                   1201:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1202:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1203:        % varying dummy (not done) or quantitative (not done);
                   1204: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1205:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1206: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1207:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1208:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1209: 
1.226     brouard  1210: 
                   1211:   
1.324     brouard  1212:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1213:            Institut national d'études démographiques, Paris.
1.126     brouard  1214:   This software have been partly granted by Euro-REVES, a concerted action
                   1215:   from the European Union.
                   1216:   It is copyrighted identically to a GNU software product, ie programme and
                   1217:   software can be distributed freely for non commercial use. Latest version
                   1218:   can be accessed at http://euroreves.ined.fr/imach .
                   1219: 
                   1220:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1221:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1222:   
                   1223:   **********************************************************************/
                   1224: /*
                   1225:   main
                   1226:   read parameterfile
                   1227:   read datafile
                   1228:   concatwav
                   1229:   freqsummary
                   1230:   if (mle >= 1)
                   1231:     mlikeli
                   1232:   print results files
                   1233:   if mle==1 
                   1234:      computes hessian
                   1235:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1236:       begin-prev-date,...
                   1237:   open gnuplot file
                   1238:   open html file
1.145     brouard  1239:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1240:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1241:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1242:     freexexit2 possible for memory heap.
                   1243: 
                   1244:   h Pij x                         | pij_nom  ficrestpij
                   1245:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1246:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1247:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1248: 
                   1249:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1250:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1251:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1252:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1253:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1254: 
1.126     brouard  1255:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1256:   health expectancies
                   1257:   Variance-covariance of DFLE
                   1258:   prevalence()
                   1259:    movingaverage()
                   1260:   varevsij() 
                   1261:   if popbased==1 varevsij(,popbased)
                   1262:   total life expectancies
                   1263:   Variance of period (stable) prevalence
                   1264:  end
                   1265: */
                   1266: 
1.187     brouard  1267: /* #define DEBUG */
                   1268: /* #define DEBUGBRENT */
1.203     brouard  1269: /* #define DEBUGLINMIN */
                   1270: /* #define DEBUGHESS */
                   1271: #define DEBUGHESSIJ
1.224     brouard  1272: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1273: #define POWELL /* Instead of NLOPT */
1.224     brouard  1274: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1275: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1276: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1277: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.126     brouard  1278: 
                   1279: #include <math.h>
                   1280: #include <stdio.h>
                   1281: #include <stdlib.h>
                   1282: #include <string.h>
1.226     brouard  1283: #include <ctype.h>
1.159     brouard  1284: 
                   1285: #ifdef _WIN32
                   1286: #include <io.h>
1.172     brouard  1287: #include <windows.h>
                   1288: #include <tchar.h>
1.159     brouard  1289: #else
1.126     brouard  1290: #include <unistd.h>
1.159     brouard  1291: #endif
1.126     brouard  1292: 
                   1293: #include <limits.h>
                   1294: #include <sys/types.h>
1.171     brouard  1295: 
                   1296: #if defined(__GNUC__)
                   1297: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1298: #endif
                   1299: 
1.126     brouard  1300: #include <sys/stat.h>
                   1301: #include <errno.h>
1.159     brouard  1302: /* extern int errno; */
1.126     brouard  1303: 
1.157     brouard  1304: /* #ifdef LINUX */
                   1305: /* #include <time.h> */
                   1306: /* #include "timeval.h" */
                   1307: /* #else */
                   1308: /* #include <sys/time.h> */
                   1309: /* #endif */
                   1310: 
1.126     brouard  1311: #include <time.h>
                   1312: 
1.136     brouard  1313: #ifdef GSL
                   1314: #include <gsl/gsl_errno.h>
                   1315: #include <gsl/gsl_multimin.h>
                   1316: #endif
                   1317: 
1.167     brouard  1318: 
1.162     brouard  1319: #ifdef NLOPT
                   1320: #include <nlopt.h>
                   1321: typedef struct {
                   1322:   double (* function)(double [] );
                   1323: } myfunc_data ;
                   1324: #endif
                   1325: 
1.126     brouard  1326: /* #include <libintl.h> */
                   1327: /* #define _(String) gettext (String) */
                   1328: 
1.349     brouard  1329: #define MAXLINE 16384 /* Was 256 and 1024 and 2048. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1330: 
                   1331: #define GNUPLOTPROGRAM "gnuplot"
1.343     brouard  1332: #define GNUPLOTVERSION 5.1
                   1333: double gnuplotversion=GNUPLOTVERSION;
1.126     brouard  1334: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1335: #define FILENAMELENGTH 256
1.126     brouard  1336: 
                   1337: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1338: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1339: 
1.349     brouard  1340: #define MAXPARM 216 /**< Maximum number of parameters for the optimization was 128 */
1.144     brouard  1341: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1342: 
                   1343: #define NINTERVMAX 8
1.144     brouard  1344: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1345: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1346: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1347: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1348: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1349: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1350: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1351: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1352: /* #define AGESUP 130 */
1.288     brouard  1353: /* #define AGESUP 150 */
                   1354: #define AGESUP 200
1.268     brouard  1355: #define AGEINF 0
1.218     brouard  1356: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1357: #define AGEBASE 40
1.194     brouard  1358: #define AGEOVERFLOW 1.e20
1.164     brouard  1359: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1360: #ifdef _WIN32
                   1361: #define DIRSEPARATOR '\\'
                   1362: #define CHARSEPARATOR "\\"
                   1363: #define ODIRSEPARATOR '/'
                   1364: #else
1.126     brouard  1365: #define DIRSEPARATOR '/'
                   1366: #define CHARSEPARATOR "/"
                   1367: #define ODIRSEPARATOR '\\'
                   1368: #endif
                   1369: 
1.353   ! brouard  1370: /* $Id: imach.c,v 1.352 2023/04/29 10:46:21 brouard Exp $ */
1.126     brouard  1371: /* $State: Exp $ */
1.196     brouard  1372: #include "version.h"
                   1373: char version[]=__IMACH_VERSION__;
1.352     brouard  1374: 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.353   ! brouard  1375: char fullversion[]="$Revision: 1.352 $ $Date: 2023/04/29 10:46:21 $"; 
1.126     brouard  1376: char strstart[80];
                   1377: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1378: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.342     brouard  1379: int debugILK=0; /* debugILK is set by a #d in a comment line */
1.187     brouard  1380: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1381: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1382: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
1.335     brouard  1383: 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  1384: 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  1385: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1386: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1387: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
1.349     brouard  1388: int cptcovprodage=0; /**< Number of fixed covariates with age: V3*age or V2*V3*age 1 */
                   1389: int cptcovprodvage=0; /**< Number of varying covariates with age: V7*age or V7*V6*age */
                   1390: int cptcovdageprod=0; /**< Number of doubleproducts with age, since 0.99r44 only: age*Vn*Vm for gnuplot printing*/
1.145     brouard  1391: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335     brouard  1392: 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  1393: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1394: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.339     brouard  1395: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
1.349     brouard  1396: 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 */
                   1397: 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 */
                   1398: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (single or product, dummy or quantitative) in the model */
                   1399: 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  1400: int nsd=0; /**< Total number of single dummy variables (output) */
                   1401: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1402: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1403: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1404: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1405: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1406: int cptcov=0; /* Working variable */
1.334     brouard  1407: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1408: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1409: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1410: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1411: int nlstate=2; /* Number of live states */
                   1412: int ndeath=1; /* Number of dead states */
1.130     brouard  1413: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.339     brouard  1414: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
                   1415: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
1.126     brouard  1416: int popbased=0;
                   1417: 
                   1418: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1419: int maxwav=0; /* Maxim number of waves */
                   1420: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1421: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1422: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1423:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1424: int mle=1, weightopt=0;
1.126     brouard  1425: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1426: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1427: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1428:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1429: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1430: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1431: 
1.130     brouard  1432: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1433: double **matprod2(); /* test */
1.126     brouard  1434: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1435: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1436: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1437: 
1.136     brouard  1438: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1439: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1440: FILE *ficlog, *ficrespow;
1.130     brouard  1441: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1442: double fretone; /* Only one call to likelihood */
1.130     brouard  1443: long ipmx=0; /* Number of contributions */
1.126     brouard  1444: double sw; /* Sum of weights */
                   1445: char filerespow[FILENAMELENGTH];
                   1446: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1447: FILE *ficresilk;
                   1448: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1449: FILE *ficresprobmorprev;
                   1450: FILE *fichtm, *fichtmcov; /* Html File */
                   1451: FILE *ficreseij;
                   1452: char filerese[FILENAMELENGTH];
                   1453: FILE *ficresstdeij;
                   1454: char fileresstde[FILENAMELENGTH];
                   1455: FILE *ficrescveij;
                   1456: char filerescve[FILENAMELENGTH];
                   1457: FILE  *ficresvij;
                   1458: char fileresv[FILENAMELENGTH];
1.269     brouard  1459: 
1.126     brouard  1460: char title[MAXLINE];
1.234     brouard  1461: char model[MAXLINE]; /**< The model line */
1.217     brouard  1462: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1463: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1464: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1465: char command[FILENAMELENGTH];
                   1466: int  outcmd=0;
                   1467: 
1.217     brouard  1468: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1469: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1470: char filelog[FILENAMELENGTH]; /* Log file */
                   1471: char filerest[FILENAMELENGTH];
                   1472: char fileregp[FILENAMELENGTH];
                   1473: char popfile[FILENAMELENGTH];
                   1474: 
                   1475: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1476: 
1.157     brouard  1477: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1478: /* struct timezone tzp; */
                   1479: /* extern int gettimeofday(); */
                   1480: struct tm tml, *gmtime(), *localtime();
                   1481: 
                   1482: extern time_t time();
                   1483: 
                   1484: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1485: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
1.349     brouard  1486: time_t   rlast_btime; /* raw time */
1.157     brouard  1487: struct tm tm;
                   1488: 
1.126     brouard  1489: char strcurr[80], strfor[80];
                   1490: 
                   1491: char *endptr;
                   1492: long lval;
                   1493: double dval;
                   1494: 
                   1495: #define NR_END 1
                   1496: #define FREE_ARG char*
                   1497: #define FTOL 1.0e-10
                   1498: 
                   1499: #define NRANSI 
1.240     brouard  1500: #define ITMAX 200
                   1501: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1502: 
                   1503: #define TOL 2.0e-4 
                   1504: 
                   1505: #define CGOLD 0.3819660 
                   1506: #define ZEPS 1.0e-10 
                   1507: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1508: 
                   1509: #define GOLD 1.618034 
                   1510: #define GLIMIT 100.0 
                   1511: #define TINY 1.0e-20 
                   1512: 
                   1513: static double maxarg1,maxarg2;
                   1514: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1515: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1516:   
                   1517: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1518: #define rint(a) floor(a+0.5)
1.166     brouard  1519: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1520: #define mytinydouble 1.0e-16
1.166     brouard  1521: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1522: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1523: /* static double dsqrarg; */
                   1524: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1525: static double sqrarg;
                   1526: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1527: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1528: int agegomp= AGEGOMP;
                   1529: 
                   1530: int imx; 
                   1531: int stepm=1;
                   1532: /* Stepm, step in month: minimum step interpolation*/
                   1533: 
                   1534: int estepm;
                   1535: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1536: 
                   1537: int m,nb;
                   1538: long *num;
1.197     brouard  1539: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1540: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1541:                   covariate for which somebody answered excluding 
                   1542:                   undefined. Usually 2: 0 and 1. */
                   1543: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1544:                             covariate for which somebody answered including 
                   1545:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1546: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1547: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1548: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1549: 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  1550: double *ageexmed,*agecens;
                   1551: double dateintmean=0;
1.296     brouard  1552:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1553:   double anprojf, mprojf, jprojf;
1.126     brouard  1554: 
1.296     brouard  1555:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1556:   double anbackf, mbackf, jbackf;
                   1557:   double jintmean,mintmean,aintmean;  
1.126     brouard  1558: double *weight;
                   1559: int **s; /* Status */
1.141     brouard  1560: double *agedc;
1.145     brouard  1561: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1562:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1563:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1564: double **coqvar; /* Fixed quantitative covariate nqv */
1.341     brouard  1565: double ***cotvar; /* Time varying covariate start at ncovcol + nqv + (1 to ntv) */
1.225     brouard  1566: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1567: double  idx; 
                   1568: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1569: /* Some documentation */
                   1570:       /*   Design original data
                   1571:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1572:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1573:        *                                                             ntv=3     nqtv=1
1.330     brouard  1574:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1575:        * For time varying covariate, quanti or dummies
                   1576:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
1.341     brouard  1577:        *       cotvar[wav][ncovcol+nqv+ iv(1 to nqtv)][i]= [(1 to nqtv)][i]=(V12) quanti
1.319     brouard  1578:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1579:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1580:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1581:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1582:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1583:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1584:        */
                   1585: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1586: /* 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
                   1587:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1588:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1589: */
1.349     brouard  1590: /*           V5+V4+ V3+V4*V3 +V5*age+V2 +V1*V2+V1*age+V1+V4*V3*age */
                   1591: /*    kmodel  1  2   3    4     5     6    7     8     9    10 */
                   1592: /*Typevar[k]=  0  0   0   2     1    0    2     1     0    3 *//*0 for simple covariate (dummy, quantitative,*/
                   1593:                                                                /* fixed or varying), 1 for age product, 2 for*/
                   1594:                                                                /* product without age, 3 for age and double product   */
                   1595: /*Dummy[k]=    1  0   0   1     3    1    1     2     0     3  *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1596:                                                                 /*(single or product without age), 2 dummy*/
                   1597:                                                                /* with age product, 3 quant with age product*/
                   1598: /*Tvar[k]=     5  4   3   6     5    2    7     1     1     6 */
                   1599: /*    nsd         1   2                               3 */ /* Counting single dummies covar fixed or tv */
                   1600: /*TnsdVar[Tvar]   1   2                               3 */ 
                   1601: /*Tvaraff[nsd]    4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1602: /*TvarsD[nsd]     4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1603: /*TvarsDind[nsd]  2   3                               9 */ /* position K of single dummy cova */
                   1604: /*    nsq      1                     2                  */ /* Counting single quantit tv */
                   1605: /* TvarsQ[k]   5                     2                  */ /* Number of single quantitative cova */
                   1606: /* TvarsQind   1                     6                  */ /* position K of single quantitative cova */
                   1607: /* Tprod[i]=k             1               2             */ /* Position in model of the ith prod without age */
                   1608: /* cptcovage                    1               2         3 */ /* Counting cov*age in the model equation */
                   1609: /* Tage[cptcovage]=k            5               8         10 */ /* Position in the model of ith cov*age */
1.350     brouard  1610: /* 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"*/
                   1611: /*  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}*/
                   1612: /*  p Tvard[2][1]@21 = {7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0 <repeats 11 times>}
                   1613: /* 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}*/
                   1614: /* 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  1615: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2               */ /* Position in model of the ith prod without age */
1.330     brouard  1616: /* 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  1617: /* 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  1618: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1619: /* Type                    */
                   1620: /* V         1  2  3  4  5 */
                   1621: /*           F  F  V  V  V */
                   1622: /*           D  Q  D  D  Q */
                   1623: /*                         */
                   1624: int *TvarsD;
1.330     brouard  1625: int *TnsdVar;
1.234     brouard  1626: int *TvarsDind;
                   1627: int *TvarsQ;
                   1628: int *TvarsQind;
                   1629: 
1.318     brouard  1630: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1631: int nresult=0;
1.258     brouard  1632: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1633: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1634: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1635: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1636: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1637: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1638: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1639: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1640: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1641: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1642: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1643: 
                   1644: /* 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
                   1645:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1646:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1647: */
1.234     brouard  1648: /* 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  1649: 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 */
                   1650: 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 */
                   1651: 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 */
                   1652: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1653: 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 */
                   1654: 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  1655: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1656: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1657: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1658: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1659: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1660: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1661: 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 */
                   1662: 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  1663: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1664: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
1.349     brouard  1665: int *TvarVVA; /* We count ncovvt time varying covariates (single or products with age) and put their name into TvarVVA */
                   1666: int *TvarVVAind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1667: int *TvarAVVA; /* We count ALL ncovta time varying covariates (single or products with age) and put their name into TvarVVA */
                   1668: int *TvarAVVAind; /* We count ALL ncovta time varying covariates (single or products without age) and put their name into TvarVV */
1.339     brouard  1669:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  1670:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age */
                   1671:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   1672:       /* TvarVV={3,1,3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */        
                   1673:       /* 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  1674: int *Tvarsel; /**< Selected covariates for output */
                   1675: double *Tvalsel; /**< Selected modality value of covariate for output */
1.349     brouard  1676: 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  1677: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1678: 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  1679: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1680: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1681: int *Tage;
1.227     brouard  1682: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1683: 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  1684: 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*/ 
                   1685: 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  1686: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1687: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1688: int **Tvard;
1.330     brouard  1689: int **Tvardk;
1.227     brouard  1690: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1691: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1692: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1693:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1694:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1695: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1696: double *lsurv, *lpop, *tpop;
                   1697: 
1.231     brouard  1698: #define FD 1; /* Fixed dummy covariate */
                   1699: #define FQ 2; /* Fixed quantitative covariate */
                   1700: #define FP 3; /* Fixed product covariate */
                   1701: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1702: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1703: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1704: #define VD 10; /* Varying dummy covariate */
                   1705: #define VQ 11; /* Varying quantitative covariate */
                   1706: #define VP 12; /* Varying product covariate */
                   1707: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1708: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1709: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1710: #define APFD 16; /* Age product * fixed dummy covariate */
                   1711: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1712: #define APVD 18; /* Age product * varying dummy covariate */
                   1713: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1714: 
                   1715: #define FTYPE 1; /* Fixed covariate */
                   1716: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1717: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1718: 
                   1719: struct kmodel{
                   1720:        int maintype; /* main type */
                   1721:        int subtype; /* subtype */
                   1722: };
                   1723: struct kmodel modell[NCOVMAX];
                   1724: 
1.143     brouard  1725: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1726: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1727: 
                   1728: /**************** split *************************/
                   1729: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1730: {
                   1731:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1732:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1733:   */ 
                   1734:   char *ss;                            /* pointer */
1.186     brouard  1735:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1736: 
                   1737:   l1 = strlen(path );                  /* length of path */
                   1738:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1739:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1740:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1741:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1742:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1743:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1744:     /* get current working directory */
                   1745:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1746: #ifdef WIN32
                   1747:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1748: #else
                   1749:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1750: #endif
1.126     brouard  1751:       return( GLOCK_ERROR_GETCWD );
                   1752:     }
                   1753:     /* got dirc from getcwd*/
                   1754:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1755:   } else {                             /* strip directory from path */
1.126     brouard  1756:     ss++;                              /* after this, the filename */
                   1757:     l2 = strlen( ss );                 /* length of filename */
                   1758:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1759:     strcpy( name, ss );                /* save file name */
                   1760:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1761:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1762:     printf(" DIRC2 = %s \n",dirc);
                   1763:   }
                   1764:   /* We add a separator at the end of dirc if not exists */
                   1765:   l1 = strlen( dirc );                 /* length of directory */
                   1766:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1767:     dirc[l1] =  DIRSEPARATOR;
                   1768:     dirc[l1+1] = 0; 
                   1769:     printf(" DIRC3 = %s \n",dirc);
                   1770:   }
                   1771:   ss = strrchr( name, '.' );           /* find last / */
                   1772:   if (ss >0){
                   1773:     ss++;
                   1774:     strcpy(ext,ss);                    /* save extension */
                   1775:     l1= strlen( name);
                   1776:     l2= strlen(ss)+1;
                   1777:     strncpy( finame, name, l1-l2);
                   1778:     finame[l1-l2]= 0;
                   1779:   }
                   1780: 
                   1781:   return( 0 );                         /* we're done */
                   1782: }
                   1783: 
                   1784: 
                   1785: /******************************************/
                   1786: 
                   1787: void replace_back_to_slash(char *s, char*t)
                   1788: {
                   1789:   int i;
                   1790:   int lg=0;
                   1791:   i=0;
                   1792:   lg=strlen(t);
                   1793:   for(i=0; i<= lg; i++) {
                   1794:     (s[i] = t[i]);
                   1795:     if (t[i]== '\\') s[i]='/';
                   1796:   }
                   1797: }
                   1798: 
1.132     brouard  1799: char *trimbb(char *out, char *in)
1.137     brouard  1800: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1801:   char *s;
                   1802:   s=out;
                   1803:   while (*in != '\0'){
1.137     brouard  1804:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1805:       in++;
                   1806:     }
                   1807:     *out++ = *in++;
                   1808:   }
                   1809:   *out='\0';
                   1810:   return s;
                   1811: }
                   1812: 
1.351     brouard  1813: char *trimbtab(char *out, char *in)
                   1814: { /* Trim  blanks or tabs in line but keeps first blanks if line starts with blanks */
                   1815:   char *s;
                   1816:   s=out;
                   1817:   while (*in != '\0'){
                   1818:     while( (*in == ' ' || *in == '\t')){ /* && *(in+1) != '\0'){*/
                   1819:       in++;
                   1820:     }
                   1821:     *out++ = *in++;
                   1822:   }
                   1823:   *out='\0';
                   1824:   return s;
                   1825: }
                   1826: 
1.187     brouard  1827: /* char *substrchaine(char *out, char *in, char *chain) */
                   1828: /* { */
                   1829: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1830: /*   char *s, *t; */
                   1831: /*   t=in;s=out; */
                   1832: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1833: /*     *out++ = *in++; */
                   1834: /*   } */
                   1835: 
                   1836: /*   /\* *in matches *chain *\/ */
                   1837: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1838: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1839: /*   } */
                   1840: /*   in--; chain--; */
                   1841: /*   while ( (*in != '\0')){ */
                   1842: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1843: /*     *out++ = *in++; */
                   1844: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1845: /*   } */
                   1846: /*   *out='\0'; */
                   1847: /*   out=s; */
                   1848: /*   return out; */
                   1849: /* } */
                   1850: char *substrchaine(char *out, char *in, char *chain)
                   1851: {
                   1852:   /* Substract chain 'chain' from 'in', return and output 'out' */
1.349     brouard  1853:   /* in="V1+V1*age+age*age+V2", chain="+age*age" out="V1+V1*age+V2" */
1.187     brouard  1854: 
                   1855:   char *strloc;
                   1856: 
1.349     brouard  1857:   strcpy (out, in);                   /* out="V1+V1*age+age*age+V2" */
                   1858:   strloc = strstr(out, chain); /* strloc points to out at "+age*age+V2"  */
                   1859:   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  1860:   if(strloc != NULL){ 
1.349     brouard  1861:     /* will affect out */ /* strloc+strlen(chain)=|+V2 = "V1+V1*age+age*age|+V2" */ /* Will also work in Unicodek */
                   1862:     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)*/
                   1863:     /* equivalent to strcpy (strloc, strloc +strlen(chain)) if no overlap; Copies from "+V2" to V1+V1*age+ */
1.187     brouard  1864:   }
1.349     brouard  1865:   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  1866:   return out;
                   1867: }
                   1868: 
                   1869: 
1.145     brouard  1870: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1871: {
1.187     brouard  1872:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.349     brouard  1873:      and alocc starts after first occurence of char 'occ' : ex cutl(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1874:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1875:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1876:   */
1.160     brouard  1877:   char *s, *t;
1.145     brouard  1878:   t=in;s=in;
                   1879:   while ((*in != occ) && (*in != '\0')){
                   1880:     *alocc++ = *in++;
                   1881:   }
                   1882:   if( *in == occ){
                   1883:     *(alocc)='\0';
                   1884:     s=++in;
                   1885:   }
                   1886:  
                   1887:   if (s == t) {/* occ not found */
                   1888:     *(alocc-(in-s))='\0';
                   1889:     in=s;
                   1890:   }
                   1891:   while ( *in != '\0'){
                   1892:     *blocc++ = *in++;
                   1893:   }
                   1894: 
                   1895:   *blocc='\0';
                   1896:   return t;
                   1897: }
1.137     brouard  1898: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1899: {
1.187     brouard  1900:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1901:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1902:      gives blocc="abcdef2ghi" and alocc="j".
                   1903:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1904:   */
                   1905:   char *s, *t;
                   1906:   t=in;s=in;
                   1907:   while (*in != '\0'){
                   1908:     while( *in == occ){
                   1909:       *blocc++ = *in++;
                   1910:       s=in;
                   1911:     }
                   1912:     *blocc++ = *in++;
                   1913:   }
                   1914:   if (s == t) /* occ not found */
                   1915:     *(blocc-(in-s))='\0';
                   1916:   else
                   1917:     *(blocc-(in-s)-1)='\0';
                   1918:   in=s;
                   1919:   while ( *in != '\0'){
                   1920:     *alocc++ = *in++;
                   1921:   }
                   1922: 
                   1923:   *alocc='\0';
                   1924:   return s;
                   1925: }
                   1926: 
1.126     brouard  1927: int nbocc(char *s, char occ)
                   1928: {
                   1929:   int i,j=0;
                   1930:   int lg=20;
                   1931:   i=0;
                   1932:   lg=strlen(s);
                   1933:   for(i=0; i<= lg; i++) {
1.234     brouard  1934:     if  (s[i] == occ ) j++;
1.126     brouard  1935:   }
                   1936:   return j;
                   1937: }
                   1938: 
1.349     brouard  1939: int nboccstr(char *textin, char *chain)
                   1940: {
                   1941:   /* Counts the number of occurence of "chain"  in string textin */
                   1942:   /*  in="+V7*V4+age*V2+age*V3+age*V4"  chain="age" */
                   1943:   char *strloc;
                   1944:   
                   1945:   int i,j=0;
                   1946: 
                   1947:   i=0;
                   1948: 
                   1949:   strloc=textin; /* strloc points to "^+V7*V4+age+..." in textin */
                   1950:   for(;;) {
                   1951:     strloc= strstr(strloc,chain); /* strloc points to first character of chain in textin if found. Example strloc points^ to "+V7*V4+^age" in textin  */
                   1952:     if(strloc != NULL){
                   1953:       strloc = strloc+strlen(chain); /* strloc points to "+V7*V4+age^" in textin */
                   1954:       j++;
                   1955:     }else
                   1956:       break;
                   1957:   }
                   1958:   return j;
                   1959:   
                   1960: }
1.137     brouard  1961: /* void cutv(char *u,char *v, char*t, char occ) */
                   1962: /* { */
                   1963: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1964: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1965: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1966: /*   int i,lg,j,p=0; */
                   1967: /*   i=0; */
                   1968: /*   lg=strlen(t); */
                   1969: /*   for(j=0; j<=lg-1; j++) { */
                   1970: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1971: /*   } */
1.126     brouard  1972: 
1.137     brouard  1973: /*   for(j=0; j<p; j++) { */
                   1974: /*     (u[j] = t[j]); */
                   1975: /*   } */
                   1976: /*      u[p]='\0'; */
1.126     brouard  1977: 
1.137     brouard  1978: /*    for(j=0; j<= lg; j++) { */
                   1979: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1980: /*   } */
                   1981: /* } */
1.126     brouard  1982: 
1.160     brouard  1983: #ifdef _WIN32
                   1984: char * strsep(char **pp, const char *delim)
                   1985: {
                   1986:   char *p, *q;
                   1987:          
                   1988:   if ((p = *pp) == NULL)
                   1989:     return 0;
                   1990:   if ((q = strpbrk (p, delim)) != NULL)
                   1991:   {
                   1992:     *pp = q + 1;
                   1993:     *q = '\0';
                   1994:   }
                   1995:   else
                   1996:     *pp = 0;
                   1997:   return p;
                   1998: }
                   1999: #endif
                   2000: 
1.126     brouard  2001: /********************** nrerror ********************/
                   2002: 
                   2003: void nrerror(char error_text[])
                   2004: {
                   2005:   fprintf(stderr,"ERREUR ...\n");
                   2006:   fprintf(stderr,"%s\n",error_text);
                   2007:   exit(EXIT_FAILURE);
                   2008: }
                   2009: /*********************** vector *******************/
                   2010: double *vector(int nl, int nh)
                   2011: {
                   2012:   double *v;
                   2013:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   2014:   if (!v) nrerror("allocation failure in vector");
                   2015:   return v-nl+NR_END;
                   2016: }
                   2017: 
                   2018: /************************ free vector ******************/
                   2019: void free_vector(double*v, int nl, int nh)
                   2020: {
                   2021:   free((FREE_ARG)(v+nl-NR_END));
                   2022: }
                   2023: 
                   2024: /************************ivector *******************************/
                   2025: int *ivector(long nl,long nh)
                   2026: {
                   2027:   int *v;
                   2028:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   2029:   if (!v) nrerror("allocation failure in ivector");
                   2030:   return v-nl+NR_END;
                   2031: }
                   2032: 
                   2033: /******************free ivector **************************/
                   2034: void free_ivector(int *v, long nl, long nh)
                   2035: {
                   2036:   free((FREE_ARG)(v+nl-NR_END));
                   2037: }
                   2038: 
                   2039: /************************lvector *******************************/
                   2040: long *lvector(long nl,long nh)
                   2041: {
                   2042:   long *v;
                   2043:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   2044:   if (!v) nrerror("allocation failure in ivector");
                   2045:   return v-nl+NR_END;
                   2046: }
                   2047: 
                   2048: /******************free lvector **************************/
                   2049: void free_lvector(long *v, long nl, long nh)
                   2050: {
                   2051:   free((FREE_ARG)(v+nl-NR_END));
                   2052: }
                   2053: 
                   2054: /******************* imatrix *******************************/
                   2055: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   2056:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   2057: { 
                   2058:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   2059:   int **m; 
                   2060:   
                   2061:   /* allocate pointers to rows */ 
                   2062:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   2063:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   2064:   m += NR_END; 
                   2065:   m -= nrl; 
                   2066:   
                   2067:   
                   2068:   /* allocate rows and set pointers to them */ 
                   2069:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   2070:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   2071:   m[nrl] += NR_END; 
                   2072:   m[nrl] -= ncl; 
                   2073:   
                   2074:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   2075:   
                   2076:   /* return pointer to array of pointers to rows */ 
                   2077:   return m; 
                   2078: } 
                   2079: 
                   2080: /****************** free_imatrix *************************/
                   2081: void free_imatrix(m,nrl,nrh,ncl,nch)
                   2082:       int **m;
                   2083:       long nch,ncl,nrh,nrl; 
                   2084:      /* free an int matrix allocated by imatrix() */ 
                   2085: { 
                   2086:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   2087:   free((FREE_ARG) (m+nrl-NR_END)); 
                   2088: } 
                   2089: 
                   2090: /******************* matrix *******************************/
                   2091: double **matrix(long nrl, long nrh, long ncl, long nch)
                   2092: {
                   2093:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   2094:   double **m;
                   2095: 
                   2096:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2097:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2098:   m += NR_END;
                   2099:   m -= nrl;
                   2100: 
                   2101:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2102:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2103:   m[nrl] += NR_END;
                   2104:   m[nrl] -= ncl;
                   2105: 
                   2106:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2107:   return m;
1.145     brouard  2108:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   2109: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   2110: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  2111:    */
                   2112: }
                   2113: 
                   2114: /*************************free matrix ************************/
                   2115: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   2116: {
                   2117:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2118:   free((FREE_ARG)(m+nrl-NR_END));
                   2119: }
                   2120: 
                   2121: /******************* ma3x *******************************/
                   2122: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   2123: {
                   2124:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   2125:   double ***m;
                   2126: 
                   2127:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2128:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2129:   m += NR_END;
                   2130:   m -= nrl;
                   2131: 
                   2132:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2133:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2134:   m[nrl] += NR_END;
                   2135:   m[nrl] -= ncl;
                   2136: 
                   2137:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2138: 
                   2139:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   2140:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2141:   m[nrl][ncl] += NR_END;
                   2142:   m[nrl][ncl] -= nll;
                   2143:   for (j=ncl+1; j<=nch; j++) 
                   2144:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2145:   
                   2146:   for (i=nrl+1; i<=nrh; i++) {
                   2147:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2148:     for (j=ncl+1; j<=nch; j++) 
                   2149:       m[i][j]=m[i][j-1]+nlay;
                   2150:   }
                   2151:   return m; 
                   2152:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2153:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2154:   */
                   2155: }
                   2156: 
                   2157: /*************************free ma3x ************************/
                   2158: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2159: {
                   2160:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2161:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2162:   free((FREE_ARG)(m+nrl-NR_END));
                   2163: }
                   2164: 
                   2165: /*************** function subdirf ***********/
                   2166: char *subdirf(char fileres[])
                   2167: {
                   2168:   /* Caution optionfilefiname is hidden */
                   2169:   strcpy(tmpout,optionfilefiname);
                   2170:   strcat(tmpout,"/"); /* Add to the right */
                   2171:   strcat(tmpout,fileres);
                   2172:   return tmpout;
                   2173: }
                   2174: 
                   2175: /*************** function subdirf2 ***********/
                   2176: char *subdirf2(char fileres[], char *preop)
                   2177: {
1.314     brouard  2178:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2179:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2180:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2181:   /* Caution optionfilefiname is hidden */
                   2182:   strcpy(tmpout,optionfilefiname);
                   2183:   strcat(tmpout,"/");
                   2184:   strcat(tmpout,preop);
                   2185:   strcat(tmpout,fileres);
                   2186:   return tmpout;
                   2187: }
                   2188: 
                   2189: /*************** function subdirf3 ***********/
                   2190: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2191: {
                   2192:   
                   2193:   /* Caution optionfilefiname is hidden */
                   2194:   strcpy(tmpout,optionfilefiname);
                   2195:   strcat(tmpout,"/");
                   2196:   strcat(tmpout,preop);
                   2197:   strcat(tmpout,preop2);
                   2198:   strcat(tmpout,fileres);
                   2199:   return tmpout;
                   2200: }
1.213     brouard  2201:  
                   2202: /*************** function subdirfext ***********/
                   2203: char *subdirfext(char fileres[], char *preop, char *postop)
                   2204: {
                   2205:   
                   2206:   strcpy(tmpout,preop);
                   2207:   strcat(tmpout,fileres);
                   2208:   strcat(tmpout,postop);
                   2209:   return tmpout;
                   2210: }
1.126     brouard  2211: 
1.213     brouard  2212: /*************** function subdirfext3 ***********/
                   2213: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2214: {
                   2215:   
                   2216:   /* Caution optionfilefiname is hidden */
                   2217:   strcpy(tmpout,optionfilefiname);
                   2218:   strcat(tmpout,"/");
                   2219:   strcat(tmpout,preop);
                   2220:   strcat(tmpout,fileres);
                   2221:   strcat(tmpout,postop);
                   2222:   return tmpout;
                   2223: }
                   2224:  
1.162     brouard  2225: char *asc_diff_time(long time_sec, char ascdiff[])
                   2226: {
                   2227:   long sec_left, days, hours, minutes;
                   2228:   days = (time_sec) / (60*60*24);
                   2229:   sec_left = (time_sec) % (60*60*24);
                   2230:   hours = (sec_left) / (60*60) ;
                   2231:   sec_left = (sec_left) %(60*60);
                   2232:   minutes = (sec_left) /60;
                   2233:   sec_left = (sec_left) % (60);
                   2234:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2235:   return ascdiff;
                   2236: }
                   2237: 
1.126     brouard  2238: /***************** f1dim *************************/
                   2239: extern int ncom; 
                   2240: extern double *pcom,*xicom;
                   2241: extern double (*nrfunc)(double []); 
                   2242:  
                   2243: double f1dim(double x) 
                   2244: { 
                   2245:   int j; 
                   2246:   double f;
                   2247:   double *xt; 
                   2248:  
                   2249:   xt=vector(1,ncom); 
                   2250:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2251:   f=(*nrfunc)(xt); 
                   2252:   free_vector(xt,1,ncom); 
                   2253:   return f; 
                   2254: } 
                   2255: 
                   2256: /*****************brent *************************/
                   2257: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2258: {
                   2259:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2260:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2261:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2262:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2263:    * returned function value. 
                   2264:   */
1.126     brouard  2265:   int iter; 
                   2266:   double a,b,d,etemp;
1.159     brouard  2267:   double fu=0,fv,fw,fx;
1.164     brouard  2268:   double ftemp=0.;
1.126     brouard  2269:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2270:   double e=0.0; 
                   2271:  
                   2272:   a=(ax < cx ? ax : cx); 
                   2273:   b=(ax > cx ? ax : cx); 
                   2274:   x=w=v=bx; 
                   2275:   fw=fv=fx=(*f)(x); 
                   2276:   for (iter=1;iter<=ITMAX;iter++) { 
                   2277:     xm=0.5*(a+b); 
                   2278:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2279:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2280:     printf(".");fflush(stdout);
                   2281:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2282: #ifdef DEBUGBRENT
1.126     brouard  2283:     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);
                   2284:     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);
                   2285:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2286: #endif
                   2287:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2288:       *xmin=x; 
                   2289:       return fx; 
                   2290:     } 
                   2291:     ftemp=fu;
                   2292:     if (fabs(e) > tol1) { 
                   2293:       r=(x-w)*(fx-fv); 
                   2294:       q=(x-v)*(fx-fw); 
                   2295:       p=(x-v)*q-(x-w)*r; 
                   2296:       q=2.0*(q-r); 
                   2297:       if (q > 0.0) p = -p; 
                   2298:       q=fabs(q); 
                   2299:       etemp=e; 
                   2300:       e=d; 
                   2301:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2302:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2303:       else { 
1.224     brouard  2304:                                d=p/q; 
                   2305:                                u=x+d; 
                   2306:                                if (u-a < tol2 || b-u < tol2) 
                   2307:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2308:       } 
                   2309:     } else { 
                   2310:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2311:     } 
                   2312:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2313:     fu=(*f)(u); 
                   2314:     if (fu <= fx) { 
                   2315:       if (u >= x) a=x; else b=x; 
                   2316:       SHFT(v,w,x,u) 
1.183     brouard  2317:       SHFT(fv,fw,fx,fu) 
                   2318:     } else { 
                   2319:       if (u < x) a=u; else b=u; 
                   2320:       if (fu <= fw || w == x) { 
1.224     brouard  2321:                                v=w; 
                   2322:                                w=u; 
                   2323:                                fv=fw; 
                   2324:                                fw=fu; 
1.183     brouard  2325:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2326:                                v=u; 
                   2327:                                fv=fu; 
1.183     brouard  2328:       } 
                   2329:     } 
1.126     brouard  2330:   } 
                   2331:   nrerror("Too many iterations in brent"); 
                   2332:   *xmin=x; 
                   2333:   return fx; 
                   2334: } 
                   2335: 
                   2336: /****************** mnbrak ***********************/
                   2337: 
                   2338: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2339:            double (*func)(double)) 
1.183     brouard  2340: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2341: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2342: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2343: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2344:    */
1.126     brouard  2345:   double ulim,u,r,q, dum;
                   2346:   double fu; 
1.187     brouard  2347: 
                   2348:   double scale=10.;
                   2349:   int iterscale=0;
                   2350: 
                   2351:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2352:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2353: 
                   2354: 
                   2355:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2356:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2357:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2358:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2359:   /* } */
                   2360: 
1.126     brouard  2361:   if (*fb > *fa) { 
                   2362:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2363:     SHFT(dum,*fb,*fa,dum) 
                   2364:   } 
1.126     brouard  2365:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2366:   *fc=(*func)(*cx); 
1.183     brouard  2367: #ifdef DEBUG
1.224     brouard  2368:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2369:   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  2370: #endif
1.224     brouard  2371:   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  2372:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2373:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2374:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2375:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2376:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2377:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2378:       fu=(*func)(u); 
1.163     brouard  2379: #ifdef DEBUG
                   2380:       /* f(x)=A(x-u)**2+f(u) */
                   2381:       double A, fparabu; 
                   2382:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2383:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2384:       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);
                   2385:       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  2386:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2387:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2388:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2389:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2390: #endif 
1.184     brouard  2391: #ifdef MNBRAKORIGINAL
1.183     brouard  2392: #else
1.191     brouard  2393: /*       if (fu > *fc) { */
                   2394: /* #ifdef DEBUG */
                   2395: /*       printf("mnbrak4  fu > fc \n"); */
                   2396: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2397: /* #endif */
                   2398: /*     /\* 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 *\\/  *\/ */
                   2399: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2400: /*     dum=u; /\* Shifting c and u *\/ */
                   2401: /*     u = *cx; */
                   2402: /*     *cx = dum; */
                   2403: /*     dum = fu; */
                   2404: /*     fu = *fc; */
                   2405: /*     *fc =dum; */
                   2406: /*       } else { /\* end *\/ */
                   2407: /* #ifdef DEBUG */
                   2408: /*       printf("mnbrak3  fu < fc \n"); */
                   2409: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2410: /* #endif */
                   2411: /*     dum=u; /\* Shifting c and u *\/ */
                   2412: /*     u = *cx; */
                   2413: /*     *cx = dum; */
                   2414: /*     dum = fu; */
                   2415: /*     fu = *fc; */
                   2416: /*     *fc =dum; */
                   2417: /*       } */
1.224     brouard  2418: #ifdef DEBUGMNBRAK
                   2419:                 double A, fparabu; 
                   2420:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2421:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2422:      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);
                   2423:      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  2424: #endif
1.191     brouard  2425:       dum=u; /* Shifting c and u */
                   2426:       u = *cx;
                   2427:       *cx = dum;
                   2428:       dum = fu;
                   2429:       fu = *fc;
                   2430:       *fc =dum;
1.183     brouard  2431: #endif
1.162     brouard  2432:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2433: #ifdef DEBUG
1.224     brouard  2434:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2435:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2436: #endif
1.126     brouard  2437:       fu=(*func)(u); 
                   2438:       if (fu < *fc) { 
1.183     brouard  2439: #ifdef DEBUG
1.224     brouard  2440:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2441:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2442: #endif
                   2443:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2444:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2445: #ifdef DEBUG
                   2446:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2447: #endif
                   2448:       } 
1.162     brouard  2449:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2450: #ifdef DEBUG
1.224     brouard  2451:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2452:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2453: #endif
1.126     brouard  2454:       u=ulim; 
                   2455:       fu=(*func)(u); 
1.183     brouard  2456:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2457: #ifdef DEBUG
1.224     brouard  2458:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2459:       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  2460: #endif
1.126     brouard  2461:       u=(*cx)+GOLD*(*cx-*bx); 
                   2462:       fu=(*func)(u); 
1.224     brouard  2463: #ifdef DEBUG
                   2464:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2465:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2466: #endif
1.183     brouard  2467:     } /* end tests */
1.126     brouard  2468:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2469:     SHFT(*fa,*fb,*fc,fu) 
                   2470: #ifdef DEBUG
1.224     brouard  2471:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2472:       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  2473: #endif
                   2474:   } /* 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  2475: } 
                   2476: 
                   2477: /*************** linmin ************************/
1.162     brouard  2478: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2479: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2480: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2481: the value of func at the returned location p . This is actually all accomplished by calling the
                   2482: routines mnbrak and brent .*/
1.126     brouard  2483: int ncom; 
                   2484: double *pcom,*xicom;
                   2485: double (*nrfunc)(double []); 
                   2486:  
1.224     brouard  2487: #ifdef LINMINORIGINAL
1.126     brouard  2488: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2489: #else
                   2490: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2491: #endif
1.126     brouard  2492: { 
                   2493:   double brent(double ax, double bx, double cx, 
                   2494:               double (*f)(double), double tol, double *xmin); 
                   2495:   double f1dim(double x); 
                   2496:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2497:              double *fc, double (*func)(double)); 
                   2498:   int j; 
                   2499:   double xx,xmin,bx,ax; 
                   2500:   double fx,fb,fa;
1.187     brouard  2501: 
1.203     brouard  2502: #ifdef LINMINORIGINAL
                   2503: #else
                   2504:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2505: #endif
                   2506:   
1.126     brouard  2507:   ncom=n; 
                   2508:   pcom=vector(1,n); 
                   2509:   xicom=vector(1,n); 
                   2510:   nrfunc=func; 
                   2511:   for (j=1;j<=n;j++) { 
                   2512:     pcom[j]=p[j]; 
1.202     brouard  2513:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2514:   } 
1.187     brouard  2515: 
1.203     brouard  2516: #ifdef LINMINORIGINAL
                   2517:   xx=1.;
                   2518: #else
                   2519:   axs=0.0;
                   2520:   xxs=1.;
                   2521:   do{
                   2522:     xx= xxs;
                   2523: #endif
1.187     brouard  2524:     ax=0.;
                   2525:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2526:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2527:     /* 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))   */
                   2528:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2529:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2530:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2531:     /* 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  2532: #ifdef LINMINORIGINAL
                   2533: #else
                   2534:     if (fx != fx){
1.224     brouard  2535:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2536:                        printf("|");
                   2537:                        fprintf(ficlog,"|");
1.203     brouard  2538: #ifdef DEBUGLINMIN
1.224     brouard  2539:                        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  2540: #endif
                   2541:     }
1.224     brouard  2542:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2543: #endif
                   2544:   
1.191     brouard  2545: #ifdef DEBUGLINMIN
                   2546:   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  2547:   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  2548: #endif
1.224     brouard  2549: #ifdef LINMINORIGINAL
                   2550: #else
1.317     brouard  2551:   if(fb == fx){ /* Flat function in the direction */
                   2552:     xmin=xx;
1.224     brouard  2553:     *flat=1;
1.317     brouard  2554:   }else{
1.224     brouard  2555:     *flat=0;
                   2556: #endif
                   2557:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2558:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2559:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2560:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2561:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2562:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2563: #ifdef DEBUG
1.224     brouard  2564:   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);
                   2565:   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);
                   2566: #endif
                   2567: #ifdef LINMINORIGINAL
                   2568: #else
                   2569:                        }
1.126     brouard  2570: #endif
1.191     brouard  2571: #ifdef DEBUGLINMIN
                   2572:   printf("linmin end ");
1.202     brouard  2573:   fprintf(ficlog,"linmin end ");
1.191     brouard  2574: #endif
1.126     brouard  2575:   for (j=1;j<=n;j++) { 
1.203     brouard  2576: #ifdef LINMINORIGINAL
                   2577:     xi[j] *= xmin; 
                   2578: #else
                   2579: #ifdef DEBUGLINMIN
                   2580:     if(xxs <1.0)
                   2581:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2582: #endif
                   2583:     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) */
                   2584: #ifdef DEBUGLINMIN
                   2585:     if(xxs <1.0)
                   2586:       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 );
                   2587: #endif
                   2588: #endif
1.187     brouard  2589:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2590:   } 
1.191     brouard  2591: #ifdef DEBUGLINMIN
1.203     brouard  2592:   printf("\n");
1.191     brouard  2593:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2594:   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  2595:   for (j=1;j<=n;j++) { 
1.202     brouard  2596:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2597:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2598:     if(j % ncovmodel == 0){
1.191     brouard  2599:       printf("\n");
1.202     brouard  2600:       fprintf(ficlog,"\n");
                   2601:     }
1.191     brouard  2602:   }
1.203     brouard  2603: #else
1.191     brouard  2604: #endif
1.126     brouard  2605:   free_vector(xicom,1,n); 
                   2606:   free_vector(pcom,1,n); 
                   2607: } 
                   2608: 
                   2609: 
                   2610: /*************** powell ************************/
1.162     brouard  2611: /*
1.317     brouard  2612: Minimization of a function func of n variables. Input consists in an initial starting point
                   2613: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2614: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2615: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2616: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2617: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2618:  */
1.224     brouard  2619: #ifdef LINMINORIGINAL
                   2620: #else
                   2621:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2622:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2623: #endif
1.126     brouard  2624: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2625:            double (*func)(double [])) 
                   2626: { 
1.224     brouard  2627: #ifdef LINMINORIGINAL
                   2628:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2629:              double (*func)(double [])); 
1.224     brouard  2630: #else 
1.241     brouard  2631:  void linmin(double p[], double xi[], int n, double *fret,
                   2632:             double (*func)(double []),int *flat); 
1.224     brouard  2633: #endif
1.239     brouard  2634:  int i,ibig,j,jk,k; 
1.126     brouard  2635:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2636:   double directest;
1.126     brouard  2637:   double fp,fptt;
                   2638:   double *xits;
                   2639:   int niterf, itmp;
1.349     brouard  2640:   int Bigter=0, nBigterf=1;
                   2641:   
1.126     brouard  2642:   pt=vector(1,n); 
                   2643:   ptt=vector(1,n); 
                   2644:   xit=vector(1,n); 
                   2645:   xits=vector(1,n); 
                   2646:   *fret=(*func)(p); 
                   2647:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.338     brouard  2648:   rcurr_time = time(NULL);
                   2649:   fp=(*fret); /* Initialisation */
1.126     brouard  2650:   for (*iter=1;;++(*iter)) { 
                   2651:     ibig=0; 
                   2652:     del=0.0; 
1.157     brouard  2653:     rlast_time=rcurr_time;
1.349     brouard  2654:     rlast_btime=rcurr_time;
1.157     brouard  2655:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2656:     rcurr_time = time(NULL);  
                   2657:     curr_time = *localtime(&rcurr_time);
1.337     brouard  2658:     /* 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); */
                   2659:     /* 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  2660:     Bigter=(*iter - *iter % ncovmodel)/ncovmodel +1; /* Big iteration, i.e on ncovmodel cycle */
                   2661:     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);
                   2662:     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);
                   2663:     fprintf(ficrespow,"%d %d %.12f %d",*iter,Bigter, *fret,curr_time.tm_sec-start_time.tm_sec);
1.324     brouard  2664:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2665:     for (i=1;i<=n;i++) {
1.126     brouard  2666:       fprintf(ficrespow," %.12lf", p[i]);
                   2667:     }
1.239     brouard  2668:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2669:     printf("\n#model=  1      +     age ");
                   2670:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2671:     if(nagesqr==1){
1.241     brouard  2672:        printf("  + age*age  ");
                   2673:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2674:     }
                   2675:     for(j=1;j <=ncovmodel-2;j++){
                   2676:       if(Typevar[j]==0) {
                   2677:        printf("  +      V%d  ",Tvar[j]);
                   2678:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2679:       }else if(Typevar[j]==1) {
                   2680:        printf("  +    V%d*age ",Tvar[j]);
                   2681:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2682:       }else if(Typevar[j]==2) {
                   2683:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2684:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  2685:       }else if(Typevar[j]==3) {
                   2686:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2687:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.239     brouard  2688:       }
                   2689:     }
1.126     brouard  2690:     printf("\n");
1.239     brouard  2691: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2692: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2693:     fprintf(ficlog,"\n");
1.239     brouard  2694:     for(i=1,jk=1; i <=nlstate; i++){
                   2695:       for(k=1; k <=(nlstate+ndeath); k++){
                   2696:        if (k != i) {
                   2697:          printf("%d%d ",i,k);
                   2698:          fprintf(ficlog,"%d%d ",i,k);
                   2699:          for(j=1; j <=ncovmodel; j++){
                   2700:            printf("%12.7f ",p[jk]);
                   2701:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2702:            jk++; 
                   2703:          }
                   2704:          printf("\n");
                   2705:          fprintf(ficlog,"\n");
                   2706:        }
                   2707:       }
                   2708:     }
1.241     brouard  2709:     if(*iter <=3 && *iter >1){
1.157     brouard  2710:       tml = *localtime(&rcurr_time);
                   2711:       strcpy(strcurr,asctime(&tml));
                   2712:       rforecast_time=rcurr_time; 
1.126     brouard  2713:       itmp = strlen(strcurr);
                   2714:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2715:        strcurr[itmp-1]='\0';
1.162     brouard  2716:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2717:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.349     brouard  2718:       for(nBigterf=1;nBigterf<=31;nBigterf+=10){
                   2719:        niterf=nBigterf*ncovmodel;
                   2720:        /* rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time); */
1.241     brouard  2721:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2722:        forecast_time = *localtime(&rforecast_time);
                   2723:        strcpy(strfor,asctime(&forecast_time));
                   2724:        itmp = strlen(strfor);
                   2725:        if(strfor[itmp-1]=='\n')
                   2726:          strfor[itmp-1]='\0';
1.349     brouard  2727:        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);
                   2728:        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  2729:       }
                   2730:     }
1.187     brouard  2731:     for (i=1;i<=n;i++) { /* For each direction i */
                   2732:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2733:       fptt=(*fret); 
                   2734: #ifdef DEBUG
1.203     brouard  2735:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2736:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2737: #endif
1.203     brouard  2738:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2739:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2740: #ifdef LINMINORIGINAL
1.188     brouard  2741:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2742: #else
                   2743:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2744:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2745: #endif
                   2746:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2747:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2748:                                /* because that direction will be replaced unless the gain del is small */
                   2749:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2750:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2751:                                /* with the new direction. */
                   2752:                                del=fabs(fptt-(*fret)); 
                   2753:                                ibig=i; 
1.126     brouard  2754:       } 
                   2755: #ifdef DEBUG
                   2756:       printf("%d %.12e",i,(*fret));
                   2757:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2758:       for (j=1;j<=n;j++) {
1.224     brouard  2759:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2760:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2761:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2762:       }
                   2763:       for(j=1;j<=n;j++) {
1.225     brouard  2764:                                printf(" p(%d)=%.12e",j,p[j]);
                   2765:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2766:       }
                   2767:       printf("\n");
                   2768:       fprintf(ficlog,"\n");
                   2769: #endif
1.187     brouard  2770:     } /* end loop on each direction i */
                   2771:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2772:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2773:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2774:     for(j=1;j<=n;j++) {
                   2775:       if(flatdir[j] >0){
                   2776:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2777:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2778:       }
1.319     brouard  2779:       /* printf("\n"); */
                   2780:       /* fprintf(ficlog,"\n"); */
                   2781:     }
1.243     brouard  2782:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2783:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2784:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2785:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2786:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2787:       /* decreased of more than 3.84  */
                   2788:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2789:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2790:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2791:                        
1.188     brouard  2792:       /* Starting the program with initial values given by a former maximization will simply change */
                   2793:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2794:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2795:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2796: #ifdef DEBUG
                   2797:       int k[2],l;
                   2798:       k[0]=1;
                   2799:       k[1]=-1;
                   2800:       printf("Max: %.12e",(*func)(p));
                   2801:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2802:       for (j=1;j<=n;j++) {
                   2803:        printf(" %.12e",p[j]);
                   2804:        fprintf(ficlog," %.12e",p[j]);
                   2805:       }
                   2806:       printf("\n");
                   2807:       fprintf(ficlog,"\n");
                   2808:       for(l=0;l<=1;l++) {
                   2809:        for (j=1;j<=n;j++) {
                   2810:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2811:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2812:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2813:        }
                   2814:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2815:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2816:       }
                   2817: #endif
                   2818: 
                   2819:       free_vector(xit,1,n); 
                   2820:       free_vector(xits,1,n); 
                   2821:       free_vector(ptt,1,n); 
                   2822:       free_vector(pt,1,n); 
                   2823:       return; 
1.192     brouard  2824:     } /* enough precision */ 
1.240     brouard  2825:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2826:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2827:       ptt[j]=2.0*p[j]-pt[j]; 
                   2828:       xit[j]=p[j]-pt[j]; 
                   2829:       pt[j]=p[j]; 
                   2830:     } 
1.181     brouard  2831:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2832: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2833:                if (*iter <=4) {
1.225     brouard  2834: #else
                   2835: #endif
1.224     brouard  2836: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2837: #else
1.161     brouard  2838:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2839: #endif
1.162     brouard  2840:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2841:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2842:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2843:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2844:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2845:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2846:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2847:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2848:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2849:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2850:       /* mu² and del² are equal when f3=f1 */
                   2851:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2852:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2853:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2854:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2855: #ifdef NRCORIGINAL
                   2856:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2857: #else
                   2858:       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  2859:       t= t- del*SQR(fp-fptt);
1.183     brouard  2860: #endif
1.202     brouard  2861:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2862: #ifdef DEBUG
1.181     brouard  2863:       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);
                   2864:       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  2865:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2866:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2867:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2868:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2869:       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);
                   2870:       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);
                   2871: #endif
1.183     brouard  2872: #ifdef POWELLORIGINAL
                   2873:       if (t < 0.0) { /* Then we use it for new direction */
                   2874: #else
1.182     brouard  2875:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2876:                                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  2877:         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  2878:         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  2879:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2880:       } 
1.181     brouard  2881:       if (directest < 0.0) { /* Then we use it for new direction */
                   2882: #endif
1.191     brouard  2883: #ifdef DEBUGLINMIN
1.234     brouard  2884:        printf("Before linmin in direction P%d-P0\n",n);
                   2885:        for (j=1;j<=n;j++) {
                   2886:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2887:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2888:          if(j % ncovmodel == 0){
                   2889:            printf("\n");
                   2890:            fprintf(ficlog,"\n");
                   2891:          }
                   2892:        }
1.224     brouard  2893: #endif
                   2894: #ifdef LINMINORIGINAL
1.234     brouard  2895:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2896: #else
1.234     brouard  2897:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2898:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2899: #endif
1.234     brouard  2900:        
1.191     brouard  2901: #ifdef DEBUGLINMIN
1.234     brouard  2902:        for (j=1;j<=n;j++) { 
                   2903:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2904:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2905:          if(j % ncovmodel == 0){
                   2906:            printf("\n");
                   2907:            fprintf(ficlog,"\n");
                   2908:          }
                   2909:        }
1.224     brouard  2910: #endif
1.234     brouard  2911:        for (j=1;j<=n;j++) { 
                   2912:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2913:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2914:        }
1.224     brouard  2915: #ifdef LINMINORIGINAL
                   2916: #else
1.234     brouard  2917:        for (j=1, flatd=0;j<=n;j++) {
                   2918:          if(flatdir[j]>0)
                   2919:            flatd++;
                   2920:        }
                   2921:        if(flatd >0){
1.255     brouard  2922:          printf("%d flat directions: ",flatd);
                   2923:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2924:          for (j=1;j<=n;j++) { 
                   2925:            if(flatdir[j]>0){
                   2926:              printf("%d ",j);
                   2927:              fprintf(ficlog,"%d ",j);
                   2928:            }
                   2929:          }
                   2930:          printf("\n");
                   2931:          fprintf(ficlog,"\n");
1.319     brouard  2932: #ifdef FLATSUP
                   2933:           free_vector(xit,1,n); 
                   2934:           free_vector(xits,1,n); 
                   2935:           free_vector(ptt,1,n); 
                   2936:           free_vector(pt,1,n); 
                   2937:           return;
                   2938: #endif
1.234     brouard  2939:        }
1.191     brouard  2940: #endif
1.234     brouard  2941:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2942:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2943:        
1.126     brouard  2944: #ifdef DEBUG
1.234     brouard  2945:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2946:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2947:        for(j=1;j<=n;j++){
                   2948:          printf(" %lf",xit[j]);
                   2949:          fprintf(ficlog," %lf",xit[j]);
                   2950:        }
                   2951:        printf("\n");
                   2952:        fprintf(ficlog,"\n");
1.126     brouard  2953: #endif
1.192     brouard  2954:       } /* end of t or directest negative */
1.224     brouard  2955: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2956: #else
1.234     brouard  2957:       } /* end if (fptt < fp)  */
1.192     brouard  2958: #endif
1.225     brouard  2959: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2960:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2961: #else
1.224     brouard  2962: #endif
1.234     brouard  2963:                } /* loop iteration */ 
1.126     brouard  2964: } 
1.234     brouard  2965:   
1.126     brouard  2966: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2967:   
1.235     brouard  2968:   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  2969:   {
1.338     brouard  2970:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
1.279     brouard  2971:      *   (and selected quantitative values in nres)
                   2972:      *  by left multiplying the unit
                   2973:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2974:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2975:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2976:      * or prevalence in state 1, prevalence in state 2, 0
                   2977:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2978:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2979:      * Output is prlim.
                   2980:      * Initial matrix pimij 
                   2981:      */
1.206     brouard  2982:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2983:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2984:   /*  0,                   0                  , 1} */
                   2985:   /*
                   2986:    * and after some iteration: */
                   2987:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2988:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2989:   /*  0,                   0                  , 1} */
                   2990:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2991:   /* {0.51571254859325999, 0.4842874514067399, */
                   2992:   /*  0.51326036147820708, 0.48673963852179264} */
                   2993:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2994:     
1.332     brouard  2995:     int i, ii,j,k, k1;
1.209     brouard  2996:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2997:   /* double **matprod2(); */ /* test */
1.218     brouard  2998:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2999:   double **newm;
1.209     brouard  3000:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  3001:   int ncvloop=0;
1.288     brouard  3002:   int first=0;
1.169     brouard  3003:   
1.209     brouard  3004:   min=vector(1,nlstate);
                   3005:   max=vector(1,nlstate);
                   3006:   meandiff=vector(1,nlstate);
                   3007: 
1.218     brouard  3008:        /* Starting with matrix unity */
1.126     brouard  3009:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3010:     for (j=1;j<=nlstate+ndeath;j++){
                   3011:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3012:     }
1.169     brouard  3013:   
                   3014:   cov[1]=1.;
                   3015:   
                   3016:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  3017:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  3018:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  3019:     ncvloop++;
1.126     brouard  3020:     newm=savm;
                   3021:     /* Covariates have to be included here again */
1.138     brouard  3022:     cov[2]=agefin;
1.319     brouard  3023:      if(nagesqr==1){
                   3024:       cov[3]= agefin*agefin;
                   3025:      }
1.332     brouard  3026:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3027:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3028:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3029:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3030:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3031:        }else{
                   3032:         cov[2+nagesqr+k1]=precov[nres][k1];
                   3033:        }
                   3034:      }/* End of loop on model equation */
                   3035:      
                   3036: /* Start of old code (replaced by a loop on position in the model equation */
                   3037:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   3038:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3039:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   3040:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   3041:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   3042:     /*    * k                  1        2      3    4      5      6     7        8 */
                   3043:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   3044:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   3045:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   3046:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   3047:     /*    *nsd=3                              (1)  (2)           (3) */
                   3048:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   3049:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   3050:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   3051:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   3052:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   3053:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   3054:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   3055:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   3056:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   3057:     /*    *TvarsDpType */
                   3058:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   3059:     /*    * nsd=1              (1)           (2) */
                   3060:     /*    *TvarsD[nsd]          3             2 */
                   3061:     /*    *TnsdVar           (3)=1          (2)=2 */
                   3062:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   3063:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   3064:     /*    *\/ */
                   3065:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   3066:     /*   /\* 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)); *\/ */
                   3067:     /* } */
                   3068:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   3069:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3070:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   3071:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3072:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   3073:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   3074:     /*   /\* 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]); *\/ */
                   3075:     /* } */
                   3076:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3077:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   3078:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3079:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   3080:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   3081:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3082:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   3083:     /*   } */
                   3084:     /*   /\* 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]); *\/ */
                   3085:     /* } */
                   3086:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3087:     /*   /\* 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]); *\/ */
                   3088:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3089:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3090:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3091:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3092:     /*         }else{ */
                   3093:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3094:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   3095:     /*         } */
                   3096:     /*   }else{ */
                   3097:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3098:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3099:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   3100:     /*         }else{ */
                   3101:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3102:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   3103:     /*         } */
                   3104:     /*   } */
                   3105:     /* } /\* End product without age *\/ */
                   3106: /* ENd of old code */
1.138     brouard  3107:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3108:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3109:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  3110:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3111:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  3112:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  3113:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  3114:     
1.126     brouard  3115:     savm=oldm;
                   3116:     oldm=newm;
1.209     brouard  3117: 
                   3118:     for(j=1; j<=nlstate; j++){
                   3119:       max[j]=0.;
                   3120:       min[j]=1.;
                   3121:     }
                   3122:     for(i=1;i<=nlstate;i++){
                   3123:       sumnew=0;
                   3124:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   3125:       for(j=1; j<=nlstate; j++){ 
                   3126:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   3127:        max[j]=FMAX(max[j],prlim[i][j]);
                   3128:        min[j]=FMIN(min[j],prlim[i][j]);
                   3129:       }
                   3130:     }
                   3131: 
1.126     brouard  3132:     maxmax=0.;
1.209     brouard  3133:     for(j=1; j<=nlstate; j++){
                   3134:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   3135:       maxmax=FMAX(maxmax,meandiff[j]);
                   3136:       /* 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  3137:     } /* j loop */
1.203     brouard  3138:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  3139:     /* 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  3140:     if(maxmax < ftolpl){
1.209     brouard  3141:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   3142:       free_vector(min,1,nlstate);
                   3143:       free_vector(max,1,nlstate);
                   3144:       free_vector(meandiff,1,nlstate);
1.126     brouard  3145:       return prlim;
                   3146:     }
1.288     brouard  3147:   } /* agefin loop */
1.208     brouard  3148:     /* After some age loop it doesn't converge */
1.288     brouard  3149:   if(!first){
                   3150:     first=1;
                   3151:     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  3152:     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);
                   3153:   }else if (first >=1 && first <10){
                   3154:     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);
                   3155:     first++;
                   3156:   }else if (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:     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");
                   3159:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   3160:     first++;
1.288     brouard  3161:   }
                   3162: 
1.209     brouard  3163:   /* 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); */
                   3164:   free_vector(min,1,nlstate);
                   3165:   free_vector(max,1,nlstate);
                   3166:   free_vector(meandiff,1,nlstate);
1.208     brouard  3167:   
1.169     brouard  3168:   return prlim; /* should not reach here */
1.126     brouard  3169: }
                   3170: 
1.217     brouard  3171: 
                   3172:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   3173: 
1.218     brouard  3174:  /* 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) */
                   3175:  /* 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  3176:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  3177: {
1.264     brouard  3178:   /* 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  3179:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   3180:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   3181:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   3182:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   3183:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   3184:   /* Initial matrix pimij */
                   3185:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3186:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3187:   /*  0,                   0                  , 1} */
                   3188:   /*
                   3189:    * and after some iteration: */
                   3190:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3191:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3192:   /*  0,                   0                  , 1} */
                   3193:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3194:   /* {0.51571254859325999, 0.4842874514067399, */
                   3195:   /*  0.51326036147820708, 0.48673963852179264} */
                   3196:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3197: 
1.332     brouard  3198:   int i, ii,j,k, k1;
1.247     brouard  3199:   int first=0;
1.217     brouard  3200:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3201:   /* double **matprod2(); */ /* test */
                   3202:   double **out, cov[NCOVMAX+1], **bmij();
                   3203:   double **newm;
1.218     brouard  3204:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   3205:   double        **oldm, **savm;  /* for use */
                   3206: 
1.217     brouard  3207:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3208:   int ncvloop=0;
                   3209:   
                   3210:   min=vector(1,nlstate);
                   3211:   max=vector(1,nlstate);
                   3212:   meandiff=vector(1,nlstate);
                   3213: 
1.266     brouard  3214:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   3215:   oldm=oldms; savm=savms;
                   3216:   
                   3217:   /* Starting with matrix unity */
                   3218:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3219:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  3220:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3221:     }
                   3222:   
                   3223:   cov[1]=1.;
                   3224:   
                   3225:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3226:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  3227:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  3228:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3229:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  3230:     ncvloop++;
1.218     brouard  3231:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   3232:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  3233:     /* Covariates have to be included here again */
                   3234:     cov[2]=agefin;
1.319     brouard  3235:     if(nagesqr==1){
1.217     brouard  3236:       cov[3]= agefin*agefin;;
1.319     brouard  3237:     }
1.332     brouard  3238:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3239:       if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3240:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  3241:       }else{
1.332     brouard  3242:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  3243:       }
1.332     brouard  3244:     }/* End of loop on model equation */
                   3245: 
                   3246: /* Old code */ 
                   3247: 
                   3248:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   3249:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3250:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   3251:     /*   /\* 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)); *\/ */
                   3252:     /* } */
                   3253:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   3254:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3255:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3256:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   3257:     /* /\* } *\/ */
                   3258:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3259:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3260:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3261:     /*   /\* 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]); *\/ */
                   3262:     /* } */
                   3263:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   3264:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   3265:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   3266:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3267:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3268:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   3269:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3270:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3271:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3272:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3273:     /*   } */
                   3274:     /*   /\* 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]); *\/ */
                   3275:     /* } */
                   3276:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3277:     /*   /\* 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]); *\/ */
                   3278:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3279:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3280:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3281:     /*         }else{ */
                   3282:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3283:     /*         } */
                   3284:     /*   }else{ */
                   3285:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3286:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3287:     /*         }else{ */
                   3288:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3289:     /*         } */
                   3290:     /*   } */
                   3291:     /* } */
1.217     brouard  3292:     
                   3293:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3294:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3295:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3296:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3297:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3298:                /* ij should be linked to the correct index of cov */
                   3299:                /* age and covariate values ij are in 'cov', but we need to pass
                   3300:                 * ij for the observed prevalence at age and status and covariate
                   3301:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3302:                 */
                   3303:     /* 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 *\/ */
                   3304:     /* 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 *\/ */
                   3305:     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  3306:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3307:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3308:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3309:     /*         printf("%d newm= ",i); */
                   3310:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3311:     /*           printf("%f ",newm[i][j]); */
                   3312:     /*         } */
                   3313:     /*         printf("oldm * "); */
                   3314:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3315:     /*           printf("%f ",oldm[i][j]); */
                   3316:     /*         } */
1.268     brouard  3317:     /*         printf(" bmmij "); */
1.266     brouard  3318:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3319:     /*           printf("%f ",pmmij[i][j]); */
                   3320:     /*         } */
                   3321:     /*         printf("\n"); */
                   3322:     /*   } */
                   3323:     /* } */
1.217     brouard  3324:     savm=oldm;
                   3325:     oldm=newm;
1.266     brouard  3326: 
1.217     brouard  3327:     for(j=1; j<=nlstate; j++){
                   3328:       max[j]=0.;
                   3329:       min[j]=1.;
                   3330:     }
                   3331:     for(j=1; j<=nlstate; j++){ 
                   3332:       for(i=1;i<=nlstate;i++){
1.234     brouard  3333:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3334:        bprlim[i][j]= newm[i][j];
                   3335:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3336:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3337:       }
                   3338:     }
1.218     brouard  3339:                
1.217     brouard  3340:     maxmax=0.;
                   3341:     for(i=1; i<=nlstate; i++){
1.318     brouard  3342:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3343:       maxmax=FMAX(maxmax,meandiff[i]);
                   3344:       /* 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  3345:     } /* i loop */
1.217     brouard  3346:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3347:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3348:     if(maxmax < ftolpl){
1.220     brouard  3349:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3350:       free_vector(min,1,nlstate);
                   3351:       free_vector(max,1,nlstate);
                   3352:       free_vector(meandiff,1,nlstate);
                   3353:       return bprlim;
                   3354:     }
1.288     brouard  3355:   } /* agefin loop */
1.217     brouard  3356:     /* After some age loop it doesn't converge */
1.288     brouard  3357:   if(!first){
1.247     brouard  3358:     first=1;
                   3359:     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\
                   3360: 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);
                   3361:   }
                   3362:   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  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:   /* 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); */
                   3365:   free_vector(min,1,nlstate);
                   3366:   free_vector(max,1,nlstate);
                   3367:   free_vector(meandiff,1,nlstate);
                   3368:   
                   3369:   return bprlim; /* should not reach here */
                   3370: }
                   3371: 
1.126     brouard  3372: /*************** transition probabilities ***************/ 
                   3373: 
                   3374: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3375: {
1.138     brouard  3376:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3377:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3378:      model to the ncovmodel covariates (including constant and age).
                   3379:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3380:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3381:      ncth covariate in the global vector x is given by the formula:
                   3382:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3383:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3384:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3385:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3386:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3387:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3388:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3389:   */
                   3390:   double s1, lnpijopii;
1.126     brouard  3391:   /*double t34;*/
1.164     brouard  3392:   int i,j, nc, ii, jj;
1.126     brouard  3393: 
1.223     brouard  3394:   for(i=1; i<= nlstate; i++){
                   3395:     for(j=1; j<i;j++){
                   3396:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3397:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3398:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3399:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3400:       }
                   3401:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3402:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3403:     }
                   3404:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3405:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3406:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3407:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3408:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3409:       }
                   3410:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3411:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3412:     }
                   3413:   }
1.218     brouard  3414:   
1.223     brouard  3415:   for(i=1; i<= nlstate; i++){
                   3416:     s1=0;
                   3417:     for(j=1; j<i; j++){
1.339     brouard  3418:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3419:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3420:     }
                   3421:     for(j=i+1; j<=nlstate+ndeath; j++){
1.339     brouard  3422:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3423:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3424:     }
                   3425:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3426:     ps[i][i]=1./(s1+1.);
                   3427:     /* Computing other pijs */
                   3428:     for(j=1; j<i; j++)
1.325     brouard  3429:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3430:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3431:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3432:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3433:   } /* end i */
1.218     brouard  3434:   
1.223     brouard  3435:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3436:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3437:       ps[ii][jj]=0;
                   3438:       ps[ii][ii]=1;
                   3439:     }
                   3440:   }
1.294     brouard  3441: 
                   3442: 
1.223     brouard  3443:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3444:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3445:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3446:   /*   } */
                   3447:   /*   printf("\n "); */
                   3448:   /* } */
                   3449:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3450:   /*
                   3451:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3452:                goto end;*/
1.266     brouard  3453:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3454: }
                   3455: 
1.218     brouard  3456: /*************** backward transition probabilities ***************/ 
                   3457: 
                   3458:  /* 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 ) */
                   3459: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3460:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3461: {
1.302     brouard  3462:   /* 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  3463:    * 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  3464:    */
1.218     brouard  3465:   int i, ii, j,k;
1.222     brouard  3466:   
                   3467:   double **out, **pmij();
                   3468:   double sumnew=0.;
1.218     brouard  3469:   double agefin;
1.292     brouard  3470:   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  3471:   double **dnewm, **dsavm, **doldm;
                   3472:   double **bbmij;
                   3473:   
1.218     brouard  3474:   doldm=ddoldms; /* global pointers */
1.222     brouard  3475:   dnewm=ddnewms;
                   3476:   dsavm=ddsavms;
1.318     brouard  3477: 
                   3478:   /* Debug */
                   3479:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3480:   agefin=cov[2];
1.268     brouard  3481:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3482:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3483:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3484:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3485: 
                   3486:   /* P_x */
1.325     brouard  3487:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3488:   /* outputs pmmij which is a stochastic matrix in row */
                   3489: 
                   3490:   /* Diag(w_x) */
1.292     brouard  3491:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3492:   sumnew=0.;
1.269     brouard  3493:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3494:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3495:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3496:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3497:   }
                   3498:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3499:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3500:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3501:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3502:     }
                   3503:   }else{
                   3504:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3505:       for (j=1;j<=nlstate+ndeath;j++)
                   3506:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3507:     }
                   3508:     /* if(sumnew <0.9){ */
                   3509:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3510:     /* } */
                   3511:   }
                   3512:   k3=0.0;  /* We put the last diagonal to 0 */
                   3513:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3514:       doldm[ii][ii]= k3;
                   3515:   }
                   3516:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3517:   
1.292     brouard  3518:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3519:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3520: 
1.292     brouard  3521:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3522:   /* 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  3523:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3524:     sumnew=0.;
1.222     brouard  3525:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3526:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3527:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3528:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3529:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3530:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3531:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3532:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3533:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3534:        /* }else */
1.268     brouard  3535:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3536:     } /*End ii */
                   3537:   } /* 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 */
                   3538: 
1.292     brouard  3539:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3540:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3541:   /* end bmij */
1.266     brouard  3542:   return ps; /*pointer is unchanged */
1.218     brouard  3543: }
1.217     brouard  3544: /*************** transition probabilities ***************/ 
                   3545: 
1.218     brouard  3546: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3547: {
                   3548:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3549:      computes the probability to be observed in state j being in state i by appying the
                   3550:      model to the ncovmodel covariates (including constant and age).
                   3551:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3552:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3553:      ncth covariate in the global vector x is given by the formula:
                   3554:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3555:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3556:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3557:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3558:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3559:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3560:   */
                   3561:   double s1, lnpijopii;
                   3562:   /*double t34;*/
                   3563:   int i,j, nc, ii, jj;
                   3564: 
1.234     brouard  3565:   for(i=1; i<= nlstate; i++){
                   3566:     for(j=1; j<i;j++){
                   3567:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3568:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3569:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3570:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3571:       }
                   3572:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3573:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3574:     }
                   3575:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3576:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3577:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3578:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3579:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3580:       }
                   3581:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3582:     }
                   3583:   }
                   3584:   
                   3585:   for(i=1; i<= nlstate; i++){
                   3586:     s1=0;
                   3587:     for(j=1; j<i; j++){
                   3588:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3589:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3590:     }
                   3591:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3592:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3593:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3594:     }
                   3595:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3596:     ps[i][i]=1./(s1+1.);
                   3597:     /* Computing other pijs */
                   3598:     for(j=1; j<i; j++)
                   3599:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3600:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3601:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3602:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3603:   } /* end i */
                   3604:   
                   3605:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3606:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3607:       ps[ii][jj]=0;
                   3608:       ps[ii][ii]=1;
                   3609:     }
                   3610:   }
1.296     brouard  3611:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3612:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3613:     s1=0.;
                   3614:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3615:       s1+=ps[ii][jj];
                   3616:     }
                   3617:     for(ii=1; ii<= nlstate; ii++){
                   3618:       ps[ii][jj]=ps[ii][jj]/s1;
                   3619:     }
                   3620:   }
                   3621:   /* Transposition */
                   3622:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3623:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3624:       s1=ps[ii][jj];
                   3625:       ps[ii][jj]=ps[jj][ii];
                   3626:       ps[jj][ii]=s1;
                   3627:     }
                   3628:   }
                   3629:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3630:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3631:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3632:   /*   } */
                   3633:   /*   printf("\n "); */
                   3634:   /* } */
                   3635:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3636:   /*
                   3637:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3638:     goto end;*/
                   3639:   return ps;
1.217     brouard  3640: }
                   3641: 
                   3642: 
1.126     brouard  3643: /**************** Product of 2 matrices ******************/
                   3644: 
1.145     brouard  3645: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3646: {
                   3647:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3648:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3649:   /* in, b, out are matrice of pointers which should have been initialized 
                   3650:      before: only the contents of out is modified. The function returns
                   3651:      a pointer to pointers identical to out */
1.145     brouard  3652:   int i, j, k;
1.126     brouard  3653:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3654:     for(k=ncolol; k<=ncoloh; k++){
                   3655:       out[i][k]=0.;
                   3656:       for(j=ncl; j<=nch; j++)
                   3657:        out[i][k] +=in[i][j]*b[j][k];
                   3658:     }
1.126     brouard  3659:   return out;
                   3660: }
                   3661: 
                   3662: 
                   3663: /************* Higher Matrix Product ***************/
                   3664: 
1.235     brouard  3665: 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  3666: {
1.336     brouard  3667:   /* Already optimized with precov.
                   3668:      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  3669:      'nhstepm*hstepm*stepm' months (i.e. until
                   3670:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3671:      nhstepm*hstepm matrices. 
                   3672:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3673:      (typically every 2 years instead of every month which is too big 
                   3674:      for the memory).
                   3675:      Model is determined by parameters x and covariates have to be 
                   3676:      included manually here. 
                   3677: 
                   3678:      */
                   3679: 
1.330     brouard  3680:   int i, j, d, h, k, k1;
1.131     brouard  3681:   double **out, cov[NCOVMAX+1];
1.126     brouard  3682:   double **newm;
1.187     brouard  3683:   double agexact;
1.214     brouard  3684:   double agebegin, ageend;
1.126     brouard  3685: 
                   3686:   /* Hstepm could be zero and should return the unit matrix */
                   3687:   for (i=1;i<=nlstate+ndeath;i++)
                   3688:     for (j=1;j<=nlstate+ndeath;j++){
                   3689:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3690:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3691:     }
                   3692:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3693:   for(h=1; h <=nhstepm; h++){
                   3694:     for(d=1; d <=hstepm; d++){
                   3695:       newm=savm;
                   3696:       /* Covariates have to be included here again */
                   3697:       cov[1]=1.;
1.214     brouard  3698:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3699:       cov[2]=agexact;
1.319     brouard  3700:       if(nagesqr==1){
1.227     brouard  3701:        cov[3]= agexact*agexact;
1.319     brouard  3702:       }
1.330     brouard  3703:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3704:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3705:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3706:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3707:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3708:        }else{
                   3709:          cov[2+nagesqr+k1]=precov[nres][k1];
                   3710:        }
                   3711:       }/* End of loop on model equation */
                   3712:        /* Old code */ 
                   3713: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   3714: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   3715: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   3716: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   3717: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   3718: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3719: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3720: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   3721: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   3722: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   3723: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   3724: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   3725: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   3726: /*       /\* 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]])); *\/ */
                   3727: /*       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); */
                   3728: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3729: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   3730: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   3731: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   3732: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   3733: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   3734: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3735: /*       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]]); */
                   3736: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3737: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   3738: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   3739: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   3740: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   3741: /*       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]); */
                   3742: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3743: 
                   3744: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   3745: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   3746: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   3747: /*       /\* *\/ */
1.330     brouard  3748: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3749: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3750: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  3751: /* /\*cptcovage=2                   1               2      *\/ */
                   3752: /* /\*Tage[k]=                      5               8      *\/  */
                   3753: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   3754: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   3755: /*       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]]); */
                   3756: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3757: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   3758: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   3759: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   3760: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   3761: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   3762: /*       /\*   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); *\/ */
                   3763: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   3764: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   3765: /*       /\* } *\/ */
                   3766: /*       /\* 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]); *\/ */
                   3767: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   3768: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   3769: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   3770: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   3771: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   3772: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   3773: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   3774: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   3775: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  3776:          
1.332     brouard  3777: /*       /\* 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])]); *\/ */
                   3778: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3779: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   3780: /*       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]]); */
                   3781: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3782: 
                   3783: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   3784: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   3785: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3786: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   3787: /*           /\* 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]])]; *\/ */
                   3788: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   3789: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   3790: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   3791: /*       /\*   } *\/ */
                   3792: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   3793: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   3794: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   3795: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3796: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   3797: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   3798: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3799: /*       /\*   } *\/ */
                   3800: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   3801: /*     }/\*end of products *\/ */
                   3802:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  3803:       /* for (k=1; k<=cptcovn;k++)  */
                   3804:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3805:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3806:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3807:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3808:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3809:       
                   3810:       
1.126     brouard  3811:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3812:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3813:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3814:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3815:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3816:       /* if((int)age == 70){ */
                   3817:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3818:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3819:       /*         printf("%d pmmij ",i); */
                   3820:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3821:       /*           printf("%f ",pmmij[i][j]); */
                   3822:       /*         } */
                   3823:       /*         printf(" oldm "); */
                   3824:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3825:       /*           printf("%f ",oldm[i][j]); */
                   3826:       /*         } */
                   3827:       /*         printf("\n"); */
                   3828:       /*       } */
                   3829:       /* } */
1.126     brouard  3830:       savm=oldm;
                   3831:       oldm=newm;
                   3832:     }
                   3833:     for(i=1; i<=nlstate+ndeath; i++)
                   3834:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3835:        po[i][j][h]=newm[i][j];
                   3836:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3837:       }
1.128     brouard  3838:     /*printf("h=%d ",h);*/
1.126     brouard  3839:   } /* end h */
1.267     brouard  3840:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3841:   return po;
                   3842: }
                   3843: 
1.217     brouard  3844: /************* Higher Back Matrix Product ***************/
1.218     brouard  3845: /* 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  3846: 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  3847: {
1.332     brouard  3848:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   3849:      computes the transition matrix starting at age 'age' over
1.217     brouard  3850:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3851:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3852:      nhstepm*hstepm matrices.
                   3853:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3854:      (typically every 2 years instead of every month which is too big
1.217     brouard  3855:      for the memory).
1.218     brouard  3856:      Model is determined by parameters x and covariates have to be
1.266     brouard  3857:      included manually here. Then we use a call to bmij(x and cov)
                   3858:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3859:   */
1.217     brouard  3860: 
1.332     brouard  3861:   int i, j, d, h, k, k1;
1.266     brouard  3862:   double **out, cov[NCOVMAX+1], **bmij();
                   3863:   double **newm, ***newmm;
1.217     brouard  3864:   double agexact;
                   3865:   double agebegin, ageend;
1.222     brouard  3866:   double **oldm, **savm;
1.217     brouard  3867: 
1.266     brouard  3868:   newmm=po; /* To be saved */
                   3869:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3870:   /* Hstepm could be zero and should return the unit matrix */
                   3871:   for (i=1;i<=nlstate+ndeath;i++)
                   3872:     for (j=1;j<=nlstate+ndeath;j++){
                   3873:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3874:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3875:     }
                   3876:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3877:   for(h=1; h <=nhstepm; h++){
                   3878:     for(d=1; d <=hstepm; d++){
                   3879:       newm=savm;
                   3880:       /* Covariates have to be included here again */
                   3881:       cov[1]=1.;
1.271     brouard  3882:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3883:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3884:         /* Debug */
                   3885:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3886:       cov[2]=agexact;
1.332     brouard  3887:       if(nagesqr==1){
1.222     brouard  3888:        cov[3]= agexact*agexact;
1.332     brouard  3889:       }
                   3890:       /** New code */
                   3891:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3892:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3893:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  3894:        }else{
1.332     brouard  3895:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  3896:        }
1.332     brouard  3897:       }/* End of loop on model equation */
                   3898:       /** End of new code */
                   3899:   /** This was old code */
                   3900:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   3901:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3902:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3903:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   3904:       /*   /\* 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)); *\/ */
                   3905:       /* } */
                   3906:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3907:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3908:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3909:       /*       /\* 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]); *\/ */
                   3910:       /* } */
                   3911:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   3912:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   3913:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3914:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3915:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3916:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   3917:       /*       } */
                   3918:       /*       /\* 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]); *\/ */
                   3919:       /* } */
                   3920:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   3921:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3922:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   3923:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3924:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   3925:       /*         }else{ */
                   3926:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3927:       /*         } */
                   3928:       /*       }else{ */
                   3929:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3930:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3931:       /*         }else{ */
                   3932:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3933:       /*         } */
                   3934:       /*       } */
                   3935:       /* }                      */
                   3936:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   3937:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   3938: /** End of old code */
                   3939:       
1.218     brouard  3940:       /* Careful transposed matrix */
1.266     brouard  3941:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3942:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3943:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3944:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3945:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3946:       /* if((int)age == 70){ */
                   3947:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3948:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3949:       /*         printf("%d pmmij ",i); */
                   3950:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3951:       /*           printf("%f ",pmmij[i][j]); */
                   3952:       /*         } */
                   3953:       /*         printf(" oldm "); */
                   3954:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3955:       /*           printf("%f ",oldm[i][j]); */
                   3956:       /*         } */
                   3957:       /*         printf("\n"); */
                   3958:       /*       } */
                   3959:       /* } */
                   3960:       savm=oldm;
                   3961:       oldm=newm;
                   3962:     }
                   3963:     for(i=1; i<=nlstate+ndeath; i++)
                   3964:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3965:        po[i][j][h]=newm[i][j];
1.268     brouard  3966:        /* if(h==nhstepm) */
                   3967:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3968:       }
1.268     brouard  3969:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3970:   } /* end h */
1.268     brouard  3971:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3972:   return po;
                   3973: }
                   3974: 
                   3975: 
1.162     brouard  3976: #ifdef NLOPT
                   3977:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3978:   double fret;
                   3979:   double *xt;
                   3980:   int j;
                   3981:   myfunc_data *d2 = (myfunc_data *) pd;
                   3982: /* xt = (p1-1); */
                   3983:   xt=vector(1,n); 
                   3984:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3985: 
                   3986:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3987:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3988:   printf("Function = %.12lf ",fret);
                   3989:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3990:   printf("\n");
                   3991:  free_vector(xt,1,n);
                   3992:   return fret;
                   3993: }
                   3994: #endif
1.126     brouard  3995: 
                   3996: /*************** log-likelihood *************/
                   3997: double func( double *x)
                   3998: {
1.336     brouard  3999:   int i, ii, j, k, mi, d, kk, kf=0;
1.226     brouard  4000:   int ioffset=0;
1.339     brouard  4001:   int ipos=0,iposold=0,ncovv=0;
                   4002: 
1.340     brouard  4003:   double cotvarv, cotvarvold;
1.226     brouard  4004:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   4005:   double **out;
                   4006:   double lli; /* Individual log likelihood */
                   4007:   int s1, s2;
1.228     brouard  4008:   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  4009: 
1.226     brouard  4010:   double bbh, survp;
                   4011:   double agexact;
1.336     brouard  4012:   double agebegin, ageend;
1.226     brouard  4013:   /*extern weight */
                   4014:   /* We are differentiating ll according to initial status */
                   4015:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4016:   /*for(i=1;i<imx;i++) 
                   4017:     printf(" %d\n",s[4][i]);
                   4018:   */
1.162     brouard  4019: 
1.226     brouard  4020:   ++countcallfunc;
1.162     brouard  4021: 
1.226     brouard  4022:   cov[1]=1.;
1.126     brouard  4023: 
1.226     brouard  4024:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4025:   ioffset=0;
1.226     brouard  4026:   if(mle==1){
                   4027:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4028:       /* Computes the values of the ncovmodel covariates of the model
                   4029:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4030:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4031:         to be observed in j being in i according to the model.
                   4032:       */
1.243     brouard  4033:       ioffset=2+nagesqr ;
1.233     brouard  4034:    /* Fixed */
1.345     brouard  4035:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummy or quant or prod */
1.319     brouard  4036:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   4037:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   4038:        /*  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  4039:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.336     brouard  4040:        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  4041:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  4042:       }
1.226     brouard  4043:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  4044:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  4045:         has been calculated etc */
                   4046:       /* For an individual i, wav[i] gives the number of effective waves */
                   4047:       /* We compute the contribution to Likelihood of each effective transition
                   4048:         mw[mi][i] is real wave of the mi th effectve wave */
                   4049:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4050:         s2=s[mw[mi+1][i]][i];
1.341     brouard  4051:         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  4052:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   4053:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   4054:       */
1.336     brouard  4055:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   4056:       /* Wave varying (but not age varying) */
1.339     brouard  4057:        /* 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*\/ */
                   4058:        /*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
                   4059:        /*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4060:        /* } */
1.340     brouard  4061:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
                   4062:          itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4063:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  4064:          if(FixedV[itv]!=0){ /* Not a fixed covariate */
1.341     brouard  4065:            cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* cotvar[wav][ncovcol+nqv+iv][i] */
1.340     brouard  4066:          }else{ /* fixed covariate */
1.345     brouard  4067:            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  4068:          }
1.339     brouard  4069:          if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  4070:            cotvarvold=cotvarv;
                   4071:          }else{ /* A second product */
                   4072:            cotvarv=cotvarv*cotvarvold;
1.339     brouard  4073:          }
                   4074:          iposold=ipos;
1.340     brouard  4075:          cov[ioffset+ipos]=cotvarv;
1.234     brouard  4076:        }
1.339     brouard  4077:        /* for products of time varying to be done */
1.234     brouard  4078:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4079:          for (j=1;j<=nlstate+ndeath;j++){
                   4080:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4081:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4082:          }
1.336     brouard  4083: 
                   4084:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4085:        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  4086:        for(d=0; d<dh[mi][i]; d++){
                   4087:          newm=savm;
                   4088:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4089:          cov[2]=agexact;
                   4090:          if(nagesqr==1)
                   4091:            cov[3]= agexact*agexact;  /* Should be changed here */
1.349     brouard  4092:          /* for (kk=1; kk<=cptcovage;kk++) { */
                   4093:          /*   if(!FixedV[Tvar[Tage[kk]]]) */
                   4094:          /*     cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /\* Tage[kk] gives the data-covariate associated with age *\/ */
                   4095:          /*   else */
                   4096:          /*     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) *\/  */
                   4097:          /* } */
                   4098:          for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   4099:            itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   4100:            ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4101:            if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4102:              cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   4103:            }else{ /* fixed covariate */
                   4104:              cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4105:            }
                   4106:            if(ipos!=iposold){ /* Not a product or first of a product */
                   4107:              cotvarvold=cotvarv;
                   4108:            }else{ /* A second product */
                   4109:              cotvarv=cotvarv*cotvarvold;
                   4110:            }
                   4111:            iposold=ipos;
                   4112:            cov[ioffset+ipos]=cotvarv*agexact;
                   4113:            /* For products */
1.234     brouard  4114:          }
1.349     brouard  4115:          
1.234     brouard  4116:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4117:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4118:          savm=oldm;
                   4119:          oldm=newm;
                   4120:        } /* end mult */
                   4121:        
                   4122:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4123:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4124:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4125:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4126:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4127:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4128:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4129:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  4130:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4131:                                 * -stepm/2 to stepm/2 .
                   4132:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4133:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4134:                                 */
1.234     brouard  4135:        s1=s[mw[mi][i]][i];
                   4136:        s2=s[mw[mi+1][i]][i];
                   4137:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4138:        /* bias bh is positive if real duration
                   4139:         * is higher than the multiple of stepm and negative otherwise.
                   4140:         */
                   4141:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   4142:        if( s2 > nlstate){ 
                   4143:          /* i.e. if s2 is a death state and if the date of death is known 
                   4144:             then the contribution to the likelihood is the probability to 
                   4145:             die between last step unit time and current  step unit time, 
                   4146:             which is also equal to probability to die before dh 
                   4147:             minus probability to die before dh-stepm . 
                   4148:             In version up to 0.92 likelihood was computed
                   4149:             as if date of death was unknown. Death was treated as any other
                   4150:             health state: the date of the interview describes the actual state
                   4151:             and not the date of a change in health state. The former idea was
                   4152:             to consider that at each interview the state was recorded
                   4153:             (healthy, disable or death) and IMaCh was corrected; but when we
                   4154:             introduced the exact date of death then we should have modified
                   4155:             the contribution of an exact death to the likelihood. This new
                   4156:             contribution is smaller and very dependent of the step unit
                   4157:             stepm. It is no more the probability to die between last interview
                   4158:             and month of death but the probability to survive from last
                   4159:             interview up to one month before death multiplied by the
                   4160:             probability to die within a month. Thanks to Chris
                   4161:             Jackson for correcting this bug.  Former versions increased
                   4162:             mortality artificially. The bad side is that we add another loop
                   4163:             which slows down the processing. The difference can be up to 10%
                   4164:             lower mortality.
                   4165:          */
                   4166:          /* If, at the beginning of the maximization mostly, the
                   4167:             cumulative probability or probability to be dead is
                   4168:             constant (ie = 1) over time d, the difference is equal to
                   4169:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   4170:             s1 at precedent wave, to be dead a month before current
                   4171:             wave is equal to probability, being at state s1 at
                   4172:             precedent wave, to be dead at mont of the current
                   4173:             wave. Then the observed probability (that this person died)
                   4174:             is null according to current estimated parameter. In fact,
                   4175:             it should be very low but not zero otherwise the log go to
                   4176:             infinity.
                   4177:          */
1.183     brouard  4178: /* #ifdef INFINITYORIGINAL */
                   4179: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4180: /* #else */
                   4181: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   4182: /*         lli=log(mytinydouble); */
                   4183: /*       else */
                   4184: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4185: /* #endif */
1.226     brouard  4186:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4187:          
1.226     brouard  4188:        } else if  ( s2==-1 ) { /* alive */
                   4189:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4190:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4191:          /*survp += out[s1][j]; */
                   4192:          lli= log(survp);
                   4193:        }
1.336     brouard  4194:        /* else if  (s2==-4) {  */
                   4195:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
                   4196:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4197:        /*   lli= log(survp);  */
                   4198:        /* }  */
                   4199:        /* else if  (s2==-5) {  */
                   4200:        /*   for (j=1,survp=0. ; j<=2; j++)   */
                   4201:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4202:        /*   lli= log(survp);  */
                   4203:        /* }  */
1.226     brouard  4204:        else{
                   4205:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4206:          /*  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 */
                   4207:        } 
                   4208:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   4209:        /*if(lli ==000.0)*/
1.340     brouard  4210:        /* 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  4211:        ipmx +=1;
                   4212:        sw += weight[i];
                   4213:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4214:        /* if (lli < log(mytinydouble)){ */
                   4215:        /*   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); */
                   4216:        /*   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]); */
                   4217:        /* } */
                   4218:       } /* end of wave */
                   4219:     } /* end of individual */
                   4220:   }  else if(mle==2){
                   4221:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  4222:       ioffset=2+nagesqr ;
                   4223:       for (k=1; k<=ncovf;k++)
                   4224:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  4225:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  4226:        for(k=1; k <= ncovv ; k++){
1.341     brouard  4227:          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  4228:        }
1.226     brouard  4229:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4230:          for (j=1;j<=nlstate+ndeath;j++){
                   4231:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4232:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4233:          }
                   4234:        for(d=0; d<=dh[mi][i]; d++){
                   4235:          newm=savm;
                   4236:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4237:          cov[2]=agexact;
                   4238:          if(nagesqr==1)
                   4239:            cov[3]= agexact*agexact;
                   4240:          for (kk=1; kk<=cptcovage;kk++) {
                   4241:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4242:          }
                   4243:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4244:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4245:          savm=oldm;
                   4246:          oldm=newm;
                   4247:        } /* end mult */
                   4248:       
                   4249:        s1=s[mw[mi][i]][i];
                   4250:        s2=s[mw[mi+1][i]][i];
                   4251:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4252:        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 */
                   4253:        ipmx +=1;
                   4254:        sw += weight[i];
                   4255:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4256:       } /* end of wave */
                   4257:     } /* end of individual */
                   4258:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   4259:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4260:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4261:       for(mi=1; mi<= wav[i]-1; mi++){
                   4262:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4263:          for (j=1;j<=nlstate+ndeath;j++){
                   4264:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4265:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4266:          }
                   4267:        for(d=0; d<dh[mi][i]; d++){
                   4268:          newm=savm;
                   4269:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4270:          cov[2]=agexact;
                   4271:          if(nagesqr==1)
                   4272:            cov[3]= agexact*agexact;
                   4273:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4274:            if(!FixedV[Tvar[Tage[kk]]])
                   4275:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4276:            else
1.341     brouard  4277:              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  4278:          }
                   4279:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4280:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4281:          savm=oldm;
                   4282:          oldm=newm;
                   4283:        } /* end mult */
                   4284:       
                   4285:        s1=s[mw[mi][i]][i];
                   4286:        s2=s[mw[mi+1][i]][i];
                   4287:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4288:        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 */
                   4289:        ipmx +=1;
                   4290:        sw += weight[i];
                   4291:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4292:       } /* end of wave */
                   4293:     } /* end of individual */
                   4294:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   4295:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4296:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4297:       for(mi=1; mi<= wav[i]-1; mi++){
                   4298:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4299:          for (j=1;j<=nlstate+ndeath;j++){
                   4300:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4301:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4302:          }
                   4303:        for(d=0; d<dh[mi][i]; d++){
                   4304:          newm=savm;
                   4305:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4306:          cov[2]=agexact;
                   4307:          if(nagesqr==1)
                   4308:            cov[3]= agexact*agexact;
                   4309:          for (kk=1; kk<=cptcovage;kk++) {
                   4310:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4311:          }
1.126     brouard  4312:        
1.226     brouard  4313:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4314:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4315:          savm=oldm;
                   4316:          oldm=newm;
                   4317:        } /* end mult */
                   4318:       
                   4319:        s1=s[mw[mi][i]][i];
                   4320:        s2=s[mw[mi+1][i]][i];
                   4321:        if( s2 > nlstate){ 
                   4322:          lli=log(out[s1][s2] - savm[s1][s2]);
                   4323:        } else if  ( s2==-1 ) { /* alive */
                   4324:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4325:            survp += out[s1][j];
                   4326:          lli= log(survp);
                   4327:        }else{
                   4328:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4329:        }
                   4330:        ipmx +=1;
                   4331:        sw += weight[i];
                   4332:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.343     brouard  4333:        /* 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  4334:       } /* end of wave */
                   4335:     } /* end of individual */
                   4336:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4337:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4338:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4339:       for(mi=1; mi<= wav[i]-1; mi++){
                   4340:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4341:          for (j=1;j<=nlstate+ndeath;j++){
                   4342:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4343:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4344:          }
                   4345:        for(d=0; d<dh[mi][i]; d++){
                   4346:          newm=savm;
                   4347:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4348:          cov[2]=agexact;
                   4349:          if(nagesqr==1)
                   4350:            cov[3]= agexact*agexact;
                   4351:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4352:            if(!FixedV[Tvar[Tage[kk]]])
                   4353:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4354:            else
1.341     brouard  4355:              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  4356:          }
1.126     brouard  4357:        
1.226     brouard  4358:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4359:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4360:          savm=oldm;
                   4361:          oldm=newm;
                   4362:        } /* end mult */
                   4363:       
                   4364:        s1=s[mw[mi][i]][i];
                   4365:        s2=s[mw[mi+1][i]][i];
                   4366:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4367:        ipmx +=1;
                   4368:        sw += weight[i];
                   4369:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4370:        /*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]);*/
                   4371:       } /* end of wave */
                   4372:     } /* end of individual */
                   4373:   } /* End of if */
                   4374:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4375:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4376:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4377:   return -l;
1.126     brouard  4378: }
                   4379: 
                   4380: /*************** log-likelihood *************/
                   4381: double funcone( double *x)
                   4382: {
1.228     brouard  4383:   /* Same as func but slower because of a lot of printf and if */
1.349     brouard  4384:   int i, ii, j, k, mi, d, kk, kv=0, kf=0;
1.228     brouard  4385:   int ioffset=0;
1.339     brouard  4386:   int ipos=0,iposold=0,ncovv=0;
                   4387: 
1.340     brouard  4388:   double cotvarv, cotvarvold;
1.131     brouard  4389:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  4390:   double **out;
                   4391:   double lli; /* Individual log likelihood */
                   4392:   double llt;
                   4393:   int s1, s2;
1.228     brouard  4394:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4395: 
1.126     brouard  4396:   double bbh, survp;
1.187     brouard  4397:   double agexact;
1.214     brouard  4398:   double agebegin, ageend;
1.126     brouard  4399:   /*extern weight */
                   4400:   /* We are differentiating ll according to initial status */
                   4401:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4402:   /*for(i=1;i<imx;i++) 
                   4403:     printf(" %d\n",s[4][i]);
                   4404:   */
                   4405:   cov[1]=1.;
                   4406: 
                   4407:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4408:   ioffset=0;
                   4409:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.336     brouard  4410:     /* Computes the values of the ncovmodel covariates of the model
                   4411:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4412:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4413:        to be observed in j being in i according to the model.
                   4414:     */
1.243     brouard  4415:     /* ioffset=2+nagesqr+cptcovage; */
                   4416:     ioffset=2+nagesqr;
1.232     brouard  4417:     /* Fixed */
1.224     brouard  4418:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4419:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.349     brouard  4420:     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  4421:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
                   4422:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
                   4423:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
1.335     brouard  4424:       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  4425: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4426: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4427: /*    cov[2+6]=covar[2][i]; V2  */
                   4428: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4429: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4430: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4431: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4432: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4433: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4434:     }
1.336     brouard  4435:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   4436:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   4437:         has been calculated etc */
                   4438:       /* For an individual i, wav[i] gives the number of effective waves */
                   4439:       /* We compute the contribution to Likelihood of each effective transition
                   4440:         mw[mi][i] is real wave of the mi th effectve wave */
                   4441:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4442:         s2=s[mw[mi+1][i]][i];
1.341     brouard  4443:         And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][ncovcol+nqv+iv][i]
1.336     brouard  4444:       */
                   4445:     /* This part may be useless now because everythin should be in covar */
1.232     brouard  4446:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4447:     /*   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?)*\/ */
                   4448:     /* } */
1.231     brouard  4449:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4450:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4451:     /* } */
1.225     brouard  4452:     
1.233     brouard  4453: 
                   4454:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.339     brouard  4455:       /* 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 */
                   4456:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
                   4457:       /*       /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
                   4458:       /*       cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4459:       /* } */
                   4460:       
                   4461:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   4462:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   4463:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   4464:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
                   4465:       /* We need the position of the time varying or product in the model */
                   4466:       /* 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 */            
                   4467:       /* TvarVV gives the variable name */
1.340     brouard  4468:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   4469:       *      k=         1   2     3     4         5        6        7       8        9
                   4470:       *  varying            1     2                                 3       4        5
                   4471:       *  ncovv              1     2                                3 4     5 6      7 8
1.343     brouard  4472:       * TvarVV[ncovv]      V3     5                                1 3     3 5      1 5
1.340     brouard  4473:       * TvarVVind           2     3                                7 7     8 8      9 9
                   4474:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
                   4475:       */
1.345     brouard  4476:       /* Other model ncovcol=5 nqv=0 ntv=3 nqtv=0 nlstate=3
1.349     brouard  4477:        * 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  4478:        * FixedV[ncovcol+qv+ntv+nqtv]       V5
1.349     brouard  4479:        * 3           V1  V2     V3    V4   V5 V6     V7  V8 V3*V2 V7*V2  V6*V3 V7*V3 V6*V4 V7*V4
                   4480:        *             0   0      0      0    0  1      1   1  0, 0, 1,1,   1, 0, 1, 0, 1, 0, 1, 0}
                   4481:        * 3           0   0      0      0    0  1      1   1  0,     1      1    1      1    1}
                   4482:        * model=          V2  +  V3  +  V4  +  V6  +  V7  +  V6*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4483:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4484:         *                +age*V6*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4485:        * model2=          V2  +  V3  +  V4  +  V6  +  V7  +  V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4486:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4487:         *                +age*V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4488:        * model3=          V2  +  V3  +  V4  +  V6  +  V7  + age*V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4489:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4490:         *                +V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4491:        * kmodel           1     2      3      4      5        6         7         8         9        10        11    
                   4492:        *                  12       13      14      15       16
                   4493:        *                    17        18         19        20         21
                   4494:        * Tvar[kmodel]     2     3      4      6      7        9        10        11        12        13        14
                   4495:        *                   2       3        4       6        7
                   4496:        *                     9         11          12        13         14            
                   4497:        * cptcovage=5+5 total of covariates with age 
                   4498:        * Tage[cptcovage] age*V2=12      13      14      15       16
                   4499:        *1                   17            18         19        20         21 gives the position in model of covariates associated with age
                   4500:        *3 Tage[cptcovage] age*V3*V2=6  
                   4501:        *3                age*V2=12         13      14      15       16
                   4502:        *3                age*V6*V3=18      19    20   21
                   4503:        * Tvar[Tage[cptcovage]]    Tvar[12]=2      3      4       6         Tvar[16]=7(age*V7)
                   4504:        *     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
                   4505:        * 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
                   4506:        * 3 Tvar[Tage[cptcovage]]    Tvar[6]=9      Tvar[12]=2      3     4       6         Tvar[16]=7(age*V7)
                   4507:        * 3     Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
                   4508:        * 3 Tage[cptcovage] age*V3*V2=6   age*V2=12 age*V3 13    14      15       16
                   4509:        *                    age*V6*V3=18         19        20         21 gives the position in model of covariates associated with age
                   4510:        * 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
                   4511:        * Tvar=                {2, 3, 4, 6, 7,
                   4512:        *                       9, 10, 11, 12, 13, 14,
                   4513:        *              Tvar[12]=2, 3, 4, 6, 7,
                   4514:        *              Tvar[17]=9, 11, 12, 13, 14}
                   4515:        * Typevar[1]@21 = {0, 0, 0, 0, 0,
                   4516:        *                  2, 2, 2, 2, 2, 2,
                   4517:        * 3                3, 2, 2, 2, 2, 2,
                   4518:        *                  1, 1, 1, 1, 1, 
                   4519:        *                  3, 3, 3, 3, 3}
                   4520:        * 3                 2, 3, 3, 3, 3}
                   4521:        * 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
                   4522:        * p Tprod[1]@21 {6, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   4523:        * 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}
                   4524:        * 3 Tprod[1]@21 {17, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   4525:        * cptcovprod=11 (6+5)
                   4526:        * FixedV[Tvar[Tage[cptcovage]]]]  FixedV[2]=0      FixedV[3]=0      0      1          (age*V7)Tvar[16]=1 FixedV[absolute] not [kmodel]
                   4527:        *   FixedV[Tvar[17]=FixedV[age*V6*V2]=FixedV[9]=1        1         1          1         1  
                   4528:        * 3 FixedV[Tvar[17]=FixedV[age*V3*V2]=FixedV[9]=0        [11]=1         1          1         1  
                   4529:        * FixedV[]          V1=0     V2=0   V3=0  v4=0    V5=0  V6=1    V7=1 v8=1  OK then model dependent
                   4530:        *                   9=1  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   4531:        * 3                 9=0  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   4532:        * cptcovdageprod=5  for gnuplot printing
                   4533:        * cptcovprodvage=6 
                   4534:        * ncova=15           1        2       3       4       5
                   4535:        *                      6 7        8 9      10 11        12 13     14 15
                   4536:        * TvarA              2        3       4       6       7
                   4537:        *                      6 2        6 7       7 3          6 4       7 4
                   4538:        * TvaAind             12 12      13 13     14 14      15 15       16 16        
1.345     brouard  4539:        * ncovf            1     2      3
1.349     brouard  4540:        *                                    V6       V7      V6*V2     V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   4541:        * ncovvt=14                            1      2        3 4       5 6       7 8       9 10     11 12     13 14     
                   4542:        * TvarVV[1]@14 = itv               {V6=6,     7, V6*V2=6, 2,     7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   4543:        * TvarVVind[1]@14=                    {4,     5,       6, 6,     7, 7,     8, 8,      9, 9,   10, 10,   11, 11}
                   4544:        * 3 ncovvt=12                        V6       V7      V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   4545:        * 3 TvarVV[1]@12 = itv                {6,     7, V7*V2=7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   4546:        * 3                                    1      2        3  4      5  6      7  8      9 10     11 12
                   4547:        * TvarVVind[1]@12=         {V6 is in k=4,     5,  7,(4isV2)=7,   8, 8,      9, 9,   10,10,    11,11}TvarVVind[12]=k=11
                   4548:        * TvarV              6, 7, 9, 10, 11, 12, 13, 14
                   4549:        * 3 cptcovprodvage=6
                   4550:        * 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
                   4551:        * 3 TvarAVVA[1]@15= itva 3 2    2      3    4        6       7        6 3         7 3         6 4         7 4 
                   4552:        * 3 ncovta             1 2      3      4    5        6       7        8 9       10 11       12 13        14 15
                   4553:        * TvarAVVAind[1]@15= V3 is in k=2 1 1  2    3        4       5        4,2         5,2,      4,3           5 3}TvarVVAind[]
                   4554:        * TvarAVVAind[1]@15= V3 is in k=6 6 12  13   14      15      16       18 18       19,19,     20,20        21,21}TvarVVAind[]
                   4555:        * 3 ncovvta=10     +age*V6 + age*V7 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4556:        * 3 we want to compute =cotvar[mw[mi][i]][TvarVVA[ncovva]][i] at position TvarVVAind[ncovva]
                   4557:        * 3 TvarVVA[1]@10= itva   6       7        6 3         7 3         6 4         7 4 
                   4558:        * 3 ncovva                1       2        3 4         5 6         7 8         9 10
                   4559:        * TvarVVAind[1]@10= V6 is in k=4  5        8,8         9, 9,      10,10        11 11}TvarVVAind[]
                   4560:        * TvarVVAind[1]@10=       15       16     18,18        19,19,      20,20        21 21}TvarVVAind[]
                   4561:        * TvarVA              V3*V2=6 6 , 1, 2, 11, 12, 13, 14
1.345     brouard  4562:        * TvarFind[1]@14= {1,    2,     3,     0 <repeats 12 times>}
1.349     brouard  4563:        * Tvar[1]@21=     {2,    3,     4,    6,      7,      9,      10,        11,       12,      13,       14,
                   4564:        *                   2, 3, 4, 6, 7,
                   4565:        *                     6, 8, 9, 10, 11}
1.345     brouard  4566:        * TvarFind[itv]                        0      0       0
                   4567:        * FixedV[itv]                          1      1       1  0      1 0       1 0       1 0       0
                   4568:        * Tvar[TvarFind[ncovf]]=[1]=2 [2]=3 [4]=4
                   4569:        * Tvar[TvarFind[itv]]                [0]=?      ?ncovv 1 à ncovvt]
                   4570:        *   Not a fixed cotvar[mw][itv][i]     6       7      6  2      7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
1.349     brouard  4571:        *   fixed covar[itv]                  [6]     [7]    [6][2] 
1.345     brouard  4572:        */
                   4573: 
1.349     brouard  4574:       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 */
                   4575:        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  4576:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  4577:        /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4578:        if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4579:          cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
1.340     brouard  4580:        }else{ /* fixed covariate */
1.345     brouard  4581:          /* 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.349     brouard  4582:          cotvarv=covar[itv][i];  /* Good: In V6*V3, 3 is fixed at position of the data */
1.340     brouard  4583:        }
1.339     brouard  4584:        if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  4585:          cotvarvold=cotvarv;
                   4586:        }else{ /* A second product */
                   4587:          cotvarv=cotvarv*cotvarvold;
1.339     brouard  4588:        }
                   4589:        iposold=ipos;
1.340     brouard  4590:        cov[ioffset+ipos]=cotvarv;
1.339     brouard  4591:        /* For products */
                   4592:       }
                   4593:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
                   4594:       /*       iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
                   4595:       /*       /\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
                   4596:       /*       /\*           1  2   3      4      5                         *\/ */
                   4597:       /*       /\*itv           1                                           *\/ */
                   4598:       /*       /\* TvarVInd[1]= 2                                           *\/ */
                   4599:       /*       /\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
                   4600:       /*       /\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
                   4601:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
                   4602:       /*       /\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
                   4603:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
                   4604:       /*       cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
                   4605:       /*       /\* 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]); *\/ */
                   4606:       /* } */
1.232     brouard  4607:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4608:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4609:       /*       /\* 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]); *\/ */
                   4610:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4611:       /* } */
1.126     brouard  4612:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4613:        for (j=1;j<=nlstate+ndeath;j++){
                   4614:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4615:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4616:        }
1.214     brouard  4617:       
                   4618:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4619:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4620:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4621:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4622:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4623:          and mw[mi+1][i]. dh depends on stepm.*/
                   4624:        newm=savm;
1.247     brouard  4625:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4626:        cov[2]=agexact;
                   4627:        if(nagesqr==1)
                   4628:          cov[3]= agexact*agexact;
1.349     brouard  4629:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   4630:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   4631:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4632:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4633:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4634:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4635:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   4636:          }else{ /* fixed covariate */
                   4637:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   4638:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4639:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4640:          }
                   4641:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4642:            cotvarvold=cotvarv;
                   4643:          }else{ /* A second product */
                   4644:            /* printf("DEBUG * \n"); */
                   4645:            cotvarv=cotvarv*cotvarvold;
                   4646:          }
                   4647:          iposold=ipos;
                   4648:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   4649:          cov[ioffset+ipos]=cotvarv*agexact;
                   4650:          /* For products */
1.242     brouard  4651:        }
1.349     brouard  4652: 
1.242     brouard  4653:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4654:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4655:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4656:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4657:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4658:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4659:        savm=oldm;
                   4660:        oldm=newm;
1.126     brouard  4661:       } /* end mult */
1.336     brouard  4662:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4663:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4664:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4665:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4666:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4667:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4668:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4669:         * probability in order to take into account the bias as a fraction of the way
                   4670:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4671:                                 * -stepm/2 to stepm/2 .
                   4672:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4673:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4674:                                 */
1.126     brouard  4675:       s1=s[mw[mi][i]][i];
                   4676:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4677:       /* if(s2==-1){ */
1.268     brouard  4678:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4679:       /*       /\* exit(1); *\/ */
                   4680:       /* } */
1.126     brouard  4681:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4682:       /* bias is positive if real duration
                   4683:        * is higher than the multiple of stepm and negative otherwise.
                   4684:        */
                   4685:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4686:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4687:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4688:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4689:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4690:        lli= log(survp);
1.126     brouard  4691:       }else if (mle==1){
1.242     brouard  4692:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4693:       } else if(mle==2){
1.242     brouard  4694:        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  4695:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4696:        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  4697:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4698:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4699:       } else{  /* mle=0 back to 1 */
1.242     brouard  4700:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4701:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4702:       } /* End of if */
                   4703:       ipmx +=1;
                   4704:       sw += weight[i];
                   4705:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.342     brouard  4706:       /* Printing covariates values for each contribution for checking */
1.343     brouard  4707:       /* 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  4708:       if(globpr){
1.246     brouard  4709:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4710:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4711:                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  4712:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.343     brouard  4713:        /*      printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
                   4714:        /* %11.6f %11.6f %11.6f ", \ */
                   4715:        /*              num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   4716:        /*              2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  4717:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4718:          llt +=ll[k]*gipmx/gsw;
                   4719:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335     brouard  4720:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  4721:        }
1.343     brouard  4722:        fprintf(ficresilk," %10.6f ", -llt);
1.335     brouard  4723:        /* printf(" %10.6f\n", -llt); */
1.342     brouard  4724:        /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
1.343     brouard  4725:        /* fprintf(ficresilk,"%09ld ", num[i]); */ /* not necessary */
                   4726:        for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
                   4727:          fprintf(ficresilk," %g",covar[Tvar[TvarFind[kf]]][i]);
                   4728:        }
                   4729:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
                   4730:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4731:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4732:            fprintf(ficresilk," %g",cov[ioffset+ipos]);
                   4733:            /* printf(" %g",cov[ioffset+ipos]); */
                   4734:          }else{
                   4735:            fprintf(ficresilk,"*");
                   4736:            /* printf("*"); */
1.342     brouard  4737:          }
1.343     brouard  4738:          iposold=ipos;
                   4739:        }
1.349     brouard  4740:        /* for (kk=1; kk<=cptcovage;kk++) { */
                   4741:        /*   if(!FixedV[Tvar[Tage[kk]]]){ */
                   4742:        /*     fprintf(ficresilk," %g*age",covar[Tvar[Tage[kk]]][i]); */
                   4743:        /*     /\* printf(" %g*age",covar[Tvar[Tage[kk]]][i]); *\/ */
                   4744:        /*   }else{ */
                   4745:        /*     fprintf(ficresilk," %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   4746:        /*     /\* printf(" %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\\/  *\/ */
                   4747:        /*   } */
                   4748:        /* } */
                   4749:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   4750:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   4751:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4752:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4753:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4754:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4755:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   4756:          }else{ /* fixed covariate */
                   4757:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   4758:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4759:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4760:          }
                   4761:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4762:            cotvarvold=cotvarv;
                   4763:          }else{ /* A second product */
                   4764:            /* printf("DEBUG * \n"); */
                   4765:            cotvarv=cotvarv*cotvarvold;
1.342     brouard  4766:          }
1.349     brouard  4767:          cotvarv=cotvarv*agexact;
                   4768:          fprintf(ficresilk," %g*age",cotvarv);
                   4769:          iposold=ipos;
                   4770:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   4771:          cov[ioffset+ipos]=cotvarv;
                   4772:          /* For products */
1.343     brouard  4773:        }
                   4774:        /* printf("\n"); */
1.342     brouard  4775:        /* } /\*  End debugILK *\/ */
                   4776:        fprintf(ficresilk,"\n");
                   4777:       } /* End if globpr */
1.335     brouard  4778:     } /* end of wave */
                   4779:   } /* end of individual */
                   4780:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  4781: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335     brouard  4782:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4783:   if(globpr==0){ /* First time we count the contributions and weights */
                   4784:     gipmx=ipmx;
                   4785:     gsw=sw;
                   4786:   }
1.343     brouard  4787:   return -l;
1.126     brouard  4788: }
                   4789: 
                   4790: 
                   4791: /*************** function likelione ***********/
1.292     brouard  4792: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4793: {
                   4794:   /* This routine should help understanding what is done with 
                   4795:      the selection of individuals/waves and
                   4796:      to check the exact contribution to the likelihood.
                   4797:      Plotting could be done.
1.342     brouard  4798:   */
                   4799:   void pstamp(FILE *ficres);
1.343     brouard  4800:   int k, kf, kk, kvar, ncovv, iposold, ipos;
1.126     brouard  4801: 
                   4802:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4803:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4804:     strcat(fileresilk,fileresu);
1.126     brouard  4805:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4806:       printf("Problem with resultfile: %s\n", fileresilk);
                   4807:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4808:     }
1.342     brouard  4809:     pstamp(ficresilk);fprintf(ficresilk,"# model=1+age+%s\n",model);
1.214     brouard  4810:     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");
                   4811:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4812:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4813:     for(k=1; k<=nlstate; k++) 
                   4814:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
1.342     brouard  4815:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total) ");
                   4816: 
                   4817:     /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
                   4818:       for(kf=1;kf <= ncovf; kf++){
                   4819:        fprintf(ficresilk,"V%d",Tvar[TvarFind[kf]]);
                   4820:        /* printf("V%d",Tvar[TvarFind[kf]]); */
                   4821:       }
                   4822:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){
1.343     brouard  4823:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
1.342     brouard  4824:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4825:          /* printf(" %d",ipos); */
                   4826:          fprintf(ficresilk," V%d",TvarVV[ncovv]);
                   4827:        }else{
                   4828:          /* printf("*"); */
                   4829:          fprintf(ficresilk,"*");
1.343     brouard  4830:        }
1.342     brouard  4831:        iposold=ipos;
                   4832:       }
                   4833:       for (kk=1; kk<=cptcovage;kk++) {
                   4834:        if(!FixedV[Tvar[Tage[kk]]]){
                   4835:          /* printf(" %d*age(Fixed)",Tvar[Tage[kk]]); */
                   4836:          fprintf(ficresilk," %d*age(Fixed)",Tvar[Tage[kk]]);
                   4837:        }else{
                   4838:          fprintf(ficresilk," %d*age(Varying)",Tvar[Tage[kk]]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   4839:          /* printf(" %d*age(Varying)",Tvar[Tage[kk]]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   4840:        }
                   4841:       }
                   4842:     /* } /\* End if debugILK *\/ */
                   4843:     /* printf("\n"); */
                   4844:     fprintf(ficresilk,"\n");
                   4845:   } /* End glogpri */
1.126     brouard  4846: 
1.292     brouard  4847:   *fretone=(*func)(p);
1.126     brouard  4848:   if(*globpri !=0){
                   4849:     fclose(ficresilk);
1.205     brouard  4850:     if (mle ==0)
                   4851:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4852:     else if(mle >=1)
                   4853:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4854:     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  4855:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4856:       
1.207     brouard  4857:     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  4858: <img src=\"%s-ori.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4859:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.343     brouard  4860: <img src=\"%s-dest.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
                   4861:     
                   4862:     for (k=1; k<= nlstate ; k++) {
                   4863:       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 \
                   4864: <img src=\"%s-p%dj.png\">\n",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4865:       for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.350     brouard  4866:         kvar=Tvar[TvarFind[kf]];  /* variable */
                   4867:         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]]);
                   4868:         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);
                   4869:         fprintf(fichtm,"<img src=\"%s-p%dj-%d.png\">",subdirf2(optionfilefiname,"ILK_"),k,Tvar[TvarFind[kf]]);
1.343     brouard  4870:       }
                   4871:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Loop on the time varying extended covariates (with extension of Vn*Vm */
                   4872:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   4873:        kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4874:        /* 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]); */
                   4875:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4876:          /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   4877:          /* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); */
                   4878:          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)  */
                   4879:            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> \
                   4880: <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);
                   4881:          } /* End only for dummies time varying (single?) */
                   4882:        }else{ /* Useless product */
                   4883:          /* printf("*"); */
                   4884:          /* fprintf(ficresilk,"*"); */ 
                   4885:        }
                   4886:        iposold=ipos;
                   4887:       } /* For each time varying covariate */
                   4888:     } /* End loop on states */
                   4889: 
                   4890: /*     if(debugILK){ */
                   4891: /*       for(kf=1; kf <= ncovf; kf++){ /\* For each simple dummy covariate of the model *\/ */
                   4892: /*     /\* kvar=Tvar[TvarFind[kf]]; *\/ /\* variable *\/ */
                   4893: /*     for (k=1; k<= nlstate ; k++) { */
                   4894: /*       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> \ */
                   4895: /* <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]]); */
                   4896: /*     } */
                   4897: /*       } */
                   4898: /*       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /\* Loop on the time varying extended covariates (with extension of Vn*Vm *\/ */
                   4899: /*     ipos=TvarVVind[ncovv]; /\* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate *\/ */
                   4900: /*     kvar=TvarVV[ncovv]; /\*  TvarVV={3, 1, 3} gives the name of each varying covariate *\/ */
                   4901: /*     /\* 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]); *\/ */
                   4902: /*     if(ipos!=iposold){ /\* Not a product or first of a product *\/ */
                   4903: /*       /\* fprintf(ficresilk," V%d",TvarVV[ncovv]); *\/ */
                   4904: /*       /\* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); *\/ */
                   4905: /*       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)  *\/ */
                   4906: /*         for (k=1; k<= nlstate ; k++) { */
                   4907: /*           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> \ */
                   4908: /* <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar); */
                   4909: /*         } /\* End state *\/ */
                   4910: /*       } /\* End only for dummies time varying (single?) *\/ */
                   4911: /*     }else{ /\* Useless product *\/ */
                   4912: /*       /\* printf("*"); *\/ */
                   4913: /*       /\* fprintf(ficresilk,"*"); *\/  */
                   4914: /*     } */
                   4915: /*     iposold=ipos; */
                   4916: /*       } /\* For each time varying covariate *\/ */
                   4917: /*     }/\* End debugILK *\/ */
1.207     brouard  4918:     fflush(fichtm);
1.343     brouard  4919:   }/* End globpri */
1.126     brouard  4920:   return;
                   4921: }
                   4922: 
                   4923: 
                   4924: /*********** Maximum Likelihood Estimation ***************/
                   4925: 
                   4926: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4927: {
1.319     brouard  4928:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4929:   double **xi;
                   4930:   double fret;
                   4931:   double fretone; /* Only one call to likelihood */
                   4932:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4933: 
                   4934: #ifdef NLOPT
                   4935:   int creturn;
                   4936:   nlopt_opt opt;
                   4937:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4938:   double *lb;
                   4939:   double minf; /* the minimum objective value, upon return */
                   4940:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4941:   myfunc_data dinst, *d = &dinst;
                   4942: #endif
                   4943: 
                   4944: 
1.126     brouard  4945:   xi=matrix(1,npar,1,npar);
                   4946:   for (i=1;i<=npar;i++)
                   4947:     for (j=1;j<=npar;j++)
                   4948:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4949:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4950:   strcpy(filerespow,"POW_"); 
1.126     brouard  4951:   strcat(filerespow,fileres);
                   4952:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4953:     printf("Problem with resultfile: %s\n", filerespow);
                   4954:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4955:   }
                   4956:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4957:   for (i=1;i<=nlstate;i++)
                   4958:     for(j=1;j<=nlstate+ndeath;j++)
                   4959:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4960:   fprintf(ficrespow,"\n");
1.162     brouard  4961: #ifdef POWELL
1.319     brouard  4962: #ifdef LINMINORIGINAL
                   4963: #else /* LINMINORIGINAL */
                   4964:   
                   4965:   flatdir=ivector(1,npar); 
                   4966:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4967: #endif /*LINMINORIGINAL */
                   4968: 
                   4969: #ifdef FLATSUP
                   4970:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4971:   /* reorganizing p by suppressing flat directions */
                   4972:   for(i=1, jk=1; i <=nlstate; i++){
                   4973:     for(k=1; k <=(nlstate+ndeath); k++){
                   4974:       if (k != i) {
                   4975:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4976:         if(flatdir[jk]==1){
                   4977:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4978:         }
                   4979:         for(j=1; j <=ncovmodel; j++){
                   4980:           printf("%12.7f ",p[jk]);
                   4981:           jk++; 
                   4982:         }
                   4983:         printf("\n");
                   4984:       }
                   4985:     }
                   4986:   }
                   4987: /* skipping */
                   4988:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   4989:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   4990:     for(k=1; k <=(nlstate+ndeath); k++){
                   4991:       if (k != i) {
                   4992:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4993:         if(flatdir[jk]==1){
                   4994:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   4995:           for(j=1; j <=ncovmodel;  jk++,j++){
                   4996:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   4997:             /*q[jjk]=p[jk];*/
                   4998:           }
                   4999:         }else{
                   5000:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   5001:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   5002:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   5003:             /*q[jjk]=p[jk];*/
                   5004:           }
                   5005:         }
                   5006:         printf("\n");
                   5007:       }
                   5008:       fflush(stdout);
                   5009:     }
                   5010:   }
                   5011:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   5012: #else  /* FLATSUP */
1.126     brouard  5013:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  5014: #endif  /* FLATSUP */
                   5015: 
                   5016: #ifdef LINMINORIGINAL
                   5017: #else
                   5018:       free_ivector(flatdir,1,npar); 
                   5019: #endif  /* LINMINORIGINAL*/
                   5020: #endif /* POWELL */
1.126     brouard  5021: 
1.162     brouard  5022: #ifdef NLOPT
                   5023: #ifdef NEWUOA
                   5024:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   5025: #else
                   5026:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   5027: #endif
                   5028:   lb=vector(0,npar-1);
                   5029:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   5030:   nlopt_set_lower_bounds(opt, lb);
                   5031:   nlopt_set_initial_step1(opt, 0.1);
                   5032:   
                   5033:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   5034:   d->function = func;
                   5035:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   5036:   nlopt_set_min_objective(opt, myfunc, d);
                   5037:   nlopt_set_xtol_rel(opt, ftol);
                   5038:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   5039:     printf("nlopt failed! %d\n",creturn); 
                   5040:   }
                   5041:   else {
                   5042:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   5043:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   5044:     iter=1; /* not equal */
                   5045:   }
                   5046:   nlopt_destroy(opt);
                   5047: #endif
1.319     brouard  5048: #ifdef FLATSUP
                   5049:   /* npared = npar -flatd/ncovmodel; */
                   5050:   /* xired= matrix(1,npared,1,npared); */
                   5051:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   5052:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   5053:   /* free_matrix(xire,1,npared,1,npared); */
                   5054: #else  /* FLATSUP */
                   5055: #endif /* FLATSUP */
1.126     brouard  5056:   free_matrix(xi,1,npar,1,npar);
                   5057:   fclose(ficrespow);
1.203     brouard  5058:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   5059:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  5060:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  5061: 
                   5062: }
                   5063: 
                   5064: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  5065: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  5066: {
                   5067:   double  **a,**y,*x,pd;
1.203     brouard  5068:   /* double **hess; */
1.164     brouard  5069:   int i, j;
1.126     brouard  5070:   int *indx;
                   5071: 
                   5072:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  5073:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  5074:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   5075:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   5076:   double gompertz(double p[]);
1.203     brouard  5077:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  5078: 
                   5079:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   5080:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   5081:   for (i=1;i<=npar;i++){
1.203     brouard  5082:     printf("%d-",i);fflush(stdout);
                   5083:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  5084:    
                   5085:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   5086:     
                   5087:     /*  printf(" %f ",p[i]);
                   5088:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   5089:   }
                   5090:   
                   5091:   for (i=1;i<=npar;i++) {
                   5092:     for (j=1;j<=npar;j++)  {
                   5093:       if (j>i) { 
1.203     brouard  5094:        printf(".%d-%d",i,j);fflush(stdout);
                   5095:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   5096:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  5097:        
                   5098:        hess[j][i]=hess[i][j];    
                   5099:        /*printf(" %lf ",hess[i][j]);*/
                   5100:       }
                   5101:     }
                   5102:   }
                   5103:   printf("\n");
                   5104:   fprintf(ficlog,"\n");
                   5105: 
                   5106:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   5107:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   5108:   
                   5109:   a=matrix(1,npar,1,npar);
                   5110:   y=matrix(1,npar,1,npar);
                   5111:   x=vector(1,npar);
                   5112:   indx=ivector(1,npar);
                   5113:   for (i=1;i<=npar;i++)
                   5114:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   5115:   ludcmp(a,npar,indx,&pd);
                   5116: 
                   5117:   for (j=1;j<=npar;j++) {
                   5118:     for (i=1;i<=npar;i++) x[i]=0;
                   5119:     x[j]=1;
                   5120:     lubksb(a,npar,indx,x);
                   5121:     for (i=1;i<=npar;i++){ 
                   5122:       matcov[i][j]=x[i];
                   5123:     }
                   5124:   }
                   5125: 
                   5126:   printf("\n#Hessian matrix#\n");
                   5127:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   5128:   for (i=1;i<=npar;i++) { 
                   5129:     for (j=1;j<=npar;j++) { 
1.203     brouard  5130:       printf("%.6e ",hess[i][j]);
                   5131:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  5132:     }
                   5133:     printf("\n");
                   5134:     fprintf(ficlog,"\n");
                   5135:   }
                   5136: 
1.203     brouard  5137:   /* printf("\n#Covariance matrix#\n"); */
                   5138:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   5139:   /* for (i=1;i<=npar;i++) {  */
                   5140:   /*   for (j=1;j<=npar;j++) {  */
                   5141:   /*     printf("%.6e ",matcov[i][j]); */
                   5142:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   5143:   /*   } */
                   5144:   /*   printf("\n"); */
                   5145:   /*   fprintf(ficlog,"\n"); */
                   5146:   /* } */
                   5147: 
1.126     brouard  5148:   /* Recompute Inverse */
1.203     brouard  5149:   /* for (i=1;i<=npar;i++) */
                   5150:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   5151:   /* ludcmp(a,npar,indx,&pd); */
                   5152: 
                   5153:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   5154: 
                   5155:   /* for (j=1;j<=npar;j++) { */
                   5156:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   5157:   /*   x[j]=1; */
                   5158:   /*   lubksb(a,npar,indx,x); */
                   5159:   /*   for (i=1;i<=npar;i++){  */
                   5160:   /*     y[i][j]=x[i]; */
                   5161:   /*     printf("%.3e ",y[i][j]); */
                   5162:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   5163:   /*   } */
                   5164:   /*   printf("\n"); */
                   5165:   /*   fprintf(ficlog,"\n"); */
                   5166:   /* } */
                   5167: 
                   5168:   /* Verifying the inverse matrix */
                   5169: #ifdef DEBUGHESS
                   5170:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  5171: 
1.203     brouard  5172:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   5173:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  5174: 
                   5175:   for (j=1;j<=npar;j++) {
                   5176:     for (i=1;i<=npar;i++){ 
1.203     brouard  5177:       printf("%.2f ",y[i][j]);
                   5178:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  5179:     }
                   5180:     printf("\n");
                   5181:     fprintf(ficlog,"\n");
                   5182:   }
1.203     brouard  5183: #endif
1.126     brouard  5184: 
                   5185:   free_matrix(a,1,npar,1,npar);
                   5186:   free_matrix(y,1,npar,1,npar);
                   5187:   free_vector(x,1,npar);
                   5188:   free_ivector(indx,1,npar);
1.203     brouard  5189:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  5190: 
                   5191: 
                   5192: }
                   5193: 
                   5194: /*************** hessian matrix ****************/
                   5195: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  5196: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  5197:   int i;
                   5198:   int l=1, lmax=20;
1.203     brouard  5199:   double k1,k2, res, fx;
1.132     brouard  5200:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  5201:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   5202:   int k=0,kmax=10;
                   5203:   double l1;
                   5204: 
                   5205:   fx=func(x);
                   5206:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  5207:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  5208:     l1=pow(10,l);
                   5209:     delts=delt;
                   5210:     for(k=1 ; k <kmax; k=k+1){
                   5211:       delt = delta*(l1*k);
                   5212:       p2[theta]=x[theta] +delt;
1.145     brouard  5213:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  5214:       p2[theta]=x[theta]-delt;
                   5215:       k2=func(p2)-fx;
                   5216:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  5217:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  5218:       
1.203     brouard  5219: #ifdef DEBUGHESSII
1.126     brouard  5220:       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);
                   5221:       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);
                   5222: #endif
                   5223:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   5224:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   5225:        k=kmax;
                   5226:       }
                   5227:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  5228:        k=kmax; l=lmax*10;
1.126     brouard  5229:       }
                   5230:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   5231:        delts=delt;
                   5232:       }
1.203     brouard  5233:     } /* End loop k */
1.126     brouard  5234:   }
                   5235:   delti[theta]=delts;
                   5236:   return res; 
                   5237:   
                   5238: }
                   5239: 
1.203     brouard  5240: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  5241: {
                   5242:   int i;
1.164     brouard  5243:   int l=1, lmax=20;
1.126     brouard  5244:   double k1,k2,k3,k4,res,fx;
1.132     brouard  5245:   double p2[MAXPARM+1];
1.203     brouard  5246:   int k, kmax=1;
                   5247:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  5248: 
                   5249:   int firstime=0;
1.203     brouard  5250:   
1.126     brouard  5251:   fx=func(x);
1.203     brouard  5252:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  5253:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  5254:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5255:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5256:     k1=func(p2)-fx;
                   5257:   
1.203     brouard  5258:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5259:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5260:     k2=func(p2)-fx;
                   5261:   
1.203     brouard  5262:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5263:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5264:     k3=func(p2)-fx;
                   5265:   
1.203     brouard  5266:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5267:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5268:     k4=func(p2)-fx;
1.203     brouard  5269:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   5270:     if(k1*k2*k3*k4 <0.){
1.208     brouard  5271:       firstime=1;
1.203     brouard  5272:       kmax=kmax+10;
1.208     brouard  5273:     }
                   5274:     if(kmax >=10 || firstime ==1){
1.246     brouard  5275:       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);
                   5276:       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  5277:       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);
                   5278:       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);
                   5279:     }
                   5280: #ifdef DEBUGHESSIJ
                   5281:     v1=hess[thetai][thetai];
                   5282:     v2=hess[thetaj][thetaj];
                   5283:     cv12=res;
                   5284:     /* Computing eigen value of Hessian matrix */
                   5285:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5286:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5287:     if ((lc2 <0) || (lc1 <0) ){
                   5288:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5289:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5290:       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);
                   5291:       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);
                   5292:     }
1.126     brouard  5293: #endif
                   5294:   }
                   5295:   return res;
                   5296: }
                   5297: 
1.203     brouard  5298:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   5299: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   5300: /* { */
                   5301: /*   int i; */
                   5302: /*   int l=1, lmax=20; */
                   5303: /*   double k1,k2,k3,k4,res,fx; */
                   5304: /*   double p2[MAXPARM+1]; */
                   5305: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   5306: /*   int k=0,kmax=10; */
                   5307: /*   double l1; */
                   5308:   
                   5309: /*   fx=func(x); */
                   5310: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   5311: /*     l1=pow(10,l); */
                   5312: /*     delts=delt; */
                   5313: /*     for(k=1 ; k <kmax; k=k+1){ */
                   5314: /*       delt = delti*(l1*k); */
                   5315: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   5316: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5317: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5318: /*       k1=func(p2)-fx; */
                   5319:       
                   5320: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5321: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5322: /*       k2=func(p2)-fx; */
                   5323:       
                   5324: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5325: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5326: /*       k3=func(p2)-fx; */
                   5327:       
                   5328: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5329: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5330: /*       k4=func(p2)-fx; */
                   5331: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   5332: /* #ifdef DEBUGHESSIJ */
                   5333: /*       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); */
                   5334: /*       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); */
                   5335: /* #endif */
                   5336: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   5337: /*     k=kmax; */
                   5338: /*       } */
                   5339: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   5340: /*     k=kmax; l=lmax*10; */
                   5341: /*       } */
                   5342: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   5343: /*     delts=delt; */
                   5344: /*       } */
                   5345: /*     } /\* End loop k *\/ */
                   5346: /*   } */
                   5347: /*   delti[theta]=delts; */
                   5348: /*   return res;  */
                   5349: /* } */
                   5350: 
                   5351: 
1.126     brouard  5352: /************** Inverse of matrix **************/
                   5353: void ludcmp(double **a, int n, int *indx, double *d) 
                   5354: { 
                   5355:   int i,imax,j,k; 
                   5356:   double big,dum,sum,temp; 
                   5357:   double *vv; 
                   5358:  
                   5359:   vv=vector(1,n); 
                   5360:   *d=1.0; 
                   5361:   for (i=1;i<=n;i++) { 
                   5362:     big=0.0; 
                   5363:     for (j=1;j<=n;j++) 
                   5364:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  5365:     if (big == 0.0){
                   5366:       printf(" Singular Hessian matrix at row %d:\n",i);
                   5367:       for (j=1;j<=n;j++) {
                   5368:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   5369:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   5370:       }
                   5371:       fflush(ficlog);
                   5372:       fclose(ficlog);
                   5373:       nrerror("Singular matrix in routine ludcmp"); 
                   5374:     }
1.126     brouard  5375:     vv[i]=1.0/big; 
                   5376:   } 
                   5377:   for (j=1;j<=n;j++) { 
                   5378:     for (i=1;i<j;i++) { 
                   5379:       sum=a[i][j]; 
                   5380:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   5381:       a[i][j]=sum; 
                   5382:     } 
                   5383:     big=0.0; 
                   5384:     for (i=j;i<=n;i++) { 
                   5385:       sum=a[i][j]; 
                   5386:       for (k=1;k<j;k++) 
                   5387:        sum -= a[i][k]*a[k][j]; 
                   5388:       a[i][j]=sum; 
                   5389:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   5390:        big=dum; 
                   5391:        imax=i; 
                   5392:       } 
                   5393:     } 
                   5394:     if (j != imax) { 
                   5395:       for (k=1;k<=n;k++) { 
                   5396:        dum=a[imax][k]; 
                   5397:        a[imax][k]=a[j][k]; 
                   5398:        a[j][k]=dum; 
                   5399:       } 
                   5400:       *d = -(*d); 
                   5401:       vv[imax]=vv[j]; 
                   5402:     } 
                   5403:     indx[j]=imax; 
                   5404:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   5405:     if (j != n) { 
                   5406:       dum=1.0/(a[j][j]); 
                   5407:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   5408:     } 
                   5409:   } 
                   5410:   free_vector(vv,1,n);  /* Doesn't work */
                   5411: ;
                   5412: } 
                   5413: 
                   5414: void lubksb(double **a, int n, int *indx, double b[]) 
                   5415: { 
                   5416:   int i,ii=0,ip,j; 
                   5417:   double sum; 
                   5418:  
                   5419:   for (i=1;i<=n;i++) { 
                   5420:     ip=indx[i]; 
                   5421:     sum=b[ip]; 
                   5422:     b[ip]=b[i]; 
                   5423:     if (ii) 
                   5424:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   5425:     else if (sum) ii=i; 
                   5426:     b[i]=sum; 
                   5427:   } 
                   5428:   for (i=n;i>=1;i--) { 
                   5429:     sum=b[i]; 
                   5430:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   5431:     b[i]=sum/a[i][i]; 
                   5432:   } 
                   5433: } 
                   5434: 
                   5435: void pstamp(FILE *fichier)
                   5436: {
1.196     brouard  5437:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  5438: }
                   5439: 
1.297     brouard  5440: void date2dmy(double date,double *day, double *month, double *year){
                   5441:   double yp=0., yp1=0., yp2=0.;
                   5442:   
                   5443:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   5444:                        fractional in yp1 */
                   5445:   *year=yp;
                   5446:   yp2=modf((yp1*12),&yp);
                   5447:   *month=yp;
                   5448:   yp1=modf((yp2*30.5),&yp);
                   5449:   *day=yp;
                   5450:   if(*day==0) *day=1;
                   5451:   if(*month==0) *month=1;
                   5452: }
                   5453: 
1.253     brouard  5454: 
                   5455: 
1.126     brouard  5456: /************ Frequencies ********************/
1.251     brouard  5457: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  5458:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   5459:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  5460: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  5461:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  5462:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  5463:   int iind=0, iage=0;
                   5464:   int mi; /* Effective wave */
                   5465:   int first;
                   5466:   double ***freq; /* Frequencies */
1.268     brouard  5467:   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 */
                   5468:   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  5469:   double *meanq, *stdq, *idq;
1.226     brouard  5470:   double **meanqt;
                   5471:   double *pp, **prop, *posprop, *pospropt;
                   5472:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   5473:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   5474:   double agebegin, ageend;
                   5475:     
                   5476:   pp=vector(1,nlstate);
1.251     brouard  5477:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  5478:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   5479:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   5480:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   5481:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  5482:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  5483:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  5484:   meanqt=matrix(1,lastpass,1,nqtveff);
                   5485:   strcpy(fileresp,"P_");
                   5486:   strcat(fileresp,fileresu);
                   5487:   /*strcat(fileresphtm,fileresu);*/
                   5488:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   5489:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   5490:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   5491:     exit(0);
                   5492:   }
1.240     brouard  5493:   
1.226     brouard  5494:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   5495:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   5496:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5497:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5498:     fflush(ficlog);
                   5499:     exit(70); 
                   5500:   }
                   5501:   else{
                   5502:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  5503: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  5504: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5505:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5506:   }
1.319     brouard  5507:   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  5508:   
1.226     brouard  5509:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   5510:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   5511:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5512:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5513:     fflush(ficlog);
                   5514:     exit(70); 
1.240     brouard  5515:   } else{
1.226     brouard  5516:     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  5517: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  5518: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5519:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5520:   }
1.319     brouard  5521:   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  5522:   
1.253     brouard  5523:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   5524:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  5525:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  5526:   j1=0;
1.126     brouard  5527:   
1.227     brouard  5528:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335     brouard  5529:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  5530:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  5531:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  5532:   
                   5533:   
1.226     brouard  5534:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   5535:      reference=low_education V1=0,V2=0
                   5536:      med_educ                V1=1 V2=0, 
                   5537:      high_educ               V1=0 V2=1
1.330     brouard  5538:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  5539:   */
1.249     brouard  5540:   dateintsum=0;
                   5541:   k2cpt=0;
                   5542: 
1.253     brouard  5543:   if(cptcoveff == 0 )
1.265     brouard  5544:     nl=1;  /* Constant and age model only */
1.253     brouard  5545:   else
                   5546:     nl=2;
1.265     brouard  5547: 
                   5548:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   5549:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335     brouard  5550:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  5551:    *     freq[s1][s2][iage] =0.
                   5552:    *     Loop on iind
                   5553:    *       ++freq[s1][s2][iage] weighted
                   5554:    *     end iind
                   5555:    *     if covariate and j!0
                   5556:    *       headers Variable on one line
                   5557:    *     endif cov j!=0
                   5558:    *     header of frequency table by age
                   5559:    *     Loop on age
                   5560:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   5561:    *       pos+=freq[s1][s2][iage] weighted
                   5562:    *       Loop on s1 initial state
                   5563:    *         fprintf(ficresp
                   5564:    *       end s1
                   5565:    *     end age
                   5566:    *     if j!=0 computes starting values
                   5567:    *     end compute starting values
                   5568:    *   end j1
                   5569:    * end nl 
                   5570:    */
1.253     brouard  5571:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   5572:     if(nj==1)
                   5573:       j=0;  /* First pass for the constant */
1.265     brouard  5574:     else{
1.335     brouard  5575:       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  5576:     }
1.251     brouard  5577:     first=1;
1.332     brouard  5578:     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  5579:       posproptt=0.;
1.330     brouard  5580:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  5581:        scanf("%d", i);*/
                   5582:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  5583:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  5584:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  5585:            freq[i][s2][m]=0;
1.251     brouard  5586:       
                   5587:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  5588:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  5589:          prop[i][m]=0;
                   5590:        posprop[i]=0;
                   5591:        pospropt[i]=0;
                   5592:       }
1.283     brouard  5593:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  5594:         idq[z1]=0.;
                   5595:         meanq[z1]=0.;
                   5596:         stdq[z1]=0.;
1.283     brouard  5597:       }
                   5598:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  5599:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  5600:       /*         meanqt[m][z1]=0.; */
                   5601:       /*       } */
                   5602:       /* }       */
1.251     brouard  5603:       /* dateintsum=0; */
                   5604:       /* k2cpt=0; */
                   5605:       
1.265     brouard  5606:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  5607:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   5608:        bool=1;
                   5609:        if(j !=0){
                   5610:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335     brouard  5611:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   5612:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  5613:                /* if(Tvaraff[z1] ==-20){ */
                   5614:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   5615:                /* }else  if(Tvaraff[z1] ==-10){ */
                   5616:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  5617:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335     brouard  5618:                /* 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); */
                   5619:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
1.338     brouard  5620:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  5621:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  5622:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  5623:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  5624:                  /* 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", */
                   5625:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   5626:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  5627:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   5628:                } /* Onlyf fixed */
                   5629:              } /* end z1 */
1.335     brouard  5630:            } /* cptcoveff > 0 */
1.251     brouard  5631:          } /* end any */
                   5632:        }/* end j==0 */
1.265     brouard  5633:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  5634:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  5635:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  5636:            m=mw[mi][iind];
                   5637:            if(j!=0){
                   5638:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335     brouard  5639:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  5640:                  if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  5641:                    /* iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /\* Good *\/ */
                   5642:                    iv= Tvar[Tmodelind[z1]]; /* Good *//* because cotvar starts now at first at ncovcol+nqv+ntv */ 
1.332     brouard  5643:                    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  5644:                                                                                      value is -1, we don't select. It differs from the 
                   5645:                                                                                      constant and age model which counts them. */
                   5646:                      bool=0; /* not selected */
                   5647:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  5648:                    /* i1=Tvaraff[z1]; */
                   5649:                    /* i2=TnsdVar[i1]; */
                   5650:                    /* i3=nbcode[i1][i2]; */
                   5651:                    /* i4=covar[i1][iind]; */
                   5652:                    /* if(i4 != i3){ */
                   5653:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  5654:                      bool=0;
                   5655:                    }
                   5656:                  }
                   5657:                }
                   5658:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   5659:            } /* end j==0 */
                   5660:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  5661:            if(bool==1){ /*Selected */
1.251     brouard  5662:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   5663:                 and mw[mi+1][iind]. dh depends on stepm. */
                   5664:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   5665:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   5666:              if(m >=firstpass && m <=lastpass){
                   5667:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   5668:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   5669:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   5670:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   5671:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   5672:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   5673:                if (m<lastpass) {
                   5674:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   5675:                  /*   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]); */
                   5676:                  if(s[m][iind]==-1)
                   5677:                    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.));
                   5678:                  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  5679:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   5680:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  5681:                      idq[z1]=idq[z1]+weight[iind];
                   5682:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   5683:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   5684:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  5685:                    }
1.284     brouard  5686:                  }
1.251     brouard  5687:                  /* if((int)agev[m][iind] == 55) */
                   5688:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5689:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5690:                  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  5691:                }
1.251     brouard  5692:              } /* end if between passes */  
                   5693:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5694:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5695:                k2cpt++;
                   5696:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  5697:              }
1.251     brouard  5698:            }else{
                   5699:              bool=1;
                   5700:            }/* end bool 2 */
                   5701:          } /* end m */
1.284     brouard  5702:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5703:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5704:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5705:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5706:          /* } */
1.251     brouard  5707:        } /* end bool */
                   5708:       } /* end iind = 1 to imx */
1.319     brouard  5709:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  5710:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5711:       
                   5712:       
                   5713:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335     brouard  5714:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  5715:         pstamp(ficresp);
1.335     brouard  5716:       if  (cptcoveff>0 && j!=0){
1.265     brouard  5717:         pstamp(ficresp);
1.251     brouard  5718:        printf( "\n#********** Variable "); 
                   5719:        fprintf(ficresp, "\n#********** Variable "); 
                   5720:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5721:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5722:        fprintf(ficlog, "\n#********** Variable "); 
1.340     brouard  5723:        for (z1=1; z1<=cptcoveff; z1++){
1.251     brouard  5724:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  5725:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5726:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5727:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5728:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5729:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  5730:          }else{
1.330     brouard  5731:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5732:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5733:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5734:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5735:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5736:          }
                   5737:        }
                   5738:        printf( "**********\n#");
                   5739:        fprintf(ficresp, "**********\n#");
                   5740:        fprintf(ficresphtm, "**********</h3>\n");
                   5741:        fprintf(ficresphtmfr, "**********</h3>\n");
                   5742:        fprintf(ficlog, "**********\n");
                   5743:       }
1.284     brouard  5744:       /*
                   5745:        Printing means of quantitative variables if any
                   5746:       */
                   5747:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5748:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5749:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5750:        if(weightopt==1){
                   5751:          printf(" Weighted mean and standard deviation of");
                   5752:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5753:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5754:        }
1.311     brouard  5755:        /* mu = \frac{w x}{\sum w}
                   5756:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5757:        */
                   5758:        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]));
                   5759:        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]));
                   5760:        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  5761:       }
                   5762:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5763:       /*       for(m=1;m<=lastpass;m++){ */
                   5764:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5765:       /*   } */
                   5766:       /* } */
1.283     brouard  5767: 
1.251     brouard  5768:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335     brouard  5769:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  5770:         fprintf(ficresp, " Age");
1.335     brouard  5771:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   5772:          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]]);
                   5773:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5774:        }
1.251     brouard  5775:       for(i=1; i<=nlstate;i++) {
1.335     brouard  5776:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5777:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5778:       }
1.335     brouard  5779:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5780:       fprintf(ficresphtm, "\n");
                   5781:       
                   5782:       /* Header of frequency table by age */
                   5783:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5784:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5785:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5786:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5787:          if(s2!=0 && m!=0)
                   5788:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5789:        }
1.226     brouard  5790:       }
1.251     brouard  5791:       fprintf(ficresphtmfr, "\n");
                   5792:     
                   5793:       /* For each age */
                   5794:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5795:        fprintf(ficresphtm,"<tr>");
                   5796:        if(iage==iagemax+1){
                   5797:          fprintf(ficlog,"1");
                   5798:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5799:        }else if(iage==iagemax+2){
                   5800:          fprintf(ficlog,"0");
                   5801:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5802:        }else if(iage==iagemax+3){
                   5803:          fprintf(ficlog,"Total");
                   5804:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5805:        }else{
1.240     brouard  5806:          if(first==1){
1.251     brouard  5807:            first=0;
                   5808:            printf("See log file for details...\n");
                   5809:          }
                   5810:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5811:          fprintf(ficlog,"Age %d", iage);
                   5812:        }
1.265     brouard  5813:        for(s1=1; s1 <=nlstate ; s1++){
                   5814:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5815:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5816:        }
1.265     brouard  5817:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5818:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5819:            pos += freq[s1][m][iage];
                   5820:          if(pp[s1]>=1.e-10){
1.251     brouard  5821:            if(first==1){
1.265     brouard  5822:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5823:            }
1.265     brouard  5824:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5825:          }else{
                   5826:            if(first==1)
1.265     brouard  5827:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5828:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5829:          }
                   5830:        }
                   5831:       
1.265     brouard  5832:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5833:          /* posprop[s1]=0; */
                   5834:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5835:            pp[s1] += freq[s1][m][iage];
                   5836:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5837:       
                   5838:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5839:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5840:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5841:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5842:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5843:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5844:        }
                   5845:        
                   5846:        /* Writing ficresp */
1.335     brouard  5847:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5848:           if( iage <= iagemax){
                   5849:            fprintf(ficresp," %d",iage);
                   5850:           }
                   5851:         }else if( nj==2){
                   5852:           if( iage <= iagemax){
                   5853:            fprintf(ficresp," %d",iage);
1.335     brouard  5854:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  5855:           }
1.240     brouard  5856:        }
1.265     brouard  5857:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5858:          if(pos>=1.e-5){
1.251     brouard  5859:            if(first==1)
1.265     brouard  5860:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5861:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5862:          }else{
                   5863:            if(first==1)
1.265     brouard  5864:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5865:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5866:          }
                   5867:          if( iage <= iagemax){
                   5868:            if(pos>=1.e-5){
1.335     brouard  5869:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5870:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5871:               }else if( nj==2){
                   5872:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5873:               }
                   5874:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5875:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5876:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5877:            } else{
1.335     brouard  5878:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  5879:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5880:            }
1.240     brouard  5881:          }
1.265     brouard  5882:          pospropt[s1] +=posprop[s1];
                   5883:        } /* end loop s1 */
1.251     brouard  5884:        /* pospropt=0.; */
1.265     brouard  5885:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5886:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5887:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5888:              if(first==1){
1.265     brouard  5889:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5890:              }
1.265     brouard  5891:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5892:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5893:            }
1.265     brouard  5894:            if(s1!=0 && m!=0)
                   5895:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5896:          }
1.265     brouard  5897:        } /* end loop s1 */
1.251     brouard  5898:        posproptt=0.; 
1.265     brouard  5899:        for(s1=1; s1 <=nlstate; s1++){
                   5900:          posproptt += pospropt[s1];
1.251     brouard  5901:        }
                   5902:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5903:        fprintf(ficresphtm,"</tr>\n");
1.335     brouard  5904:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  5905:          if(iage <= iagemax)
                   5906:            fprintf(ficresp,"\n");
1.240     brouard  5907:        }
1.251     brouard  5908:        if(first==1)
                   5909:          printf("Others in log...\n");
                   5910:        fprintf(ficlog,"\n");
                   5911:       } /* end loop age iage */
1.265     brouard  5912:       
1.251     brouard  5913:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5914:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5915:        if(posproptt < 1.e-5){
1.265     brouard  5916:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5917:        }else{
1.265     brouard  5918:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5919:        }
1.226     brouard  5920:       }
1.251     brouard  5921:       fprintf(ficresphtm,"</tr>\n");
                   5922:       fprintf(ficresphtm,"</table>\n");
                   5923:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5924:       if(posproptt < 1.e-5){
1.251     brouard  5925:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5926:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5927:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5928:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5929:        invalidvarcomb[j1]=1;
1.226     brouard  5930:       }else{
1.338     brouard  5931:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
1.251     brouard  5932:        invalidvarcomb[j1]=0;
1.226     brouard  5933:       }
1.251     brouard  5934:       fprintf(ficresphtmfr,"</table>\n");
                   5935:       fprintf(ficlog,"\n");
                   5936:       if(j!=0){
                   5937:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5938:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5939:          for(k=1; k <=(nlstate+ndeath); k++){
                   5940:            if (k != i) {
1.265     brouard  5941:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5942:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5943:                  if(j1==1){ /* All dummy covariates to zero */
                   5944:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5945:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5946:                    printf("%d%d ",i,k);
                   5947:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5948:                    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]));
                   5949:                    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]));
                   5950:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5951:                  }
1.253     brouard  5952:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5953:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5954:                    x[iage]= (double)iage;
                   5955:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5956:                    /* 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  5957:                  }
1.268     brouard  5958:                  /* Some are not finite, but linreg will ignore these ages */
                   5959:                  no=0;
1.253     brouard  5960:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5961:                  pstart[s1]=b;
                   5962:                  pstart[s1-1]=a;
1.252     brouard  5963:                }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 */ 
                   5964:                  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]);
                   5965:                  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  5966:                  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  5967:                  printf("%d%d ",i,k);
                   5968:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5969:                  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  5970:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5971:                  ;
                   5972:                }
                   5973:                /* printf("%12.7f )", param[i][jj][k]); */
                   5974:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5975:                s1++; 
1.251     brouard  5976:              } /* end jj */
                   5977:            } /* end k!= i */
                   5978:          } /* end k */
1.265     brouard  5979:        } /* end i, s1 */
1.251     brouard  5980:       } /* end j !=0 */
                   5981:     } /* end selected combination of covariate j1 */
                   5982:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5983:       printf("#Freqsummary: Starting values for the constants:\n");
                   5984:       fprintf(ficlog,"\n");
1.265     brouard  5985:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5986:        for(k=1; k <=(nlstate+ndeath); k++){
                   5987:          if (k != i) {
                   5988:            printf("%d%d ",i,k);
                   5989:            fprintf(ficlog,"%d%d ",i,k);
                   5990:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5991:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5992:              if(jj==1){ /* Age has to be done */
1.265     brouard  5993:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5994:                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]));
                   5995:                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  5996:              }
                   5997:              /* printf("%12.7f )", param[i][jj][k]); */
                   5998:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5999:              s1++; 
1.250     brouard  6000:            }
1.251     brouard  6001:            printf("\n");
                   6002:            fprintf(ficlog,"\n");
1.250     brouard  6003:          }
                   6004:        }
1.284     brouard  6005:       } /* end of state i */
1.251     brouard  6006:       printf("#Freqsummary\n");
                   6007:       fprintf(ficlog,"\n");
1.265     brouard  6008:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   6009:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   6010:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   6011:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   6012:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   6013:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   6014:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   6015:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  6016:          /* } */
                   6017:        }
1.265     brouard  6018:       } /* end loop s1 */
1.251     brouard  6019:       
                   6020:       printf("\n");
                   6021:       fprintf(ficlog,"\n");
                   6022:     } /* end j=0 */
1.249     brouard  6023:   } /* end j */
1.252     brouard  6024: 
1.253     brouard  6025:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  6026:     for(i=1, jk=1; i <=nlstate; i++){
                   6027:       for(j=1; j <=nlstate+ndeath; j++){
                   6028:        if(j!=i){
                   6029:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   6030:          printf("%1d%1d",i,j);
                   6031:          fprintf(ficparo,"%1d%1d",i,j);
                   6032:          for(k=1; k<=ncovmodel;k++){
                   6033:            /*    printf(" %lf",param[i][j][k]); */
                   6034:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   6035:            p[jk]=pstart[jk];
                   6036:            printf(" %f ",pstart[jk]);
                   6037:            fprintf(ficparo," %f ",pstart[jk]);
                   6038:            jk++;
                   6039:          }
                   6040:          printf("\n");
                   6041:          fprintf(ficparo,"\n");
                   6042:        }
                   6043:       }
                   6044:     }
                   6045:   } /* end mle=-2 */
1.226     brouard  6046:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  6047:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  6048:   
1.226     brouard  6049:   fclose(ficresp);
                   6050:   fclose(ficresphtm);
                   6051:   fclose(ficresphtmfr);
1.283     brouard  6052:   free_vector(idq,1,nqfveff);
1.226     brouard  6053:   free_vector(meanq,1,nqfveff);
1.284     brouard  6054:   free_vector(stdq,1,nqfveff);
1.226     brouard  6055:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  6056:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   6057:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  6058:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  6059:   free_vector(pospropt,1,nlstate);
                   6060:   free_vector(posprop,1,nlstate);
1.251     brouard  6061:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  6062:   free_vector(pp,1,nlstate);
                   6063:   /* End of freqsummary */
                   6064: }
1.126     brouard  6065: 
1.268     brouard  6066: /* Simple linear regression */
                   6067: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   6068: 
                   6069:   /* y=a+bx regression */
                   6070:   double   sumx = 0.0;                        /* sum of x                      */
                   6071:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   6072:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   6073:   double   sumy = 0.0;                        /* sum of y                      */
                   6074:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   6075:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   6076:   double yhat;
                   6077:   
                   6078:   double denom=0;
                   6079:   int i;
                   6080:   int ne=*no;
                   6081:   
                   6082:   for ( i=ifi, ne=0;i<=ila;i++) {
                   6083:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   6084:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   6085:       continue;
                   6086:     }
                   6087:     ne=ne+1;
                   6088:     sumx  += x[i];       
                   6089:     sumx2 += x[i]*x[i];  
                   6090:     sumxy += x[i] * y[i];
                   6091:     sumy  += y[i];      
                   6092:     sumy2 += y[i]*y[i]; 
                   6093:     denom = (ne * sumx2 - sumx*sumx);
                   6094:     /* 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); */
                   6095:   } 
                   6096:   
                   6097:   denom = (ne * sumx2 - sumx*sumx);
                   6098:   if (denom == 0) {
                   6099:     // vertical, slope m is infinity
                   6100:     *b = INFINITY;
                   6101:     *a = 0;
                   6102:     if (r) *r = 0;
                   6103:     return 1;
                   6104:   }
                   6105:   
                   6106:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   6107:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   6108:   if (r!=NULL) {
                   6109:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   6110:       sqrt((sumx2 - sumx*sumx/ne) *
                   6111:           (sumy2 - sumy*sumy/ne));
                   6112:   }
                   6113:   *no=ne;
                   6114:   for ( i=ifi, ne=0;i<=ila;i++) {
                   6115:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   6116:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   6117:       continue;
                   6118:     }
                   6119:     ne=ne+1;
                   6120:     yhat = y[i] - *a -*b* x[i];
                   6121:     sume2  += yhat * yhat ;       
                   6122:     
                   6123:     denom = (ne * sumx2 - sumx*sumx);
                   6124:     /* 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); */
                   6125:   } 
                   6126:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   6127:   *sa= *sb * sqrt(sumx2/ne);
                   6128:   
                   6129:   return 0; 
                   6130: }
                   6131: 
1.126     brouard  6132: /************ Prevalence ********************/
1.227     brouard  6133: 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)
                   6134: {  
                   6135:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   6136:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   6137:      We still use firstpass and lastpass as another selection.
                   6138:   */
1.126     brouard  6139:  
1.227     brouard  6140:   int i, m, jk, j1, bool, z1,j, iv;
                   6141:   int mi; /* Effective wave */
                   6142:   int iage;
                   6143:   double agebegin, ageend;
                   6144: 
                   6145:   double **prop;
                   6146:   double posprop; 
                   6147:   double  y2; /* in fractional years */
                   6148:   int iagemin, iagemax;
                   6149:   int first; /** to stop verbosity which is redirected to log file */
                   6150: 
                   6151:   iagemin= (int) agemin;
                   6152:   iagemax= (int) agemax;
                   6153:   /*pp=vector(1,nlstate);*/
1.251     brouard  6154:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  6155:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   6156:   j1=0;
1.222     brouard  6157:   
1.227     brouard  6158:   /*j=cptcoveff;*/
                   6159:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  6160:   
1.288     brouard  6161:   first=0;
1.335     brouard  6162:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  6163:     for (i=1; i<=nlstate; i++)  
1.251     brouard  6164:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  6165:        prop[i][iage]=0.0;
                   6166:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   6167:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   6168:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   6169:     
                   6170:     for (i=1; i<=imx; i++) { /* Each individual */
                   6171:       bool=1;
                   6172:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   6173:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   6174:        m=mw[mi][i];
                   6175:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   6176:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   6177:        for (z1=1; z1<=cptcoveff; z1++){
                   6178:          if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  6179:            iv= Tvar[Tmodelind[z1]];/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.332     brouard  6180:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  6181:              bool=0;
                   6182:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  6183:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  6184:              bool=0;
                   6185:            }
                   6186:        }
                   6187:        if(bool==1){ /* Otherwise we skip that wave/person */
                   6188:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   6189:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   6190:          if(m >=firstpass && m <=lastpass){
                   6191:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   6192:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   6193:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   6194:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  6195:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  6196:                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); 
                   6197:                exit(1);
                   6198:              }
                   6199:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   6200:                /*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]]);*/
                   6201:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   6202:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   6203:              } /* end valid statuses */ 
                   6204:            } /* end selection of dates */
                   6205:          } /* end selection of waves */
                   6206:        } /* end bool */
                   6207:       } /* end wave */
                   6208:     } /* end individual */
                   6209:     for(i=iagemin; i <= iagemax+3; i++){  
                   6210:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   6211:        posprop += prop[jk][i]; 
                   6212:       } 
                   6213:       
                   6214:       for(jk=1; jk <=nlstate ; jk++){      
                   6215:        if( i <=  iagemax){ 
                   6216:          if(posprop>=1.e-5){ 
                   6217:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   6218:          } else{
1.288     brouard  6219:            if(!first){
                   6220:              first=1;
1.266     brouard  6221:              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]);
                   6222:            }else{
1.288     brouard  6223:              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  6224:            }
                   6225:          }
                   6226:        } 
                   6227:       }/* end jk */ 
                   6228:     }/* end i */ 
1.222     brouard  6229:      /*} *//* end i1 */
1.227     brouard  6230:   } /* end j1 */
1.222     brouard  6231:   
1.227     brouard  6232:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   6233:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  6234:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  6235: }  /* End of prevalence */
1.126     brouard  6236: 
                   6237: /************* Waves Concatenation ***************/
                   6238: 
                   6239: 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)
                   6240: {
1.298     brouard  6241:   /* 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  6242:      Death is a valid wave (if date is known).
                   6243:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   6244:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  6245:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  6246:   */
1.126     brouard  6247: 
1.224     brouard  6248:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  6249:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   6250:      double sum=0., jmean=0.;*/
1.224     brouard  6251:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  6252:   int j, k=0,jk, ju, jl;
                   6253:   double sum=0.;
                   6254:   first=0;
1.214     brouard  6255:   firstwo=0;
1.217     brouard  6256:   firsthree=0;
1.218     brouard  6257:   firstfour=0;
1.164     brouard  6258:   jmin=100000;
1.126     brouard  6259:   jmax=-1;
                   6260:   jmean=0.;
1.224     brouard  6261: 
                   6262: /* Treating live states */
1.214     brouard  6263:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  6264:     mi=0;  /* First valid wave */
1.227     brouard  6265:     mli=0; /* Last valid wave */
1.309     brouard  6266:     m=firstpass;  /* Loop on waves */
                   6267:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  6268:       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 */
                   6269:        mli=m-1;/* mw[++mi][i]=m-1; */
                   6270:       }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  6271:        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  6272:        mli=m;
1.224     brouard  6273:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   6274:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  6275:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  6276:       }
1.309     brouard  6277:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  6278: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  6279:        break;
1.224     brouard  6280: #else
1.317     brouard  6281:        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  6282:          if(firsthree == 0){
1.302     brouard  6283:            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  6284:            firsthree=1;
1.317     brouard  6285:          }else if(firsthree >=1 && firsthree < 10){
                   6286:            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);
                   6287:            firsthree++;
                   6288:          }else if(firsthree == 10){
                   6289:            printf("Information, too many Information flags: no more reported to log either\n");
                   6290:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   6291:            firsthree++;
                   6292:          }else{
                   6293:            firsthree++;
1.227     brouard  6294:          }
1.309     brouard  6295:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  6296:          mli=m;
                   6297:        }
                   6298:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   6299:          nbwarn++;
1.309     brouard  6300:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  6301:            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);
                   6302:            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);
                   6303:          }
                   6304:          break;
                   6305:        }
                   6306:        break;
1.224     brouard  6307: #endif
1.227     brouard  6308:       }/* End m >= lastpass */
1.126     brouard  6309:     }/* end while */
1.224     brouard  6310: 
1.227     brouard  6311:     /* 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  6312:     /* After last pass */
1.224     brouard  6313: /* Treating death states */
1.214     brouard  6314:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  6315:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   6316:       /* } */
1.126     brouard  6317:       mi++;    /* Death is another wave */
                   6318:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  6319:       /* Only death is a correct wave */
1.126     brouard  6320:       mw[mi][i]=m;
1.257     brouard  6321:     } /* else not in a death state */
1.224     brouard  6322: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  6323:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  6324:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  6325:        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  6326:          nbwarn++;
                   6327:          if(firstfiv==0){
1.309     brouard  6328:            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  6329:            firstfiv=1;
                   6330:          }else{
1.309     brouard  6331:            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  6332:          }
1.309     brouard  6333:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   6334:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  6335:          nberr++;
                   6336:          if(firstwo==0){
1.309     brouard  6337:            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  6338:            firstwo=1;
                   6339:          }
1.309     brouard  6340:          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  6341:        }
1.257     brouard  6342:       }else{ /* if date of interview is unknown */
1.227     brouard  6343:        /* death is known but not confirmed by death status at any wave */
                   6344:        if(firstfour==0){
1.309     brouard  6345:          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  6346:          firstfour=1;
                   6347:        }
1.309     brouard  6348:        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  6349:       }
1.224     brouard  6350:     } /* end if date of death is known */
                   6351: #endif
1.309     brouard  6352:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   6353:     /* wav[i]=mw[mi][i];   */
1.126     brouard  6354:     if(mi==0){
                   6355:       nbwarn++;
                   6356:       if(first==0){
1.227     brouard  6357:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   6358:        first=1;
1.126     brouard  6359:       }
                   6360:       if(first==1){
1.227     brouard  6361:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  6362:       }
                   6363:     } /* end mi==0 */
                   6364:   } /* End individuals */
1.214     brouard  6365:   /* wav and mw are no more changed */
1.223     brouard  6366:        
1.317     brouard  6367:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6368:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6369: 
                   6370: 
1.126     brouard  6371:   for(i=1; i<=imx; i++){
                   6372:     for(mi=1; mi<wav[i];mi++){
                   6373:       if (stepm <=0)
1.227     brouard  6374:        dh[mi][i]=1;
1.126     brouard  6375:       else{
1.260     brouard  6376:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  6377:          if (agedc[i] < 2*AGESUP) {
                   6378:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   6379:            if(j==0) j=1;  /* Survives at least one month after exam */
                   6380:            else if(j<0){
                   6381:              nberr++;
                   6382:              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]);
                   6383:              j=1; /* Temporary Dangerous patch */
                   6384:              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);
                   6385:              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]);
                   6386:              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);
                   6387:            }
                   6388:            k=k+1;
                   6389:            if (j >= jmax){
                   6390:              jmax=j;
                   6391:              ijmax=i;
                   6392:            }
                   6393:            if (j <= jmin){
                   6394:              jmin=j;
                   6395:              ijmin=i;
                   6396:            }
                   6397:            sum=sum+j;
                   6398:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   6399:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   6400:          }
                   6401:        }
                   6402:        else{
                   6403:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  6404: /*       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  6405:                                        
1.227     brouard  6406:          k=k+1;
                   6407:          if (j >= jmax) {
                   6408:            jmax=j;
                   6409:            ijmax=i;
                   6410:          }
                   6411:          else if (j <= jmin){
                   6412:            jmin=j;
                   6413:            ijmin=i;
                   6414:          }
                   6415:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   6416:          /*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]);*/
                   6417:          if(j<0){
                   6418:            nberr++;
                   6419:            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]);
                   6420:            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]);
                   6421:          }
                   6422:          sum=sum+j;
                   6423:        }
                   6424:        jk= j/stepm;
                   6425:        jl= j -jk*stepm;
                   6426:        ju= j -(jk+1)*stepm;
                   6427:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   6428:          if(jl==0){
                   6429:            dh[mi][i]=jk;
                   6430:            bh[mi][i]=0;
                   6431:          }else{ /* We want a negative bias in order to only have interpolation ie
                   6432:                  * to avoid the price of an extra matrix product in likelihood */
                   6433:            dh[mi][i]=jk+1;
                   6434:            bh[mi][i]=ju;
                   6435:          }
                   6436:        }else{
                   6437:          if(jl <= -ju){
                   6438:            dh[mi][i]=jk;
                   6439:            bh[mi][i]=jl;       /* bias is positive if real duration
                   6440:                                 * is higher than the multiple of stepm and negative otherwise.
                   6441:                                 */
                   6442:          }
                   6443:          else{
                   6444:            dh[mi][i]=jk+1;
                   6445:            bh[mi][i]=ju;
                   6446:          }
                   6447:          if(dh[mi][i]==0){
                   6448:            dh[mi][i]=1; /* At least one step */
                   6449:            bh[mi][i]=ju; /* At least one step */
                   6450:            /*  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);*/
                   6451:          }
                   6452:        } /* end if mle */
1.126     brouard  6453:       }
                   6454:     } /* end wave */
                   6455:   }
                   6456:   jmean=sum/k;
                   6457:   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  6458:   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  6459: }
1.126     brouard  6460: 
                   6461: /*********** Tricode ****************************/
1.220     brouard  6462:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  6463:  {
                   6464:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   6465:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   6466:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   6467:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   6468:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   6469:     */
1.130     brouard  6470: 
1.242     brouard  6471:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   6472:    int modmaxcovj=0; /* Modality max of covariates j */
                   6473:    int cptcode=0; /* Modality max of covariates j */
                   6474:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  6475: 
                   6476: 
1.242     brouard  6477:    /* cptcoveff=0;  */
                   6478:    /* *cptcov=0; */
1.126     brouard  6479:  
1.242     brouard  6480:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  6481:    for (k=1; k <= maxncov; k++)
                   6482:      for(j=1; j<=2; j++)
                   6483:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  6484: 
1.242     brouard  6485:    /* Loop on covariates without age and products and no quantitative variable */
1.335     brouard  6486:    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  6487:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
1.343     brouard  6488:      /* printf("Testing k=%d, cptcovt=%d\n",k, cptcovt); */
1.349     brouard  6489:      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  6490:        switch(Fixed[k]) {
                   6491:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  6492:         modmaxcovj=0;
                   6493:         modmincovj=0;
1.242     brouard  6494:         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  6495:           /* 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  6496:           ij=(int)(covar[Tvar[k]][i]);
                   6497:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   6498:            * If product of Vn*Vm, still boolean *:
                   6499:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   6500:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   6501:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   6502:              modality of the nth covariate of individual i. */
                   6503:           if (ij > modmaxcovj)
                   6504:             modmaxcovj=ij; 
                   6505:           else if (ij < modmincovj) 
                   6506:             modmincovj=ij; 
1.287     brouard  6507:           if (ij <0 || ij >1 ){
1.311     brouard  6508:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6509:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6510:             fflush(ficlog);
                   6511:             exit(1);
1.287     brouard  6512:           }
                   6513:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  6514:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   6515:             exit(1);
                   6516:           }else
                   6517:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   6518:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   6519:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   6520:           /* getting the maximum value of the modality of the covariate
                   6521:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   6522:              female ies 1, then modmaxcovj=1.
                   6523:           */
                   6524:         } /* end for loop on individuals i */
                   6525:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6526:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6527:         cptcode=modmaxcovj;
                   6528:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   6529:         /*for (i=0; i<=cptcode; i++) {*/
                   6530:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   6531:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6532:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6533:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   6534:             if( j != -1){
                   6535:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   6536:                                  covariate for which somebody answered excluding 
                   6537:                                  undefined. Usually 2: 0 and 1. */
                   6538:             }
                   6539:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   6540:                                     covariate for which somebody answered including 
                   6541:                                     undefined. Usually 3: -1, 0 and 1. */
                   6542:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   6543:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   6544:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  6545:                        
1.242     brouard  6546:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   6547:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   6548:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   6549:         /* modmincovj=3; modmaxcovj = 7; */
                   6550:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   6551:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   6552:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   6553:         /* nbcode[Tvar[j]][ij]=k; */
                   6554:         /* nbcode[Tvar[j]][1]=0; */
                   6555:         /* nbcode[Tvar[j]][2]=1; */
                   6556:         /* nbcode[Tvar[j]][3]=2; */
                   6557:         /* To be continued (not working yet). */
                   6558:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  6559: 
                   6560:         /* 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*/
                   6561:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   6562:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   6563:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   6564:         /*, could be restored in the future */
                   6565:         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  6566:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   6567:             break;
                   6568:           }
                   6569:           ij++;
1.287     brouard  6570:           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  6571:           cptcode = ij; /* New max modality for covar j */
                   6572:         } /* end of loop on modality i=-1 to 1 or more */
                   6573:         break;
                   6574:        case 1: /* Testing on varying covariate, could be simple and
                   6575:                * should look at waves or product of fixed *
                   6576:                * varying. No time to test -1, assuming 0 and 1 only */
                   6577:         ij=0;
                   6578:         for(i=0; i<=1;i++){
                   6579:           nbcode[Tvar[k]][++ij]=i;
                   6580:         }
                   6581:         break;
                   6582:        default:
                   6583:         break;
                   6584:        } /* end switch */
                   6585:      } /* end dummy test */
1.349     brouard  6586:      if(Dummy[k]==1 && Typevar[k] !=1 && Typevar[k] !=3 && Fixed ==0){ /* Fixed Quantitative covariate and not age product */ 
1.311     brouard  6587:        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  6588:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   6589:           printf("Error k=%d \n",k);
                   6590:           exit(1);
                   6591:         }
1.311     brouard  6592:         if(isnan(covar[Tvar[k]][i])){
                   6593:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6594:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6595:           fflush(ficlog);
                   6596:           exit(1);
                   6597:          }
                   6598:        }
1.335     brouard  6599:      } /* end Quanti */
1.287     brouard  6600:    } /* 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  6601:   
                   6602:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   6603:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   6604:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   6605:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   6606:      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 */ 
                   6607:      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 */
                   6608:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   6609:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   6610:   
                   6611:    ij=0;
                   6612:    /* 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  6613:    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 */
                   6614:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  6615:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6616:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335     brouard  6617:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   6618:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   6619:        /* 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  6620:        /* If product not in single variable we don't print results */
                   6621:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335     brouard  6622:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   6623:        /* k=       1    2   3     4       5       6      7       8        9  */
                   6624:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   6625:        /* ij            1    2                                            3  */  
                   6626:        /* Tvaraff[ij]=  4    3                                            1  */
                   6627:        /* Tmodelind[ij]=2    3                                            9  */
                   6628:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  6629:        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*/
                   6630:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   6631:        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 */
                   6632:        if(Fixed[k]!=0)
                   6633:         anyvaryingduminmodel=1;
                   6634:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   6635:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6636:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   6637:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   6638:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   6639:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6640:      } 
                   6641:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   6642:    /* ij--; */
                   6643:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335     brouard  6644:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  6645:                * because they can be excluded from the model and real
                   6646:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   6647:    for(j=ij+1; j<= cptcovt; j++){
                   6648:      Tvaraff[j]=0;
                   6649:      Tmodelind[j]=0;
                   6650:    }
                   6651:    for(j=ntveff+1; j<= cptcovt; j++){
                   6652:      TmodelInvind[j]=0;
                   6653:    }
                   6654:    /* To be sorted */
                   6655:    ;
                   6656:  }
1.126     brouard  6657: 
1.145     brouard  6658: 
1.126     brouard  6659: /*********** Health Expectancies ****************/
                   6660: 
1.235     brouard  6661:  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  6662: 
                   6663: {
                   6664:   /* Health expectancies, no variances */
1.329     brouard  6665:   /* cij is the combination in the list of combination of dummy covariates */
                   6666:   /* strstart is a string of time at start of computing */
1.164     brouard  6667:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  6668:   int nhstepma, nstepma; /* Decreasing with age */
                   6669:   double age, agelim, hf;
                   6670:   double ***p3mat;
                   6671:   double eip;
                   6672: 
1.238     brouard  6673:   /* pstamp(ficreseij); */
1.126     brouard  6674:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   6675:   fprintf(ficreseij,"# Age");
                   6676:   for(i=1; i<=nlstate;i++){
                   6677:     for(j=1; j<=nlstate;j++){
                   6678:       fprintf(ficreseij," e%1d%1d ",i,j);
                   6679:     }
                   6680:     fprintf(ficreseij," e%1d. ",i);
                   6681:   }
                   6682:   fprintf(ficreseij,"\n");
                   6683: 
                   6684:   
                   6685:   if(estepm < stepm){
                   6686:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6687:   }
                   6688:   else  hstepm=estepm;   
                   6689:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6690:    * This is mainly to measure the difference between two models: for example
                   6691:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6692:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6693:    * progression in between and thus overestimating or underestimating according
                   6694:    * to the curvature of the survival function. If, for the same date, we 
                   6695:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6696:    * to compare the new estimate of Life expectancy with the same linear 
                   6697:    * hypothesis. A more precise result, taking into account a more precise
                   6698:    * curvature will be obtained if estepm is as small as stepm. */
                   6699: 
                   6700:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6701:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6702:      nhstepm is the number of hstepm from age to agelim 
                   6703:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  6704:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  6705:      and note for a fixed period like estepm months */
                   6706:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6707:      survival function given by stepm (the optimization length). Unfortunately it
                   6708:      means that if the survival funtion is printed only each two years of age and if
                   6709:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6710:      results. So we changed our mind and took the option of the best precision.
                   6711:   */
                   6712:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6713: 
                   6714:   agelim=AGESUP;
                   6715:   /* If stepm=6 months */
                   6716:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6717:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6718:     
                   6719: /* nhstepm age range expressed in number of stepm */
                   6720:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6721:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6722:   /* if (stepm >= YEARM) hstepm=1;*/
                   6723:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6724:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6725: 
                   6726:   for (age=bage; age<=fage; age ++){ 
                   6727:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6728:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6729:     /* if (stepm >= YEARM) hstepm=1;*/
                   6730:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   6731: 
                   6732:     /* If stepm=6 months */
                   6733:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6734:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  6735:     /* 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  6736:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  6737:     
                   6738:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6739:     
                   6740:     printf("%d|",(int)age);fflush(stdout);
                   6741:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6742:     
                   6743:     /* Computing expectancies */
                   6744:     for(i=1; i<=nlstate;i++)
                   6745:       for(j=1; j<=nlstate;j++)
                   6746:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6747:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   6748:          
                   6749:          /* 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]);*/
                   6750: 
                   6751:        }
                   6752: 
                   6753:     fprintf(ficreseij,"%3.0f",age );
                   6754:     for(i=1; i<=nlstate;i++){
                   6755:       eip=0;
                   6756:       for(j=1; j<=nlstate;j++){
                   6757:        eip +=eij[i][j][(int)age];
                   6758:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   6759:       }
                   6760:       fprintf(ficreseij,"%9.4f", eip );
                   6761:     }
                   6762:     fprintf(ficreseij,"\n");
                   6763:     
                   6764:   }
                   6765:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6766:   printf("\n");
                   6767:   fprintf(ficlog,"\n");
                   6768:   
                   6769: }
                   6770: 
1.235     brouard  6771:  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  6772: 
                   6773: {
                   6774:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6775:      to initial status i, ei. .
1.126     brouard  6776:   */
1.336     brouard  6777:   /* Very time consuming function, but already optimized with precov */
1.126     brouard  6778:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6779:   int nhstepma, nstepma; /* Decreasing with age */
                   6780:   double age, agelim, hf;
                   6781:   double ***p3matp, ***p3matm, ***varhe;
                   6782:   double **dnewm,**doldm;
                   6783:   double *xp, *xm;
                   6784:   double **gp, **gm;
                   6785:   double ***gradg, ***trgradg;
                   6786:   int theta;
                   6787: 
                   6788:   double eip, vip;
                   6789: 
                   6790:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6791:   xp=vector(1,npar);
                   6792:   xm=vector(1,npar);
                   6793:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6794:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6795:   
                   6796:   pstamp(ficresstdeij);
                   6797:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6798:   fprintf(ficresstdeij,"# Age");
                   6799:   for(i=1; i<=nlstate;i++){
                   6800:     for(j=1; j<=nlstate;j++)
                   6801:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6802:     fprintf(ficresstdeij," e%1d. ",i);
                   6803:   }
                   6804:   fprintf(ficresstdeij,"\n");
                   6805: 
                   6806:   pstamp(ficrescveij);
                   6807:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6808:   fprintf(ficrescveij,"# Age");
                   6809:   for(i=1; i<=nlstate;i++)
                   6810:     for(j=1; j<=nlstate;j++){
                   6811:       cptj= (j-1)*nlstate+i;
                   6812:       for(i2=1; i2<=nlstate;i2++)
                   6813:        for(j2=1; j2<=nlstate;j2++){
                   6814:          cptj2= (j2-1)*nlstate+i2;
                   6815:          if(cptj2 <= cptj)
                   6816:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6817:        }
                   6818:     }
                   6819:   fprintf(ficrescveij,"\n");
                   6820:   
                   6821:   if(estepm < stepm){
                   6822:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6823:   }
                   6824:   else  hstepm=estepm;   
                   6825:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6826:    * This is mainly to measure the difference between two models: for example
                   6827:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6828:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6829:    * progression in between and thus overestimating or underestimating according
                   6830:    * to the curvature of the survival function. If, for the same date, we 
                   6831:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6832:    * to compare the new estimate of Life expectancy with the same linear 
                   6833:    * hypothesis. A more precise result, taking into account a more precise
                   6834:    * curvature will be obtained if estepm is as small as stepm. */
                   6835: 
                   6836:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6837:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6838:      nhstepm is the number of hstepm from age to agelim 
                   6839:      nstepm is the number of stepm from age to agelin. 
                   6840:      Look at hpijx to understand the reason of that which relies in memory size
                   6841:      and note for a fixed period like estepm months */
                   6842:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6843:      survival function given by stepm (the optimization length). Unfortunately it
                   6844:      means that if the survival funtion is printed only each two years of age and if
                   6845:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6846:      results. So we changed our mind and took the option of the best precision.
                   6847:   */
                   6848:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6849: 
                   6850:   /* If stepm=6 months */
                   6851:   /* nhstepm age range expressed in number of stepm */
                   6852:   agelim=AGESUP;
                   6853:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6854:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6855:   /* if (stepm >= YEARM) hstepm=1;*/
                   6856:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6857:   
                   6858:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6859:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6860:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6861:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6862:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6863:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6864: 
                   6865:   for (age=bage; age<=fage; age ++){ 
                   6866:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6867:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6868:     /* if (stepm >= YEARM) hstepm=1;*/
                   6869:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6870:                
1.126     brouard  6871:     /* If stepm=6 months */
                   6872:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6873:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6874:     
                   6875:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6876:                
1.126     brouard  6877:     /* Computing  Variances of health expectancies */
                   6878:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6879:        decrease memory allocation */
                   6880:     for(theta=1; theta <=npar; theta++){
                   6881:       for(i=1; i<=npar; i++){ 
1.222     brouard  6882:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6883:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6884:       }
1.235     brouard  6885:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6886:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6887:                        
1.126     brouard  6888:       for(j=1; j<= nlstate; j++){
1.222     brouard  6889:        for(i=1; i<=nlstate; i++){
                   6890:          for(h=0; h<=nhstepm-1; h++){
                   6891:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6892:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6893:          }
                   6894:        }
1.126     brouard  6895:       }
1.218     brouard  6896:                        
1.126     brouard  6897:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6898:        for(h=0; h<=nhstepm-1; h++){
                   6899:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6900:        }
1.126     brouard  6901:     }/* End theta */
                   6902:     
                   6903:     
                   6904:     for(h=0; h<=nhstepm-1; h++)
                   6905:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6906:        for(theta=1; theta <=npar; theta++)
                   6907:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6908:     
1.218     brouard  6909:                
1.222     brouard  6910:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6911:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6912:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6913:                
1.222     brouard  6914:     printf("%d|",(int)age);fflush(stdout);
                   6915:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6916:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6917:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6918:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6919:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6920:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6921:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6922:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6923:       }
                   6924:     }
1.320     brouard  6925:     /* if((int)age ==50){ */
                   6926:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6927:     /* } */
1.126     brouard  6928:     /* Computing expectancies */
1.235     brouard  6929:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6930:     for(i=1; i<=nlstate;i++)
                   6931:       for(j=1; j<=nlstate;j++)
1.222     brouard  6932:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6933:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6934:                                        
1.222     brouard  6935:          /* 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  6936:                                        
1.222     brouard  6937:        }
1.269     brouard  6938: 
                   6939:     /* Standard deviation of expectancies ij */                
1.126     brouard  6940:     fprintf(ficresstdeij,"%3.0f",age );
                   6941:     for(i=1; i<=nlstate;i++){
                   6942:       eip=0.;
                   6943:       vip=0.;
                   6944:       for(j=1; j<=nlstate;j++){
1.222     brouard  6945:        eip += eij[i][j][(int)age];
                   6946:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6947:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6948:        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  6949:       }
                   6950:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6951:     }
                   6952:     fprintf(ficresstdeij,"\n");
1.218     brouard  6953:                
1.269     brouard  6954:     /* Variance of expectancies ij */          
1.126     brouard  6955:     fprintf(ficrescveij,"%3.0f",age );
                   6956:     for(i=1; i<=nlstate;i++)
                   6957:       for(j=1; j<=nlstate;j++){
1.222     brouard  6958:        cptj= (j-1)*nlstate+i;
                   6959:        for(i2=1; i2<=nlstate;i2++)
                   6960:          for(j2=1; j2<=nlstate;j2++){
                   6961:            cptj2= (j2-1)*nlstate+i2;
                   6962:            if(cptj2 <= cptj)
                   6963:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6964:          }
1.126     brouard  6965:       }
                   6966:     fprintf(ficrescveij,"\n");
1.218     brouard  6967:                
1.126     brouard  6968:   }
                   6969:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6970:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6971:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6972:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6973:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6974:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6975:   printf("\n");
                   6976:   fprintf(ficlog,"\n");
1.218     brouard  6977:        
1.126     brouard  6978:   free_vector(xm,1,npar);
                   6979:   free_vector(xp,1,npar);
                   6980:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6981:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6982:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6983: }
1.218     brouard  6984:  
1.126     brouard  6985: /************ Variance ******************/
1.235     brouard  6986:  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  6987:  {
1.279     brouard  6988:    /** Variance of health expectancies 
                   6989:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6990:     * double **newm;
                   6991:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6992:     */
1.218     brouard  6993:   
                   6994:    /* int movingaverage(); */
                   6995:    double **dnewm,**doldm;
                   6996:    double **dnewmp,**doldmp;
                   6997:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6998:    int first=0;
1.218     brouard  6999:    int k;
                   7000:    double *xp;
1.279     brouard  7001:    double **gp, **gm;  /**< for var eij */
                   7002:    double ***gradg, ***trgradg; /**< for var eij */
                   7003:    double **gradgp, **trgradgp; /**< for var p point j */
                   7004:    double *gpp, *gmp; /**< for var p point j */
                   7005:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  7006:    double ***p3mat;
                   7007:    double age,agelim, hf;
                   7008:    /* double ***mobaverage; */
                   7009:    int theta;
                   7010:    char digit[4];
                   7011:    char digitp[25];
                   7012: 
                   7013:    char fileresprobmorprev[FILENAMELENGTH];
                   7014: 
                   7015:    if(popbased==1){
                   7016:      if(mobilav!=0)
                   7017:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   7018:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   7019:    }
                   7020:    else 
                   7021:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  7022: 
1.218     brouard  7023:    /* if (mobilav!=0) { */
                   7024:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7025:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   7026:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   7027:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   7028:    /*   } */
                   7029:    /* } */
                   7030: 
                   7031:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   7032:    sprintf(digit,"%-d",ij);
                   7033:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   7034:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   7035:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   7036:    strcat(fileresprobmorprev,fileresu);
                   7037:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   7038:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   7039:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   7040:    }
                   7041:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   7042:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   7043:    pstamp(ficresprobmorprev);
                   7044:    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  7045:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.337     brouard  7046: 
                   7047:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
                   7048:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
                   7049:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   7050:    /* } */
                   7051:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
1.344     brouard  7052:      /* fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); */
1.337     brouard  7053:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  7054:    }
1.337     brouard  7055:    /* for(j=1;j<=cptcoveff;j++)  */
                   7056:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
1.238     brouard  7057:    fprintf(ficresprobmorprev,"\n");
                   7058: 
1.218     brouard  7059:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   7060:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7061:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   7062:      for(i=1; i<=nlstate;i++)
                   7063:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   7064:    }  
                   7065:    fprintf(ficresprobmorprev,"\n");
                   7066:   
                   7067:    fprintf(ficgp,"\n# Routine varevsij");
                   7068:    fprintf(ficgp,"\nunset title \n");
                   7069:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   7070:    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");
                   7071:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  7072: 
1.218     brouard  7073:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7074:    pstamp(ficresvij);
                   7075:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   7076:    if(popbased==1)
                   7077:      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);
                   7078:    else
                   7079:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   7080:    fprintf(ficresvij,"# Age");
                   7081:    for(i=1; i<=nlstate;i++)
                   7082:      for(j=1; j<=nlstate;j++)
                   7083:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   7084:    fprintf(ficresvij,"\n");
                   7085: 
                   7086:    xp=vector(1,npar);
                   7087:    dnewm=matrix(1,nlstate,1,npar);
                   7088:    doldm=matrix(1,nlstate,1,nlstate);
                   7089:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   7090:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7091: 
                   7092:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   7093:    gpp=vector(nlstate+1,nlstate+ndeath);
                   7094:    gmp=vector(nlstate+1,nlstate+ndeath);
                   7095:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  7096:   
1.218     brouard  7097:    if(estepm < stepm){
                   7098:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   7099:    }
                   7100:    else  hstepm=estepm;   
                   7101:    /* For example we decided to compute the life expectancy with the smallest unit */
                   7102:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   7103:       nhstepm is the number of hstepm from age to agelim 
                   7104:       nstepm is the number of stepm from age to agelim. 
                   7105:       Look at function hpijx to understand why because of memory size limitations, 
                   7106:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   7107:       survival function given by stepm (the optimization length). Unfortunately it
                   7108:       means that if the survival funtion is printed every two years of age and if
                   7109:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   7110:       results. So we changed our mind and took the option of the best precision.
                   7111:    */
                   7112:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   7113:    agelim = AGESUP;
                   7114:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7115:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7116:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   7117:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7118:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   7119:      gp=matrix(0,nhstepm,1,nlstate);
                   7120:      gm=matrix(0,nhstepm,1,nlstate);
                   7121:                
                   7122:                
                   7123:      for(theta=1; theta <=npar; theta++){
                   7124:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   7125:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7126:        }
1.279     brouard  7127:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   7128:        * returns into prlim .
1.288     brouard  7129:        */
1.242     brouard  7130:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  7131: 
                   7132:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  7133:        if (popbased==1) {
                   7134:         if(mobilav ==0){
                   7135:           for(i=1; i<=nlstate;i++)
                   7136:             prlim[i][i]=probs[(int)age][i][ij];
                   7137:         }else{ /* mobilav */ 
                   7138:           for(i=1; i<=nlstate;i++)
                   7139:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   7140:         }
                   7141:        }
1.295     brouard  7142:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  7143:        */                      
                   7144:        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  7145:        /**< 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  7146:        * at horizon h in state j including mortality.
                   7147:        */
1.218     brouard  7148:        for(j=1; j<= nlstate; j++){
                   7149:         for(h=0; h<=nhstepm; h++){
                   7150:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   7151:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   7152:         }
                   7153:        }
1.279     brouard  7154:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  7155:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  7156:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  7157:        */
                   7158:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7159:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   7160:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  7161:        }
                   7162:        
                   7163:        /* Again with minus shift */
1.218     brouard  7164:                        
                   7165:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   7166:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  7167: 
1.242     brouard  7168:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  7169:                        
                   7170:        if (popbased==1) {
                   7171:         if(mobilav ==0){
                   7172:           for(i=1; i<=nlstate;i++)
                   7173:             prlim[i][i]=probs[(int)age][i][ij];
                   7174:         }else{ /* mobilav */ 
                   7175:           for(i=1; i<=nlstate;i++)
                   7176:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   7177:         }
                   7178:        }
                   7179:                        
1.235     brouard  7180:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  7181:                        
                   7182:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   7183:         for(h=0; h<=nhstepm; h++){
                   7184:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   7185:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   7186:         }
                   7187:        }
                   7188:        /* This for computing probability of death (h=1 means
                   7189:          computed over hstepm matrices product = hstepm*stepm months) 
                   7190:          as a weighted average of prlim.
                   7191:        */
                   7192:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7193:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   7194:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   7195:        }    
1.279     brouard  7196:        /* end shifting computations */
                   7197: 
                   7198:        /**< Computing gradient matrix at horizon h 
                   7199:        */
1.218     brouard  7200:        for(j=1; j<= nlstate; j++) /* vareij */
                   7201:         for(h=0; h<=nhstepm; h++){
                   7202:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   7203:         }
1.279     brouard  7204:        /**< Gradient of overall mortality p.3 (or p.j) 
                   7205:        */
                   7206:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  7207:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   7208:        }
                   7209:                        
                   7210:      } /* End theta */
1.279     brouard  7211:      
                   7212:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  7213:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   7214:                
                   7215:      for(h=0; h<=nhstepm; h++) /* veij */
                   7216:        for(j=1; j<=nlstate;j++)
                   7217:         for(theta=1; theta <=npar; theta++)
                   7218:           trgradg[h][j][theta]=gradg[h][theta][j];
                   7219:                
                   7220:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   7221:        for(theta=1; theta <=npar; theta++)
                   7222:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  7223:      /**< as well as its transposed matrix 
                   7224:       */               
1.218     brouard  7225:                
                   7226:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   7227:      for(i=1;i<=nlstate;i++)
                   7228:        for(j=1;j<=nlstate;j++)
                   7229:         vareij[i][j][(int)age] =0.;
1.279     brouard  7230: 
                   7231:      /* Computing trgradg by matcov by gradg at age and summing over h
                   7232:       * and k (nhstepm) formula 15 of article
                   7233:       * Lievre-Brouard-Heathcote
                   7234:       */
                   7235:      
1.218     brouard  7236:      for(h=0;h<=nhstepm;h++){
                   7237:        for(k=0;k<=nhstepm;k++){
                   7238:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   7239:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   7240:         for(i=1;i<=nlstate;i++)
                   7241:           for(j=1;j<=nlstate;j++)
                   7242:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   7243:        }
                   7244:      }
                   7245:                
1.279     brouard  7246:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   7247:       * p.j overall mortality formula 49 but computed directly because
                   7248:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   7249:       * wix is independent of theta.
                   7250:       */
1.218     brouard  7251:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   7252:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   7253:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   7254:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   7255:         varppt[j][i]=doldmp[j][i];
                   7256:      /* end ppptj */
                   7257:      /*  x centered again */
                   7258:                
1.242     brouard  7259:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  7260:                
                   7261:      if (popbased==1) {
                   7262:        if(mobilav ==0){
                   7263:         for(i=1; i<=nlstate;i++)
                   7264:           prlim[i][i]=probs[(int)age][i][ij];
                   7265:        }else{ /* mobilav */ 
                   7266:         for(i=1; i<=nlstate;i++)
                   7267:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   7268:        }
                   7269:      }
                   7270:                
                   7271:      /* This for computing probability of death (h=1 means
                   7272:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   7273:        as a weighted average of prlim.
                   7274:      */
1.235     brouard  7275:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  7276:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7277:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   7278:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   7279:      }    
                   7280:      /* end probability of death */
                   7281:                
                   7282:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   7283:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7284:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   7285:        for(i=1; i<=nlstate;i++){
                   7286:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   7287:        }
                   7288:      } 
                   7289:      fprintf(ficresprobmorprev,"\n");
                   7290:                
                   7291:      fprintf(ficresvij,"%.0f ",age );
                   7292:      for(i=1; i<=nlstate;i++)
                   7293:        for(j=1; j<=nlstate;j++){
                   7294:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   7295:        }
                   7296:      fprintf(ficresvij,"\n");
                   7297:      free_matrix(gp,0,nhstepm,1,nlstate);
                   7298:      free_matrix(gm,0,nhstepm,1,nlstate);
                   7299:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   7300:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   7301:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7302:    } /* End age */
                   7303:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   7304:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   7305:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   7306:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   7307:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   7308:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   7309:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   7310:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   7311:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   7312:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   7313:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7314:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7315:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   7316:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   7317:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   7318:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   7319:    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);
                   7320:    /*  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  7321:     */
1.218     brouard  7322:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   7323:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  7324: 
1.218     brouard  7325:    free_vector(xp,1,npar);
                   7326:    free_matrix(doldm,1,nlstate,1,nlstate);
                   7327:    free_matrix(dnewm,1,nlstate,1,npar);
                   7328:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7329:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   7330:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7331:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7332:    fclose(ficresprobmorprev);
                   7333:    fflush(ficgp);
                   7334:    fflush(fichtm); 
                   7335:  }  /* end varevsij */
1.126     brouard  7336: 
                   7337: /************ Variance of prevlim ******************/
1.269     brouard  7338:  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  7339: {
1.205     brouard  7340:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  7341:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  7342: 
1.268     brouard  7343:   double **dnewmpar,**doldm;
1.126     brouard  7344:   int i, j, nhstepm, hstepm;
                   7345:   double *xp;
                   7346:   double *gp, *gm;
                   7347:   double **gradg, **trgradg;
1.208     brouard  7348:   double **mgm, **mgp;
1.126     brouard  7349:   double age,agelim;
                   7350:   int theta;
                   7351:   
                   7352:   pstamp(ficresvpl);
1.288     brouard  7353:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  7354:   fprintf(ficresvpl,"# Age ");
                   7355:   if(nresult >=1)
                   7356:     fprintf(ficresvpl," Result# ");
1.126     brouard  7357:   for(i=1; i<=nlstate;i++)
                   7358:       fprintf(ficresvpl," %1d-%1d",i,i);
                   7359:   fprintf(ficresvpl,"\n");
                   7360: 
                   7361:   xp=vector(1,npar);
1.268     brouard  7362:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  7363:   doldm=matrix(1,nlstate,1,nlstate);
                   7364:   
                   7365:   hstepm=1*YEARM; /* Every year of age */
                   7366:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7367:   agelim = AGESUP;
                   7368:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7369:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7370:     if (stepm >= YEARM) hstepm=1;
                   7371:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7372:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  7373:     mgp=matrix(1,npar,1,nlstate);
                   7374:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  7375:     gp=vector(1,nlstate);
                   7376:     gm=vector(1,nlstate);
                   7377: 
                   7378:     for(theta=1; theta <=npar; theta++){
                   7379:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7380:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7381:       }
1.288     brouard  7382:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7383:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7384:       /* else */
                   7385:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7386:       for(i=1;i<=nlstate;i++){
1.126     brouard  7387:        gp[i] = prlim[i][i];
1.208     brouard  7388:        mgp[theta][i] = prlim[i][i];
                   7389:       }
1.126     brouard  7390:       for(i=1; i<=npar; i++) /* Computes gradient */
                   7391:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  7392:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7393:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7394:       /* else */
                   7395:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7396:       for(i=1;i<=nlstate;i++){
1.126     brouard  7397:        gm[i] = prlim[i][i];
1.208     brouard  7398:        mgm[theta][i] = prlim[i][i];
                   7399:       }
1.126     brouard  7400:       for(i=1;i<=nlstate;i++)
                   7401:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  7402:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  7403:     } /* End theta */
                   7404: 
                   7405:     trgradg =matrix(1,nlstate,1,npar);
                   7406: 
                   7407:     for(j=1; j<=nlstate;j++)
                   7408:       for(theta=1; theta <=npar; theta++)
                   7409:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  7410:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7411:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7412:     /*   for(j=1; j<=nlstate;j++){ */
                   7413:     /*         printf(" %d ",j); */
                   7414:     /*         for(theta=1; theta <=npar; theta++) */
                   7415:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7416:     /*         printf("\n "); */
                   7417:     /*   } */
                   7418:     /* } */
                   7419:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7420:     /*   printf("\n gradg %d ",(int)age); */
                   7421:     /*   for(j=1; j<=nlstate;j++){ */
                   7422:     /*         printf("%d ",j); */
                   7423:     /*         for(theta=1; theta <=npar; theta++) */
                   7424:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7425:     /*         printf("\n "); */
                   7426:     /*   } */
                   7427:     /* } */
1.126     brouard  7428: 
                   7429:     for(i=1;i<=nlstate;i++)
                   7430:       varpl[i][(int)age] =0.;
1.209     brouard  7431:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  7432:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7433:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7434:     }else{
1.268     brouard  7435:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7436:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7437:     }
1.126     brouard  7438:     for(i=1;i<=nlstate;i++)
                   7439:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7440: 
                   7441:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  7442:     if(nresult >=1)
                   7443:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  7444:     for(i=1; i<=nlstate;i++){
1.126     brouard  7445:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  7446:       /* for(j=1;j<=nlstate;j++) */
                   7447:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   7448:     }
1.126     brouard  7449:     fprintf(ficresvpl,"\n");
                   7450:     free_vector(gp,1,nlstate);
                   7451:     free_vector(gm,1,nlstate);
1.208     brouard  7452:     free_matrix(mgm,1,npar,1,nlstate);
                   7453:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  7454:     free_matrix(gradg,1,npar,1,nlstate);
                   7455:     free_matrix(trgradg,1,nlstate,1,npar);
                   7456:   } /* End age */
                   7457: 
                   7458:   free_vector(xp,1,npar);
                   7459:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  7460:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   7461: 
                   7462: }
                   7463: 
                   7464: 
                   7465: /************ Variance of backprevalence limit ******************/
1.269     brouard  7466:  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  7467: {
                   7468:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   7469:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   7470: 
                   7471:   double **dnewmpar,**doldm;
                   7472:   int i, j, nhstepm, hstepm;
                   7473:   double *xp;
                   7474:   double *gp, *gm;
                   7475:   double **gradg, **trgradg;
                   7476:   double **mgm, **mgp;
                   7477:   double age,agelim;
                   7478:   int theta;
                   7479:   
                   7480:   pstamp(ficresvbl);
                   7481:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   7482:   fprintf(ficresvbl,"# Age ");
                   7483:   if(nresult >=1)
                   7484:     fprintf(ficresvbl," Result# ");
                   7485:   for(i=1; i<=nlstate;i++)
                   7486:       fprintf(ficresvbl," %1d-%1d",i,i);
                   7487:   fprintf(ficresvbl,"\n");
                   7488: 
                   7489:   xp=vector(1,npar);
                   7490:   dnewmpar=matrix(1,nlstate,1,npar);
                   7491:   doldm=matrix(1,nlstate,1,nlstate);
                   7492:   
                   7493:   hstepm=1*YEARM; /* Every year of age */
                   7494:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7495:   agelim = AGEINF;
                   7496:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   7497:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7498:     if (stepm >= YEARM) hstepm=1;
                   7499:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7500:     gradg=matrix(1,npar,1,nlstate);
                   7501:     mgp=matrix(1,npar,1,nlstate);
                   7502:     mgm=matrix(1,npar,1,nlstate);
                   7503:     gp=vector(1,nlstate);
                   7504:     gm=vector(1,nlstate);
                   7505: 
                   7506:     for(theta=1; theta <=npar; theta++){
                   7507:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7508:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7509:       }
                   7510:       if(mobilavproj > 0 )
                   7511:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7512:       else
                   7513:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7514:       for(i=1;i<=nlstate;i++){
                   7515:        gp[i] = bprlim[i][i];
                   7516:        mgp[theta][i] = bprlim[i][i];
                   7517:       }
                   7518:      for(i=1; i<=npar; i++) /* Computes gradient */
                   7519:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   7520:        if(mobilavproj > 0 )
                   7521:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7522:        else
                   7523:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7524:       for(i=1;i<=nlstate;i++){
                   7525:        gm[i] = bprlim[i][i];
                   7526:        mgm[theta][i] = bprlim[i][i];
                   7527:       }
                   7528:       for(i=1;i<=nlstate;i++)
                   7529:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   7530:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   7531:     } /* End theta */
                   7532: 
                   7533:     trgradg =matrix(1,nlstate,1,npar);
                   7534: 
                   7535:     for(j=1; j<=nlstate;j++)
                   7536:       for(theta=1; theta <=npar; theta++)
                   7537:        trgradg[j][theta]=gradg[theta][j];
                   7538:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7539:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7540:     /*   for(j=1; j<=nlstate;j++){ */
                   7541:     /*         printf(" %d ",j); */
                   7542:     /*         for(theta=1; theta <=npar; theta++) */
                   7543:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7544:     /*         printf("\n "); */
                   7545:     /*   } */
                   7546:     /* } */
                   7547:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7548:     /*   printf("\n gradg %d ",(int)age); */
                   7549:     /*   for(j=1; j<=nlstate;j++){ */
                   7550:     /*         printf("%d ",j); */
                   7551:     /*         for(theta=1; theta <=npar; theta++) */
                   7552:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7553:     /*         printf("\n "); */
                   7554:     /*   } */
                   7555:     /* } */
                   7556: 
                   7557:     for(i=1;i<=nlstate;i++)
                   7558:       varbpl[i][(int)age] =0.;
                   7559:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   7560:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7561:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7562:     }else{
                   7563:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7564:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7565:     }
                   7566:     for(i=1;i<=nlstate;i++)
                   7567:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7568: 
                   7569:     fprintf(ficresvbl,"%.0f ",age );
                   7570:     if(nresult >=1)
                   7571:       fprintf(ficresvbl,"%d ",nres );
                   7572:     for(i=1; i<=nlstate;i++)
                   7573:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   7574:     fprintf(ficresvbl,"\n");
                   7575:     free_vector(gp,1,nlstate);
                   7576:     free_vector(gm,1,nlstate);
                   7577:     free_matrix(mgm,1,npar,1,nlstate);
                   7578:     free_matrix(mgp,1,npar,1,nlstate);
                   7579:     free_matrix(gradg,1,npar,1,nlstate);
                   7580:     free_matrix(trgradg,1,nlstate,1,npar);
                   7581:   } /* End age */
                   7582: 
                   7583:   free_vector(xp,1,npar);
                   7584:   free_matrix(doldm,1,nlstate,1,npar);
                   7585:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  7586: 
                   7587: }
                   7588: 
                   7589: /************ Variance of one-step probabilities  ******************/
                   7590: 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  7591:  {
                   7592:    int i, j=0,  k1, l1, tj;
                   7593:    int k2, l2, j1,  z1;
                   7594:    int k=0, l;
                   7595:    int first=1, first1, first2;
1.326     brouard  7596:    int nres=0; /* New */
1.222     brouard  7597:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   7598:    double **dnewm,**doldm;
                   7599:    double *xp;
                   7600:    double *gp, *gm;
                   7601:    double **gradg, **trgradg;
                   7602:    double **mu;
                   7603:    double age, cov[NCOVMAX+1];
                   7604:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   7605:    int theta;
                   7606:    char fileresprob[FILENAMELENGTH];
                   7607:    char fileresprobcov[FILENAMELENGTH];
                   7608:    char fileresprobcor[FILENAMELENGTH];
                   7609:    double ***varpij;
                   7610: 
                   7611:    strcpy(fileresprob,"PROB_"); 
                   7612:    strcat(fileresprob,fileres);
                   7613:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   7614:      printf("Problem with resultfile: %s\n", fileresprob);
                   7615:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   7616:    }
                   7617:    strcpy(fileresprobcov,"PROBCOV_"); 
                   7618:    strcat(fileresprobcov,fileresu);
                   7619:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   7620:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   7621:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   7622:    }
                   7623:    strcpy(fileresprobcor,"PROBCOR_"); 
                   7624:    strcat(fileresprobcor,fileresu);
                   7625:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   7626:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   7627:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   7628:    }
                   7629:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7630:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7631:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7632:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7633:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7634:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7635:    pstamp(ficresprob);
                   7636:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   7637:    fprintf(ficresprob,"# Age");
                   7638:    pstamp(ficresprobcov);
                   7639:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   7640:    fprintf(ficresprobcov,"# Age");
                   7641:    pstamp(ficresprobcor);
                   7642:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   7643:    fprintf(ficresprobcor,"# Age");
1.126     brouard  7644: 
                   7645: 
1.222     brouard  7646:    for(i=1; i<=nlstate;i++)
                   7647:      for(j=1; j<=(nlstate+ndeath);j++){
                   7648:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   7649:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   7650:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   7651:      }  
                   7652:    /* fprintf(ficresprob,"\n");
                   7653:       fprintf(ficresprobcov,"\n");
                   7654:       fprintf(ficresprobcor,"\n");
                   7655:    */
                   7656:    xp=vector(1,npar);
                   7657:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7658:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7659:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   7660:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   7661:    first=1;
                   7662:    fprintf(ficgp,"\n# Routine varprob");
                   7663:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   7664:    fprintf(fichtm,"\n");
                   7665: 
1.288     brouard  7666:    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  7667:    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);
                   7668:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  7669: and drawn. It helps understanding how is the covariance between two incidences.\
                   7670:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  7671:    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  7672: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   7673: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   7674: standard deviations wide on each axis. <br>\
                   7675:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   7676:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   7677: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   7678: 
1.222     brouard  7679:    cov[1]=1;
                   7680:    /* tj=cptcoveff; */
1.225     brouard  7681:    tj = (int) pow(2,cptcoveff);
1.222     brouard  7682:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   7683:    j1=0;
1.332     brouard  7684: 
                   7685:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   7686:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.342     brouard  7687:      /* 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  7688:      if(tj != 1 && TKresult[nres]!= j1)
                   7689:        continue;
                   7690: 
                   7691:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   7692:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   7693:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  7694:      if  (cptcovn>0) {
1.334     brouard  7695:        fprintf(ficresprob, "\n#********** Variable ");
                   7696:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   7697:        fprintf(ficgp, "\n#********** Variable ");
                   7698:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   7699:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   7700: 
                   7701:        /* Including quantitative variables of the resultline to be done */
                   7702:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
1.343     brouard  7703:         /* printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model); */
1.338     brouard  7704:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   7705:         /* 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  7706:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   7707:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   7708:             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  */
                   7709:             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  */
                   7710:             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  */
                   7711:             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  */
                   7712:             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  */
                   7713:             fprintf(ficresprob,"fixed ");
                   7714:             fprintf(ficresprobcov,"fixed ");
                   7715:             fprintf(ficgp,"fixed ");
                   7716:             fprintf(fichtmcov,"fixed ");
                   7717:             fprintf(ficresprobcor,"fixed ");
                   7718:           }else{
                   7719:             fprintf(ficresprob,"varyi ");
                   7720:             fprintf(ficresprobcov,"varyi ");
                   7721:             fprintf(ficgp,"varyi ");
                   7722:             fprintf(fichtmcov,"varyi ");
                   7723:             fprintf(ficresprobcor,"varyi ");
                   7724:           }
                   7725:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   7726:           /* For each selected (single) quantitative value */
1.337     brouard  7727:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
1.334     brouard  7728:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   7729:             fprintf(ficresprob,"fixed ");
                   7730:             fprintf(ficresprobcov,"fixed ");
                   7731:             fprintf(ficgp,"fixed ");
                   7732:             fprintf(fichtmcov,"fixed ");
                   7733:             fprintf(ficresprobcor,"fixed ");
                   7734:           }else{
                   7735:             fprintf(ficresprob,"varyi ");
                   7736:             fprintf(ficresprobcov,"varyi ");
                   7737:             fprintf(ficgp,"varyi ");
                   7738:             fprintf(fichtmcov,"varyi ");
                   7739:             fprintf(ficresprobcor,"varyi ");
                   7740:           }
                   7741:         }else{
                   7742:           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 */
                   7743:           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 */
                   7744:           exit(1);
                   7745:         }
                   7746:        } /* End loop on variable of this resultline */
                   7747:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  7748:        fprintf(ficresprob, "**********\n#\n");
                   7749:        fprintf(ficresprobcov, "**********\n#\n");
                   7750:        fprintf(ficgp, "**********\n#\n");
                   7751:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   7752:        fprintf(ficresprobcor, "**********\n#");    
                   7753:        if(invalidvarcomb[j1]){
                   7754:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   7755:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   7756:         continue;
                   7757:        }
                   7758:      }
                   7759:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   7760:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7761:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   7762:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  7763:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  7764:        cov[2]=age;
                   7765:        if(nagesqr==1)
                   7766:         cov[3]= age*age;
1.334     brouard  7767:        /* New code end of combination but for each resultline */
                   7768:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  7769:         if(Typevar[k1]==1 || Typevar[k1] ==3){ /* A product with age */
1.334     brouard  7770:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  7771:         }else{
1.334     brouard  7772:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  7773:         }
1.334     brouard  7774:        }/* End of loop on model equation */
                   7775: /* Old code */
                   7776:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   7777:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   7778:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   7779:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   7780:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   7781:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   7782:        /*                                                                  * 1  1 1 1 1 */
                   7783:        /*                                                                  * 2  2 1 1 1 */
                   7784:        /*                                                                  * 3  1 2 1 1 */
                   7785:        /*                                                                  *\/ */
                   7786:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   7787:        /* } */
                   7788:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   7789:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   7790:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   7791:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   7792:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   7793:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   7794:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7795:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   7796:        /*         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]); */
                   7797:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   7798:        /*         /\* exit(1); *\/ */
                   7799:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   7800:        /*       } */
                   7801:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7802:        /* } */
                   7803:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   7804:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   7805:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7806:        /*           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]])]; */
                   7807:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7808:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   7809:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   7810:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   7811:        /*         } */
                   7812:        /*       }else{ */
                   7813:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7814:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   7815:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   7816:        /*         }else{ */
                   7817:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   7818:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   7819:        /*         } */
                   7820:        /*       } */
                   7821:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7822:        /* } */                 
1.326     brouard  7823: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  7824:        for(theta=1; theta <=npar; theta++){
                   7825:         for(i=1; i<=npar; i++)
                   7826:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7827:                                
1.222     brouard  7828:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7829:                                
1.222     brouard  7830:         k=0;
                   7831:         for(i=1; i<= (nlstate); i++){
                   7832:           for(j=1; j<=(nlstate+ndeath);j++){
                   7833:             k=k+1;
                   7834:             gp[k]=pmmij[i][j];
                   7835:           }
                   7836:         }
1.220     brouard  7837:                                
1.222     brouard  7838:         for(i=1; i<=npar; i++)
                   7839:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7840:                                
1.222     brouard  7841:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7842:         k=0;
                   7843:         for(i=1; i<=(nlstate); i++){
                   7844:           for(j=1; j<=(nlstate+ndeath);j++){
                   7845:             k=k+1;
                   7846:             gm[k]=pmmij[i][j];
                   7847:           }
                   7848:         }
1.220     brouard  7849:                                
1.222     brouard  7850:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7851:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7852:        }
1.126     brouard  7853: 
1.222     brouard  7854:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7855:         for(theta=1; theta <=npar; theta++)
                   7856:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7857:                        
1.222     brouard  7858:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7859:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7860:                        
1.222     brouard  7861:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7862:                        
1.222     brouard  7863:        k=0;
                   7864:        for(i=1; i<=(nlstate); i++){
                   7865:         for(j=1; j<=(nlstate+ndeath);j++){
                   7866:           k=k+1;
                   7867:           mu[k][(int) age]=pmmij[i][j];
                   7868:         }
                   7869:        }
                   7870:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7871:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7872:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7873:                        
1.222     brouard  7874:        /*printf("\n%d ",(int)age);
                   7875:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7876:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7877:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7878:         }*/
1.220     brouard  7879:                        
1.222     brouard  7880:        fprintf(ficresprob,"\n%d ",(int)age);
                   7881:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7882:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7883:                        
1.222     brouard  7884:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7885:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7886:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7887:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7888:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7889:        }
                   7890:        i=0;
                   7891:        for (k=1; k<=(nlstate);k++){
                   7892:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7893:           i++;
                   7894:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7895:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7896:           for (j=1; j<=i;j++){
                   7897:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7898:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7899:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7900:           }
                   7901:         }
                   7902:        }/* end of loop for state */
                   7903:      } /* end of loop for age */
                   7904:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7905:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7906:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7907:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7908:     
                   7909:      /* Confidence intervalle of pij  */
                   7910:      /*
                   7911:        fprintf(ficgp,"\nunset parametric;unset label");
                   7912:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7913:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7914:        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);
                   7915:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7916:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7917:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7918:      */
                   7919:                
                   7920:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7921:      first1=1;first2=2;
                   7922:      for (k2=1; k2<=(nlstate);k2++){
                   7923:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7924:         if(l2==k2) continue;
                   7925:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7926:         for (k1=1; k1<=(nlstate);k1++){
                   7927:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7928:             if(l1==k1) continue;
                   7929:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7930:             if(i<=j) continue;
                   7931:             for (age=bage; age<=fage; age ++){ 
                   7932:               if ((int)age %5==0){
                   7933:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7934:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7935:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7936:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7937:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7938:                 c12=cv12/sqrt(v1*v2);
                   7939:                 /* Computing eigen value of matrix of covariance */
                   7940:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7941:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7942:                 if ((lc2 <0) || (lc1 <0) ){
                   7943:                   if(first2==1){
                   7944:                     first1=0;
                   7945:                     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);
                   7946:                   }
                   7947:                   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);
                   7948:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7949:                   /* lc2=fabs(lc2); */
                   7950:                 }
1.220     brouard  7951:                                                                
1.222     brouard  7952:                 /* Eigen vectors */
1.280     brouard  7953:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7954:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7955:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7956:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7957:                 }else
                   7958:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7959:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7960:                 v21=(lc1-v1)/cv12*v11;
                   7961:                 v12=-v21;
                   7962:                 v22=v11;
                   7963:                 tnalp=v21/v11;
                   7964:                 if(first1==1){
                   7965:                   first1=0;
                   7966:                   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);
                   7967:                 }
                   7968:                 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);
                   7969:                 /*printf(fignu*/
                   7970:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7971:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7972:                 if(first==1){
                   7973:                   first=0;
                   7974:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7975:                   fprintf(ficgp,"\nset parametric;unset label");
                   7976:                   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);
                   7977:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7978:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7979:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7980: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7981:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7982:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7983:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7984:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7985:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7986:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7987:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7988:                   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  7989:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   7990:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  7991:                 }else{
                   7992:                   first=0;
                   7993:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   7994:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7995:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7996:                   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  7997:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   7998:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  7999:                 }/* if first */
                   8000:               } /* age mod 5 */
                   8001:             } /* end loop age */
                   8002:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   8003:             first=1;
                   8004:           } /*l12 */
                   8005:         } /* k12 */
                   8006:        } /*l1 */
                   8007:      }/* k1 */
1.332     brouard  8008:    }  /* loop on combination of covariates j1 */
1.326     brouard  8009:    } /* loop on nres */
1.222     brouard  8010:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   8011:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   8012:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   8013:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   8014:    free_vector(xp,1,npar);
                   8015:    fclose(ficresprob);
                   8016:    fclose(ficresprobcov);
                   8017:    fclose(ficresprobcor);
                   8018:    fflush(ficgp);
                   8019:    fflush(fichtmcov);
                   8020:  }
1.126     brouard  8021: 
                   8022: 
                   8023: /******************* Printing html file ***********/
1.201     brouard  8024: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  8025:                  int lastpass, int stepm, int weightopt, char model[],\
                   8026:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  8027:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   8028:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   8029:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  8030:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  8031:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  8032:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   8033:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   8034: </ul>");
1.319     brouard  8035: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   8036: /* </ul>", model); */
1.214     brouard  8037:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   8038:    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",
                   8039:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  8040:    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  8041:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   8042:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  8043:    fprintf(fichtm,"\
                   8044:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  8045:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  8046:    fprintf(fichtm,"\
1.217     brouard  8047:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   8048:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   8049:    fprintf(fichtm,"\
1.288     brouard  8050:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  8051:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  8052:    fprintf(fichtm,"\
1.288     brouard  8053:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  8054:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   8055:    fprintf(fichtm,"\
1.211     brouard  8056:  - (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  8057:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  8058:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  8059:    if(prevfcast==1){
                   8060:      fprintf(fichtm,"\
                   8061:  - Prevalence projections by age and states:                           \
1.201     brouard  8062:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  8063:    }
1.126     brouard  8064: 
                   8065: 
1.225     brouard  8066:    m=pow(2,cptcoveff);
1.222     brouard  8067:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  8068: 
1.317     brouard  8069:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  8070: 
                   8071:    jj1=0;
                   8072: 
                   8073:    fprintf(fichtm," \n<ul>");
1.337     brouard  8074:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8075:      /* k1=nres; */
1.338     brouard  8076:      k1=TKresult[nres];
                   8077:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
1.337     brouard  8078:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8079:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   8080:    /*     continue; */
1.264     brouard  8081:      jj1++;
                   8082:      if (cptcovn > 0) {
                   8083:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
1.337     brouard  8084:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   8085:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  8086:        }
1.337     brouard  8087:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   8088:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   8089:        /* } */
                   8090:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8091:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8092:        /* } */
1.264     brouard  8093:        fprintf(fichtm,"\">");
                   8094:        
                   8095:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8096:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  8097:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8098:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  8099:        }
1.337     brouard  8100:        /* fprintf(fichtm,"************ Results for covariates"); */
                   8101:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   8102:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   8103:        /* } */
                   8104:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8105:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8106:        /* } */
1.264     brouard  8107:        if(invalidvarcomb[k1]){
                   8108:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8109:         continue;
                   8110:        }
                   8111:        fprintf(fichtm,"</a></li>");
                   8112:      } /* cptcovn >0 */
                   8113:    }
1.317     brouard  8114:    fprintf(fichtm," \n</ul>");
1.264     brouard  8115: 
1.222     brouard  8116:    jj1=0;
1.237     brouard  8117: 
1.337     brouard  8118:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8119:      /* k1=nres; */
1.338     brouard  8120:      k1=TKresult[nres];
                   8121:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8122:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8123:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   8124:    /*     continue; */
1.220     brouard  8125: 
1.222     brouard  8126:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8127:      jj1++;
                   8128:      if (cptcovn > 0) {
1.264     brouard  8129:        fprintf(fichtm,"\n<p><a name=\"rescov");
1.337     brouard  8130:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8131:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  8132:        }
1.337     brouard  8133:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8134:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8135:        /* } */
1.264     brouard  8136:        fprintf(fichtm,"\"</a>");
                   8137:  
1.222     brouard  8138:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  8139:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8140:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8141:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  8142:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   8143:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  8144:        }
1.230     brouard  8145:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.338     brouard  8146:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  8147:        if(invalidvarcomb[k1]){
                   8148:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   8149:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   8150:         continue;
                   8151:        }
                   8152:      }
                   8153:      /* aij, bij */
1.259     brouard  8154:      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  8155: <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  8156:      /* Pij */
1.241     brouard  8157:      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> \
                   8158: <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  8159:      /* Quasi-incidences */
                   8160:      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  8161:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  8162:  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  8163: 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> \
                   8164: <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  8165:      /* Survival functions (period) in state j */
                   8166:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  8167:        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);
                   8168:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   8169:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  8170:      }
                   8171:      /* State specific survival functions (period) */
                   8172:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  8173:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   8174:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.329     brouard  8175:  <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);
                   8176:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   8177:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  8178:      }
1.288     brouard  8179:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  8180:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  8181:        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  8182:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
1.329     brouard  8183:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  8184:      }
1.296     brouard  8185:      if(prevbcast==1){
1.288     brouard  8186:        /* Backward prevalence in each health state */
1.222     brouard  8187:        for(cpt=1; cpt<=nlstate;cpt++){
1.338     brouard  8188:         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);
                   8189:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
                   8190:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  8191:        }
1.217     brouard  8192:      }
1.222     brouard  8193:      if(prevfcast==1){
1.288     brouard  8194:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  8195:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  8196:         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);
                   8197:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   8198:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   8199:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  8200:        }
                   8201:      }
1.296     brouard  8202:      if(prevbcast==1){
1.268     brouard  8203:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   8204:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  8205:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   8206:  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 \
                   8207:  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  8208: 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);
                   8209:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   8210:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  8211:        }
                   8212:      }
1.220     brouard  8213:         
1.222     brouard  8214:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  8215:        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);
                   8216:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   8217:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  8218:      }
                   8219:      /* } /\* end i1 *\/ */
1.337     brouard  8220:    }/* End k1=nres */
1.222     brouard  8221:    fprintf(fichtm,"</ul>");
1.126     brouard  8222: 
1.222     brouard  8223:    fprintf(fichtm,"\
1.126     brouard  8224: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  8225:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  8226:  - 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  8227: But because parameters are usually highly correlated (a higher incidence of disability \
                   8228: and a higher incidence of recovery can give very close observed transition) it might \
                   8229: be very useful to look not only at linear confidence intervals estimated from the \
                   8230: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   8231: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   8232: covariance matrix of the one-step probabilities. \
                   8233: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  8234: 
1.222     brouard  8235:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   8236:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   8237:    fprintf(fichtm,"\
1.126     brouard  8238:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8239:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  8240: 
1.222     brouard  8241:    fprintf(fichtm,"\
1.126     brouard  8242:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8243:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   8244:    fprintf(fichtm,"\
1.126     brouard  8245:  - 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): \
                   8246:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8247:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  8248:    fprintf(fichtm,"\
1.126     brouard  8249:  - (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): \
                   8250:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8251:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  8252:    fprintf(fichtm,"\
1.288     brouard  8253:  - 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  8254:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   8255:    fprintf(fichtm,"\
1.128     brouard  8256:  - 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  8257:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   8258:    fprintf(fichtm,"\
1.288     brouard  8259:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  8260:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  8261: 
                   8262: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   8263: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   8264: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   8265: /*     <br>",fileres,fileres,fileres,fileres); */
                   8266: /*  else  */
1.338     brouard  8267: /*    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  8268:    fflush(fichtm);
1.126     brouard  8269: 
1.225     brouard  8270:    m=pow(2,cptcoveff);
1.222     brouard  8271:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  8272: 
1.317     brouard  8273:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   8274: 
                   8275:   jj1=0;
                   8276: 
                   8277:    fprintf(fichtm," \n<ul>");
1.337     brouard  8278:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8279:      /* k1=nres; */
1.338     brouard  8280:      k1=TKresult[nres];
1.337     brouard  8281:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8282:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8283:      /*   continue; */
1.317     brouard  8284:      jj1++;
                   8285:      if (cptcovn > 0) {
                   8286:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
1.337     brouard  8287:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8288:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8289:        }
                   8290:        fprintf(fichtm,"\">");
                   8291:        
                   8292:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8293:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  8294:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8295:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8296:        }
                   8297:        if(invalidvarcomb[k1]){
                   8298:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8299:         continue;
                   8300:        }
                   8301:        fprintf(fichtm,"</a></li>");
                   8302:      } /* cptcovn >0 */
1.337     brouard  8303:    } /* End nres */
1.317     brouard  8304:    fprintf(fichtm," \n</ul>");
                   8305: 
1.222     brouard  8306:    jj1=0;
1.237     brouard  8307: 
1.241     brouard  8308:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8309:      /* k1=nres; */
1.338     brouard  8310:      k1=TKresult[nres];
                   8311:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8312:      /* for(k1=1; k1<=m;k1++){ */
                   8313:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8314:      /*   continue; */
1.222     brouard  8315:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8316:      jj1++;
1.126     brouard  8317:      if (cptcovn > 0) {
1.317     brouard  8318:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
1.337     brouard  8319:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8320:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8321:        }
                   8322:        fprintf(fichtm,"\"</a>");
                   8323:        
1.126     brouard  8324:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  8325:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
                   8326:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8327:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  8328:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  8329:        }
1.237     brouard  8330: 
1.338     brouard  8331:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  8332: 
1.222     brouard  8333:        if(invalidvarcomb[k1]){
                   8334:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   8335:         continue;
                   8336:        }
1.337     brouard  8337:      } /* If cptcovn >0 */
1.126     brouard  8338:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  8339:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  8340: 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);
                   8341:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   8342:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  8343:      }
                   8344:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  8345: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  8346: true period expectancies (those weighted with period prevalences are also\
                   8347:  drawn in addition to the population based expectancies computed using\
1.314     brouard  8348:  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);
                   8349:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   8350:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  8351:      /* } /\* end i1 *\/ */
1.241     brouard  8352:   }/* End nres */
1.222     brouard  8353:    fprintf(fichtm,"</ul>");
                   8354:    fflush(fichtm);
1.126     brouard  8355: }
                   8356: 
                   8357: /******************* Gnuplot file **************/
1.296     brouard  8358: 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  8359: 
                   8360:   char dirfileres[132],optfileres[132];
1.264     brouard  8361:   char gplotcondition[132], gplotlabel[132];
1.343     brouard  8362:   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  8363:   int lv=0, vlv=0, kl=0;
1.130     brouard  8364:   int ng=0;
1.201     brouard  8365:   int vpopbased;
1.223     brouard  8366:   int ioffset; /* variable offset for columns */
1.270     brouard  8367:   int iyearc=1; /* variable column for year of projection  */
                   8368:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  8369:   int nres=0; /* Index of resultline */
1.266     brouard  8370:   int istart=1; /* For starting graphs in projections */
1.219     brouard  8371: 
1.126     brouard  8372: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   8373: /*     printf("Problem with file %s",optionfilegnuplot); */
                   8374: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   8375: /*   } */
                   8376: 
                   8377:   /*#ifdef windows */
                   8378:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  8379:   /*#endif */
1.225     brouard  8380:   m=pow(2,cptcoveff);
1.126     brouard  8381: 
1.274     brouard  8382:   /* diagram of the model */
                   8383:   fprintf(ficgp,"\n#Diagram of the model \n");
                   8384:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   8385:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   8386:   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);
                   8387: 
1.343     brouard  8388:   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  8389:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   8390:   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);
                   8391:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   8392:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   8393:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   8394:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   8395: 
1.202     brouard  8396:   /* Contribution to likelihood */
                   8397:   /* Plot the probability implied in the likelihood */
1.223     brouard  8398:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   8399:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   8400:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   8401:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  8402: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  8403:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   8404: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  8405:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   8406:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8407:   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));
                   8408:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8409:   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));
                   8410:   for (i=1; i<= nlstate ; i ++) {
                   8411:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   8412:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   8413:     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);
                   8414:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   8415:       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);
                   8416:     }
                   8417:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8418:   }
                   8419:   /* 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 */               
                   8420:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8421:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8422:   fprintf(ficgp,"\nset out;unset log\n");
                   8423:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  8424: 
1.343     brouard  8425:   /* Plot the probability implied in the likelihood by covariate value */
                   8426:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
                   8427:   /* if(debugILK==1){ */
                   8428:   for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.347     brouard  8429:     kvar=Tvar[TvarFind[kf]]; /* variable name */
                   8430:     /* k=18+Tvar[TvarFind[kf]];/\*offset because there are 18 columns in the ILK_ file but could be placed else where *\/ */
1.350     brouard  8431:     /* k=18+kf;/\*offset because there are 18 columns in the ILK_ file *\/ */
                   8432:     k=19+kf;/*offset because there are 19 columns in the ILK_ file */
1.343     brouard  8433:     for (i=1; i<= nlstate ; i ++) {
                   8434:       fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8435:       fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
1.348     brouard  8436:       if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   8437:        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);
                   8438:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   8439:          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);
                   8440:        }
                   8441:       }else{
                   8442:        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);
                   8443:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   8444:          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);
                   8445:        }
1.343     brouard  8446:       }
                   8447:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8448:     }
                   8449:   } /* End of each covariate dummy */
                   8450:   for(ncovv=1, iposold=0, kk=0; ncovv <= ncovvt ; ncovv++){
                   8451:     /* Other example        V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   8452:      *     kmodel       =     1   2     3     4         5        6        7       8        9
                   8453:      *  varying                   1     2                                 3       4        5
                   8454:      *  ncovv                     1     2                                3 4     5 6      7 8
                   8455:      * TvarVV[ncovv]             V3     5                                1 3     3 5      1 5
                   8456:      * TvarVVind[ncovv]=kmodel    2     3                                7 7     8 8      9 9
                   8457:      * TvarFind[kmodel]       1   0     0     0         0        0        0       0        0
                   8458:      * kdata     ncovcol=[V1 V2] nqv=0 ntv=[V3 V4] nqtv=V5
                   8459:      * Dummy[kmodel]          0   0     1     2         2        3        1       1        1
                   8460:      */
                   8461:     ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   8462:     kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   8463:     /* 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]); */
                   8464:     if(ipos!=iposold){ /* Not a product or first of a product */
                   8465:       /* printf(" %d",ipos); */
                   8466:       /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   8467:       /* printf(" DebugILK ficgp suite ipos=%d != iposold=%d\n", ipos, iposold); */
                   8468:       kk++; /* Position of the ncovv column in ILK_ */
                   8469:       k=18+ncovf+kk; /*offset because there are 18 columns in the ILK_ file plus ncovf fixed covariate */
                   8470:       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)  */
                   8471:        for (i=1; i<= nlstate ; i ++) {
                   8472:          fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8473:          fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   8474: 
1.348     brouard  8475:            /* printf("Before DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
1.343     brouard  8476:          if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   8477:            /* printf("DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
                   8478:            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);
                   8479:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8480:              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);
                   8481:            }
                   8482:          }else{
                   8483:            /* printf("DebugILK gnuplotversion=%g <5.2\n",gnuplotversion); */
                   8484:            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);
                   8485:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8486:              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);
                   8487:            }
                   8488:          }
                   8489:          fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8490:        }
                   8491:       }/* End if dummy varying */
                   8492:     }else{ /*Product */
                   8493:       /* printf("*"); */
                   8494:       /* fprintf(ficresilk,"*"); */
                   8495:     }
                   8496:     iposold=ipos;
                   8497:   } /* For each time varying covariate */
                   8498:   /* } /\* debugILK==1 *\/ */
                   8499:   /* 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 */               
                   8500:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8501:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8502:   fprintf(ficgp,"\nset out;unset log\n");
                   8503:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   8504: 
                   8505: 
                   8506:   
1.126     brouard  8507:   strcpy(dirfileres,optionfilefiname);
                   8508:   strcpy(optfileres,"vpl");
1.223     brouard  8509:   /* 1eme*/
1.238     brouard  8510:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
1.337     brouard  8511:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
1.236     brouard  8512:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8513:        k1=TKresult[nres];
1.338     brouard  8514:        if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.238     brouard  8515:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.337     brouard  8516:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8517:        /*   continue; */
1.238     brouard  8518:        /* We are interested in selected combination by the resultline */
1.246     brouard  8519:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  8520:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  8521:        strcpy(gplotlabel,"(");
1.337     brouard  8522:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8523:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8524:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8525: 
                   8526:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
                   8527:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
                   8528:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8529:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8530:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8531:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8532:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
                   8533:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
                   8534:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
                   8535:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8536:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8537:        /* } */
                   8538:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8539:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
                   8540:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8541:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.264     brouard  8542:        }
                   8543:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  8544:        /* printf("\n#\n"); */
1.238     brouard  8545:        fprintf(ficgp,"\n#\n");
                   8546:        if(invalidvarcomb[k1]){
1.260     brouard  8547:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  8548:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8549:          continue;
                   8550:        }
1.235     brouard  8551:       
1.241     brouard  8552:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   8553:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  8554:        /* 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  8555:        fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  8556:        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);
                   8557:        /* 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); */
                   8558:       /* k1-1 error should be nres-1*/
1.238     brouard  8559:        for (i=1; i<= nlstate ; i ++) {
                   8560:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8561:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   8562:        }
1.288     brouard  8563:        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  8564:        for (i=1; i<= nlstate ; i ++) {
                   8565:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8566:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8567:        } 
1.260     brouard  8568:        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  8569:        for (i=1; i<= nlstate ; i ++) {
                   8570:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8571:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8572:        }  
1.265     brouard  8573:        /* 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)); */
                   8574:        
                   8575:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   8576:         if(cptcoveff ==0){
1.271     brouard  8577:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  8578:        }else{
                   8579:          kl=0;
                   8580:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8581:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8582:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  8583:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8584:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8585:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8586:            vlv= nbcode[Tvaraff[k]][lv];
                   8587:            kl++;
                   8588:            /* 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 *\/ */
                   8589:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8590:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8591:            /* ''  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*/
                   8592:            if(k==cptcoveff){
                   8593:              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], \
                   8594:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   8595:            }else{
                   8596:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   8597:              kl++;
                   8598:            }
                   8599:          } /* end covariate */
                   8600:        } /* end if no covariate */
                   8601: 
1.296     brouard  8602:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  8603:          /* 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  8604:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  8605:          if(cptcoveff ==0){
1.245     brouard  8606:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  8607:          }else{
                   8608:            kl=0;
                   8609:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8610:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8611:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  8612:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8613:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8614:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8615:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8616:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  8617:              kl++;
1.238     brouard  8618:              /* 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 *\/ */
                   8619:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8620:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8621:              /* ''  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*/
                   8622:              if(k==cptcoveff){
1.245     brouard  8623:                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  8624:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  8625:              }else{
1.332     brouard  8626:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  8627:                kl++;
                   8628:              }
                   8629:            } /* end covariate */
                   8630:          } /* end if no covariate */
1.296     brouard  8631:          if(prevbcast == 1){
1.268     brouard  8632:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   8633:            /* k1-1 error should be nres-1*/
                   8634:            for (i=1; i<= nlstate ; i ++) {
                   8635:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8636:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   8637:            }
1.271     brouard  8638:            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  8639:            for (i=1; i<= nlstate ; i ++) {
                   8640:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8641:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8642:            } 
1.276     brouard  8643:            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  8644:            for (i=1; i<= nlstate ; i ++) {
                   8645:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8646:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8647:            } 
1.274     brouard  8648:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  8649:          } /* end if backprojcast */
1.296     brouard  8650:        } /* end if prevbcast */
1.276     brouard  8651:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   8652:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  8653:       } /* nres */
1.337     brouard  8654:     /* } /\* k1 *\/ */
1.201     brouard  8655:   } /* cpt */
1.235     brouard  8656: 
                   8657:   
1.126     brouard  8658:   /*2 eme*/
1.337     brouard  8659:   /* for (k1=1; k1<= m ; k1 ++){   */
1.238     brouard  8660:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8661:       k1=TKresult[nres];
1.338     brouard  8662:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8663:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8664:       /*       continue; */
1.238     brouard  8665:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  8666:       strcpy(gplotlabel,"(");
1.337     brouard  8667:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8668:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8669:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8670:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8671:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8672:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8673:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8674:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8675:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8676:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8677:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8678:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8679:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8680:       /* } */
                   8681:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
                   8682:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8683:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8684:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8685:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  8686:       }
1.264     brouard  8687:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8688:       fprintf(ficgp,"\n#\n");
1.223     brouard  8689:       if(invalidvarcomb[k1]){
                   8690:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8691:        continue;
                   8692:       }
1.219     brouard  8693:                        
1.241     brouard  8694:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  8695:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  8696:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   8697:        if(vpopbased==0){
1.238     brouard  8698:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  8699:        }else
1.238     brouard  8700:          fprintf(ficgp,"\nreplot ");
                   8701:        for (i=1; i<= nlstate+1 ; i ++) {
                   8702:          k=2*i;
1.261     brouard  8703:          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  8704:          for (j=1; j<= nlstate+1 ; j ++) {
                   8705:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8706:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8707:          }   
                   8708:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   8709:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  8710:          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  8711:          for (j=1; j<= nlstate+1 ; j ++) {
                   8712:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8713:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8714:          }   
                   8715:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  8716:          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  8717:          for (j=1; j<= nlstate+1 ; j ++) {
                   8718:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8719:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8720:          }   
                   8721:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   8722:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   8723:        } /* state */
                   8724:       } /* vpopbased */
1.264     brouard  8725:       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  8726:     } /* end nres */
1.337     brouard  8727:   /* } /\* k1 end 2 eme*\/ */
1.238     brouard  8728:        
                   8729:        
                   8730:   /*3eme*/
1.337     brouard  8731:   /* for (k1=1; k1<= m ; k1 ++){ */
1.238     brouard  8732:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8733:       k1=TKresult[nres];
1.338     brouard  8734:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8735:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8736:       /*       continue; */
1.238     brouard  8737: 
1.332     brouard  8738:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  8739:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  8740:        strcpy(gplotlabel,"(");
1.337     brouard  8741:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8742:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8743:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8744:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8745:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8746:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8747:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8748:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8749:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8750:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8751:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8752:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8753:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8754:        /* } */
                   8755:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8756:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8757:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8758:        }
1.264     brouard  8759:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8760:        fprintf(ficgp,"\n#\n");
                   8761:        if(invalidvarcomb[k1]){
                   8762:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8763:          continue;
                   8764:        }
                   8765:                        
                   8766:        /*       k=2+nlstate*(2*cpt-2); */
                   8767:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  8768:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  8769:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  8770:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  8771: 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  8772:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8773:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8774:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   8775:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8776:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8777:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  8778:                                
1.238     brouard  8779:        */
                   8780:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  8781:          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  8782:          /*    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  8783:                                
1.238     brouard  8784:        } 
1.261     brouard  8785:        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  8786:       }
1.264     brouard  8787:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  8788:     } /* end nres */
1.337     brouard  8789:   /* } /\* end kl 3eme *\/ */
1.126     brouard  8790:   
1.223     brouard  8791:   /* 4eme */
1.201     brouard  8792:   /* Survival functions (period) from state i in state j by initial state i */
1.337     brouard  8793:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
1.238     brouard  8794:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8795:       k1=TKresult[nres];
1.338     brouard  8796:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8797:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8798:       /*       continue; */
1.238     brouard  8799:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  8800:        strcpy(gplotlabel,"(");
1.337     brouard  8801:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
                   8802:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8803:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8804:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8805:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8806:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8807:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8808:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8809:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8810:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8811:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8812:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8813:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8814:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8815:        /* } */
                   8816:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8817:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8818:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8819:        }       
1.264     brouard  8820:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8821:        fprintf(ficgp,"\n#\n");
                   8822:        if(invalidvarcomb[k1]){
                   8823:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8824:          continue;
1.223     brouard  8825:        }
1.238     brouard  8826:       
1.241     brouard  8827:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  8828:        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  8829:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8830: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8831:        k=3;
                   8832:        for (i=1; i<= nlstate ; i ++){
                   8833:          if(i==1){
                   8834:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8835:          }else{
                   8836:            fprintf(ficgp,", '' ");
                   8837:          }
                   8838:          l=(nlstate+ndeath)*(i-1)+1;
                   8839:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8840:          for (j=2; j<= nlstate+ndeath ; j ++)
                   8841:            fprintf(ficgp,"+$%d",k+l+j-1);
                   8842:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   8843:        } /* nlstate */
1.264     brouard  8844:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8845:       } /* end cpt state*/ 
                   8846:     } /* end nres */
1.337     brouard  8847:   /* } /\* end covariate k1 *\/   */
1.238     brouard  8848: 
1.220     brouard  8849: /* 5eme */
1.201     brouard  8850:   /* Survival functions (period) from state i in state j by final state j */
1.337     brouard  8851:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
1.238     brouard  8852:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8853:       k1=TKresult[nres];
1.338     brouard  8854:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8855:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8856:       /*       continue; */
1.238     brouard  8857:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  8858:        strcpy(gplotlabel,"(");
1.238     brouard  8859:        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  8860:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8861:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8862:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8863:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8864:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8865:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8866:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8867:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8868:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8869:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8870:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8871:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8872:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8873:        /* } */
                   8874:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8875:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8876:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8877:        }       
1.264     brouard  8878:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8879:        fprintf(ficgp,"\n#\n");
                   8880:        if(invalidvarcomb[k1]){
                   8881:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8882:          continue;
                   8883:        }
1.227     brouard  8884:       
1.241     brouard  8885:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  8886:        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  8887:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8888: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8889:        k=3;
                   8890:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8891:          if(j==1)
                   8892:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8893:          else
                   8894:            fprintf(ficgp,", '' ");
                   8895:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8896:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   8897:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   8898:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   8899:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   8900:        } /* nlstate */
                   8901:        fprintf(ficgp,", '' ");
                   8902:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   8903:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8904:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8905:          if(j < nlstate)
                   8906:            fprintf(ficgp,"$%d +",k+l);
                   8907:          else
                   8908:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   8909:        }
1.264     brouard  8910:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8911:       } /* end cpt state*/ 
1.337     brouard  8912:     /* } /\* end covariate *\/   */
1.238     brouard  8913:   } /* end nres */
1.227     brouard  8914:   
1.220     brouard  8915: /* 6eme */
1.202     brouard  8916:   /* CV preval stable (period) for each covariate */
1.337     brouard  8917:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8918:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8919:      k1=TKresult[nres];
1.338     brouard  8920:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8921:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8922:      /*  continue; */
1.255     brouard  8923:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  8924:       strcpy(gplotlabel,"(");      
1.288     brouard  8925:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8926:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8927:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8928:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8929:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8930:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8931:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8932:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8933:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8934:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8935:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8936:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8937:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8938:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8939:       /* } */
                   8940:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8941:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8942:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8943:       }        
1.264     brouard  8944:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8945:       fprintf(ficgp,"\n#\n");
1.223     brouard  8946:       if(invalidvarcomb[k1]){
1.227     brouard  8947:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8948:        continue;
1.223     brouard  8949:       }
1.227     brouard  8950:       
1.241     brouard  8951:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  8952:       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  8953:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8954: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  8955:       k=3; /* Offset */
1.255     brouard  8956:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  8957:        if(i==1)
                   8958:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8959:        else
                   8960:          fprintf(ficgp,", '' ");
1.255     brouard  8961:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  8962:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8963:        for (j=2; j<= nlstate ; j ++)
                   8964:          fprintf(ficgp,"+$%d",k+l+j-1);
                   8965:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  8966:       } /* nlstate */
1.264     brouard  8967:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  8968:     } /* end cpt state*/ 
                   8969:   } /* end covariate */  
1.227     brouard  8970:   
                   8971:   
1.220     brouard  8972: /* 7eme */
1.296     brouard  8973:   if(prevbcast == 1){
1.288     brouard  8974:     /* CV backward prevalence  for each covariate */
1.337     brouard  8975:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8976:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8977:       k1=TKresult[nres];
1.338     brouard  8978:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8979:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8980:       /*       continue; */
1.268     brouard  8981:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  8982:        strcpy(gplotlabel,"(");      
1.288     brouard  8983:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8984:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8985:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8986:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8987:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8988:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8989:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8990:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8991:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8992:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8993:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8994:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8995:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8996:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8997:        /* } */
                   8998:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8999:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9000:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  9001:        }       
1.264     brouard  9002:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  9003:        fprintf(ficgp,"\n#\n");
                   9004:        if(invalidvarcomb[k1]){
                   9005:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9006:          continue;
                   9007:        }
                   9008:        
1.241     brouard  9009:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  9010:        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  9011:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  9012: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  9013:        k=3; /* Offset */
1.268     brouard  9014:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  9015:          if(i==1)
                   9016:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   9017:          else
                   9018:            fprintf(ficgp,", '' ");
                   9019:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  9020:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  9021:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   9022:          /* 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  9023:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  9024:          /* for (j=2; j<= nlstate ; j ++) */
                   9025:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   9026:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  9027:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  9028:        } /* nlstate */
1.264     brouard  9029:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  9030:       } /* end cpt state*/ 
                   9031:     } /* end covariate */  
1.296     brouard  9032:   } /* End if prevbcast */
1.218     brouard  9033:   
1.223     brouard  9034:   /* 8eme */
1.218     brouard  9035:   if(prevfcast==1){
1.288     brouard  9036:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  9037:     
1.337     brouard  9038:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  9039:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9040:       k1=TKresult[nres];
1.338     brouard  9041:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9042:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9043:       /*       continue; */
1.211     brouard  9044:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  9045:        strcpy(gplotlabel,"(");      
1.288     brouard  9046:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  9047:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9048:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9049:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9050:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9051:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9052:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9053:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9054:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9055:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9056:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9057:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9058:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9059:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9060:        /* } */
                   9061:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9062:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9063:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  9064:        }       
1.264     brouard  9065:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  9066:        fprintf(ficgp,"\n#\n");
                   9067:        if(invalidvarcomb[k1]){
                   9068:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9069:          continue;
                   9070:        }
                   9071:        
                   9072:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  9073:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  9074:        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  9075:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  9076: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  9077: 
                   9078:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   9079:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9080:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9081:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  9082:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9083:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9084:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9085:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  9086:          if(i==istart){
1.227     brouard  9087:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   9088:          }else{
                   9089:            fprintf(ficgp,",\\\n '' ");
                   9090:          }
                   9091:          if(cptcoveff ==0){ /* No covariate */
                   9092:            ioffset=2; /* Age is in 2 */
                   9093:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9094:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9095:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9096:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9097:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  9098:            if(i==nlstate+1){
1.270     brouard  9099:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  9100:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   9101:              fprintf(ficgp,",\\\n '' ");
                   9102:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  9103:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  9104:                     offyear,                           \
1.268     brouard  9105:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  9106:            }else
1.227     brouard  9107:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   9108:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   9109:          }else{ /* more than 2 covariates */
1.270     brouard  9110:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   9111:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9112:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   9113:            iyearc=ioffset-1;
                   9114:            iagec=ioffset;
1.227     brouard  9115:            fprintf(ficgp," u %d:(",ioffset); 
                   9116:            kl=0;
                   9117:            strcpy(gplotcondition,"(");
1.351     brouard  9118:            /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
1.332     brouard  9119:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
1.351     brouard  9120:            for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9121:              /* lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9122:              lv=Tvresult[nres][k];
                   9123:              vlv=TinvDoQresult[nres][Tvresult[nres][k]];
1.227     brouard  9124:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9125:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9126:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  9127:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
1.351     brouard  9128:              /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
1.227     brouard  9129:              kl++;
1.351     brouard  9130:              /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   9131:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,lv, kl+1, vlv );
1.227     brouard  9132:              kl++;
1.351     brouard  9133:              if(k <cptcovs && cptcovs>1)
1.227     brouard  9134:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9135:            }
                   9136:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9137:            /* 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 *\/ */
                   9138:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9139:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9140:            /* ''  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*/
                   9141:            if(i==nlstate+1){
1.270     brouard  9142:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   9143:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  9144:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  9145:              fprintf(ficgp," u %d:(",iagec); 
                   9146:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   9147:                      iyearc, iagec, offyear,                           \
                   9148:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  9149: /*  '' 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  9150:            }else{
                   9151:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   9152:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   9153:            }
                   9154:          } /* end if covariate */
                   9155:        } /* nlstate */
1.264     brouard  9156:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  9157:       } /* end cpt state*/
                   9158:     } /* end covariate */
                   9159:   } /* End if prevfcast */
1.227     brouard  9160:   
1.296     brouard  9161:   if(prevbcast==1){
1.268     brouard  9162:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   9163:     
1.337     brouard  9164:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.268     brouard  9165:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9166:      k1=TKresult[nres];
1.338     brouard  9167:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9168:        /* if(m != 1 && TKresult[nres]!= k1) */
                   9169:        /*      continue; */
1.268     brouard  9170:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   9171:        strcpy(gplotlabel,"(");      
                   9172:        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  9173:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9174:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9175:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9176:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9177:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9178:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9179:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9180:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9181:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9182:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9183:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9184:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9185:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9186:        /* } */
                   9187:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9188:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9189:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.268     brouard  9190:        }       
                   9191:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   9192:        fprintf(ficgp,"\n#\n");
                   9193:        if(invalidvarcomb[k1]){
                   9194:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9195:          continue;
                   9196:        }
                   9197:        
                   9198:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   9199:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   9200:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   9201:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   9202: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   9203: 
                   9204:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   9205:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9206:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9207:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   9208:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9209:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9210:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9211:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9212:          if(i==istart){
                   9213:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   9214:          }else{
                   9215:            fprintf(ficgp,",\\\n '' ");
                   9216:          }
1.351     brouard  9217:          /* if(cptcoveff ==0){ /\* No covariate *\/ */
                   9218:          if(cptcovs ==0){ /* No covariate */
1.268     brouard  9219:            ioffset=2; /* Age is in 2 */
                   9220:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9221:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9222:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9223:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9224:            fprintf(ficgp," u %d:(", ioffset); 
                   9225:            if(i==nlstate+1){
1.270     brouard  9226:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  9227:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   9228:              fprintf(ficgp,",\\\n '' ");
                   9229:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  9230:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  9231:                     offbyear,                          \
                   9232:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   9233:            }else
                   9234:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   9235:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   9236:          }else{ /* more than 2 covariates */
1.270     brouard  9237:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   9238:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9239:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   9240:            iyearc=ioffset-1;
                   9241:            iagec=ioffset;
1.268     brouard  9242:            fprintf(ficgp," u %d:(",ioffset); 
                   9243:            kl=0;
                   9244:            strcpy(gplotcondition,"(");
1.337     brouard  9245:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
1.338     brouard  9246:              if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
1.337     brouard  9247:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
                   9248:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9249:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9250:                lv=Tvresult[nres][k];
                   9251:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
                   9252:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9253:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9254:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   9255:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   9256:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9257:                kl++;
                   9258:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   9259:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
                   9260:                kl++;
1.338     brouard  9261:                if(k <cptcovs && cptcovs>1)
1.337     brouard  9262:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9263:              }
1.268     brouard  9264:            }
                   9265:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9266:            /* 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 *\/ */
                   9267:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9268:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9269:            /* ''  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*/
                   9270:            if(i==nlstate+1){
1.270     brouard  9271:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   9272:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  9273:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  9274:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  9275:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  9276:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   9277:                      iyearc,iagec,offbyear,                            \
                   9278:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  9279: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   9280:            }else{
                   9281:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   9282:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   9283:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   9284:            }
                   9285:          } /* end if covariate */
                   9286:        } /* nlstate */
                   9287:        fprintf(ficgp,"\nset out; unset label;\n");
                   9288:       } /* end cpt state*/
                   9289:     } /* end covariate */
1.296     brouard  9290:   } /* End if prevbcast */
1.268     brouard  9291:   
1.227     brouard  9292:   
1.238     brouard  9293:   /* 9eme writing MLE parameters */
                   9294:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  9295:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  9296:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  9297:     for(k=1; k <=(nlstate+ndeath); k++){
                   9298:       if (k != i) {
1.227     brouard  9299:        fprintf(ficgp,"#   current state %d\n",k);
                   9300:        for(j=1; j <=ncovmodel; j++){
                   9301:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   9302:          jk++; 
                   9303:        }
                   9304:        fprintf(ficgp,"\n");
1.126     brouard  9305:       }
                   9306:     }
1.223     brouard  9307:   }
1.187     brouard  9308:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  9309:   
1.145     brouard  9310:   /*goto avoid;*/
1.238     brouard  9311:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   9312:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  9313:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   9314:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   9315:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   9316:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   9317:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9318:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9319:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9320:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9321:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   9322:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9323:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   9324:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   9325:   fprintf(ficgp,"#\n");
1.223     brouard  9326:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  9327:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.338     brouard  9328:     fprintf(ficgp,"#model=1+age+%s \n",model);
1.238     brouard  9329:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.351     brouard  9330:     /* fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/\* to be checked *\/ */
                   9331:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcovs,m);/* to be checked */
1.337     brouard  9332:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
1.237     brouard  9333:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9334:      /* k1=nres; */
1.338     brouard  9335:       k1=TKresult[nres];
                   9336:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9337:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
1.264     brouard  9338:       strcpy(gplotlabel,"(");
1.276     brouard  9339:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.337     brouard  9340:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   9341:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
                   9342:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
                   9343:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9344:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9345:       }
                   9346:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9347:       /*       continue; */
                   9348:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
                   9349:       /* strcpy(gplotlabel,"("); */
                   9350:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
                   9351:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9352:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9353:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9354:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9355:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9356:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9357:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9358:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9359:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9360:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9361:       /* } */
                   9362:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9363:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9364:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9365:       /* }      */
1.264     brouard  9366:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  9367:       fprintf(ficgp,"\n#\n");
1.264     brouard  9368:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  9369:       fprintf(ficgp,"\nset key outside ");
                   9370:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   9371:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  9372:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   9373:       if (ng==1){
                   9374:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   9375:        fprintf(ficgp,"\nunset log y");
                   9376:       }else if (ng==2){
                   9377:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   9378:        fprintf(ficgp,"\nset log y");
                   9379:       }else if (ng==3){
                   9380:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   9381:        fprintf(ficgp,"\nset log y");
                   9382:       }else
                   9383:        fprintf(ficgp,"\nunset title ");
                   9384:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   9385:       i=1;
                   9386:       for(k2=1; k2<=nlstate; k2++) {
                   9387:        k3=i;
                   9388:        for(k=1; k<=(nlstate+ndeath); k++) {
                   9389:          if (k != k2){
                   9390:            switch( ng) {
                   9391:            case 1:
                   9392:              if(nagesqr==0)
                   9393:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   9394:              else /* nagesqr =1 */
                   9395:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9396:              break;
                   9397:            case 2: /* ng=2 */
                   9398:              if(nagesqr==0)
                   9399:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   9400:              else /* nagesqr =1 */
                   9401:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9402:              break;
                   9403:            case 3:
                   9404:              if(nagesqr==0)
                   9405:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   9406:              else /* nagesqr =1 */
                   9407:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   9408:              break;
                   9409:            }
                   9410:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  9411:            ijp=1; /* product no age */
                   9412:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   9413:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  9414:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  9415:              switch(Typevar[j]){
                   9416:              case 1:
                   9417:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9418:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   9419:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9420:                      if(DummyV[j]==0){/* Bug valgrind */
                   9421:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   9422:                      }else{ /* quantitative */
                   9423:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9424:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9425:                      }
                   9426:                      ij++;
1.268     brouard  9427:                    }
1.237     brouard  9428:                  }
1.329     brouard  9429:                }
                   9430:                break;
                   9431:              case 2:
                   9432:                if(cptcovprod >0){
                   9433:                  if(j==Tprod[ijp]) { /* */ 
                   9434:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9435:                    if(ijp <=cptcovprod) { /* Product */
                   9436:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9437:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9438:                          /* 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)]); */
                   9439:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9440:                        }else{ /* Vn is dummy and Vm is quanti */
                   9441:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9442:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9443:                        }
                   9444:                      }else{ /* Vn*Vm Vn is quanti */
                   9445:                        if(DummyV[Tvard[ijp][2]]==0){
                   9446:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9447:                        }else{ /* Both quanti */
                   9448:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9449:                        }
1.268     brouard  9450:                      }
1.329     brouard  9451:                      ijp++;
1.237     brouard  9452:                    }
1.329     brouard  9453:                  } /* end Tprod */
                   9454:                }
                   9455:                break;
1.349     brouard  9456:              case 3:
                   9457:                if(cptcovdageprod >0){
                   9458:                  /* if(j==Tprod[ijp]) { */ /* not necessary */ 
                   9459:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
1.350     brouard  9460:                    if(ijp <=cptcovprod) { /* Product Vn*Vm and age*VN*Vm*/
                   9461:                      if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   9462:                        if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  9463:                          /* 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)]); */
                   9464:                          fprintf(ficgp,"+p%d*%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9465:                        }else{ /* Vn is dummy and Vm is quanti */
                   9466:                          /* 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  9467:                          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  9468:                        }
1.350     brouard  9469:                      }else{ /* age* Vn*Vm Vn is quanti HERE */
1.349     brouard  9470:                        if(DummyV[Tvard[ijp][2]]==0){
1.350     brouard  9471:                          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  9472:                        }else{ /* Both quanti */
1.350     brouard  9473:                          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  9474:                        }
                   9475:                      }
                   9476:                      ijp++;
                   9477:                    }
                   9478:                    /* } */ /* end Tprod */
                   9479:                }
                   9480:                break;
1.329     brouard  9481:              case 0:
                   9482:                /* simple covariate */
1.264     brouard  9483:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  9484:                if(Dummy[j]==0){
                   9485:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   9486:                }else{ /* quantitative */
                   9487:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  9488:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  9489:                }
1.329     brouard  9490:               /* end simple */
                   9491:                break;
                   9492:              default:
                   9493:                break;
                   9494:              } /* end switch */
1.237     brouard  9495:            } /* end j */
1.329     brouard  9496:          }else{ /* k=k2 */
                   9497:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   9498:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   9499:            }else
                   9500:              i=i-ncovmodel;
1.223     brouard  9501:          }
1.227     brouard  9502:          
1.223     brouard  9503:          if(ng != 1){
                   9504:            fprintf(ficgp,")/(1");
1.227     brouard  9505:            
1.264     brouard  9506:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  9507:              if(nagesqr==0)
1.264     brouard  9508:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  9509:              else /* nagesqr =1 */
1.264     brouard  9510:                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  9511:               
1.223     brouard  9512:              ij=1;
1.329     brouard  9513:              ijp=1;
                   9514:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   9515:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   9516:                switch(Typevar[j]){
                   9517:                case 1:
                   9518:                  if(cptcovage >0){ 
                   9519:                    if(j==Tage[ij]) { /* Bug valgrind */
                   9520:                      if(ij <=cptcovage) { /* Bug valgrind */
                   9521:                        if(DummyV[j]==0){/* Bug valgrind */
                   9522:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   9523:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   9524:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   9525:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   9526:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9527:                        }else{ /* quantitative */
                   9528:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9529:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9530:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9531:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9532:                        }
                   9533:                        ij++;
                   9534:                      }
                   9535:                    }
                   9536:                  }
                   9537:                  break;
                   9538:                case 2:
                   9539:                  if(cptcovprod >0){
                   9540:                    if(j==Tprod[ijp]) { /* */ 
                   9541:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9542:                      if(ijp <=cptcovprod) { /* Product */
                   9543:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9544:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9545:                            /* 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)]); */
                   9546:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9547:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9548:                          }else{ /* Vn is dummy and Vm is quanti */
                   9549:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9550:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9551:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9552:                          }
                   9553:                        }else{ /* Vn*Vm Vn is quanti */
                   9554:                          if(DummyV[Tvard[ijp][2]]==0){
                   9555:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9556:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9557:                          }else{ /* Both quanti */
                   9558:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9559:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9560:                          } 
                   9561:                        }
                   9562:                        ijp++;
                   9563:                      }
                   9564:                    } /* end Tprod */
                   9565:                  } /* end if */
                   9566:                  break;
1.349     brouard  9567:                case 3:
                   9568:                  if(cptcovdageprod >0){
                   9569:                    /* if(j==Tprod[ijp]) { /\* *\/  */
                   9570:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9571:                      if(ijp <=cptcovprod) { /* Product */
1.350     brouard  9572:                        if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   9573:                          if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  9574:                            /* 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  9575:                            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  9576:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9577:                          }else{ /* Vn is dummy and Vm is quanti */
                   9578:                            /* 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  9579:                            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  9580:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9581:                          }
                   9582:                        }else{ /* Vn*Vm Vn is quanti */
1.350     brouard  9583:                          if(DummyV[Tvardk[ijp][2]]==0){
                   9584:                            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  9585:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9586:                          }else{ /* Both quanti */
1.350     brouard  9587:                            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  9588:                            /* fprintf(ficgp,"+p%d*%f*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9589:                          } 
                   9590:                        }
                   9591:                        ijp++;
                   9592:                      }
                   9593:                    /* } /\* end Tprod *\/ */
                   9594:                  } /* end if */
                   9595:                  break;
1.329     brouard  9596:                case 0: 
                   9597:                  /* simple covariate */
                   9598:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   9599:                  if(Dummy[j]==0){
                   9600:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9601:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   9602:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9603:                  }else{ /* quantitative */
                   9604:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   9605:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   9606:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9607:                  }
                   9608:                  /* end simple */
                   9609:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   9610:                  break;
                   9611:                default:
                   9612:                  break;
                   9613:                } /* end switch */
1.223     brouard  9614:              }
                   9615:              fprintf(ficgp,")");
                   9616:            }
                   9617:            fprintf(ficgp,")");
                   9618:            if(ng ==2)
1.276     brouard  9619:              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  9620:            else /* ng= 3 */
1.276     brouard  9621:              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  9622:           }else{ /* end ng <> 1 */
1.223     brouard  9623:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  9624:              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  9625:          }
                   9626:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   9627:            fprintf(ficgp,",");
                   9628:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   9629:            fprintf(ficgp,",");
                   9630:          i=i+ncovmodel;
                   9631:        } /* end k */
                   9632:       } /* end k2 */
1.276     brouard  9633:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   9634:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.337     brouard  9635:     } /* end resultline */
1.223     brouard  9636:   } /* end ng */
                   9637:   /* avoid: */
                   9638:   fflush(ficgp); 
1.126     brouard  9639: }  /* end gnuplot */
                   9640: 
                   9641: 
                   9642: /*************** Moving average **************/
1.219     brouard  9643: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  9644:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  9645:    
1.222     brouard  9646:    int i, cpt, cptcod;
                   9647:    int modcovmax =1;
                   9648:    int mobilavrange, mob;
                   9649:    int iage=0;
1.288     brouard  9650:    int firstA1=0, firstA2=0;
1.222     brouard  9651: 
1.266     brouard  9652:    double sum=0., sumr=0.;
1.222     brouard  9653:    double age;
1.266     brouard  9654:    double *sumnewp, *sumnewm, *sumnewmr;
                   9655:    double *agemingood, *agemaxgood; 
                   9656:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  9657:   
                   9658:   
1.278     brouard  9659:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   9660:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  9661: 
                   9662:    sumnewp = vector(1,ncovcombmax);
                   9663:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  9664:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  9665:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  9666:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  9667:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  9668:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  9669: 
                   9670:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  9671:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  9672:      sumnewp[cptcod]=0.;
1.266     brouard  9673:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   9674:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  9675:    }
                   9676:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   9677:   
1.266     brouard  9678:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   9679:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  9680:      else mobilavrange=mobilav;
                   9681:      for (age=bage; age<=fage; age++)
                   9682:        for (i=1; i<=nlstate;i++)
                   9683:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   9684:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9685:      /* We keep the original values on the extreme ages bage, fage and for 
                   9686:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   9687:        we use a 5 terms etc. until the borders are no more concerned. 
                   9688:      */ 
                   9689:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   9690:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  9691:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   9692:           sumnewm[cptcod]=0.;
                   9693:           for (i=1; i<=nlstate;i++){
1.222     brouard  9694:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   9695:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   9696:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   9697:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   9698:             }
                   9699:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  9700:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9701:           } /* end i */
                   9702:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   9703:         } /* end cptcod */
1.222     brouard  9704:        }/* end age */
                   9705:      }/* end mob */
1.266     brouard  9706:    }else{
                   9707:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  9708:      return -1;
1.266     brouard  9709:    }
                   9710: 
                   9711:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  9712:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   9713:      if(invalidvarcomb[cptcod]){
                   9714:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   9715:        continue;
                   9716:      }
1.219     brouard  9717: 
1.266     brouard  9718:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   9719:        sumnewm[cptcod]=0.;
                   9720:        sumnewmr[cptcod]=0.;
                   9721:        for (i=1; i<=nlstate;i++){
                   9722:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9723:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9724:        }
                   9725:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9726:         agemingoodr[cptcod]=age;
                   9727:        }
                   9728:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9729:           agemingood[cptcod]=age;
                   9730:        }
                   9731:      } /* age */
                   9732:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  9733:        sumnewm[cptcod]=0.;
1.266     brouard  9734:        sumnewmr[cptcod]=0.;
1.222     brouard  9735:        for (i=1; i<=nlstate;i++){
                   9736:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9737:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9738:        }
                   9739:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9740:         agemaxgoodr[cptcod]=age;
1.222     brouard  9741:        }
                   9742:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  9743:         agemaxgood[cptcod]=age;
                   9744:        }
                   9745:      } /* age */
                   9746:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   9747:      /* but they will change */
1.288     brouard  9748:      firstA1=0;firstA2=0;
1.266     brouard  9749:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   9750:        sumnewm[cptcod]=0.;
                   9751:        sumnewmr[cptcod]=0.;
                   9752:        for (i=1; i<=nlstate;i++){
                   9753:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9754:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9755:        }
                   9756:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9757:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9758:           agemaxgoodr[cptcod]=age;  /* age min */
                   9759:           for (i=1; i<=nlstate;i++)
                   9760:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9761:         }else{ /* bad we change the value with the values of good ages */
                   9762:           for (i=1; i<=nlstate;i++){
                   9763:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   9764:           } /* i */
                   9765:         } /* end bad */
                   9766:        }else{
                   9767:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9768:           agemaxgood[cptcod]=age;
                   9769:         }else{ /* bad we change the value with the values of good ages */
                   9770:           for (i=1; i<=nlstate;i++){
                   9771:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   9772:           } /* i */
                   9773:         } /* end bad */
                   9774:        }/* end else */
                   9775:        sum=0.;sumr=0.;
                   9776:        for (i=1; i<=nlstate;i++){
                   9777:         sum+=mobaverage[(int)age][i][cptcod];
                   9778:         sumr+=probs[(int)age][i][cptcod];
                   9779:        }
                   9780:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  9781:         if(!firstA1){
                   9782:           firstA1=1;
                   9783:           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);
                   9784:         }
                   9785:         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  9786:        } /* end bad */
                   9787:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9788:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  9789:         if(!firstA2){
                   9790:           firstA2=1;
                   9791:           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);
                   9792:         }
                   9793:         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  9794:        } /* end bad */
                   9795:      }/* age */
1.266     brouard  9796: 
                   9797:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  9798:        sumnewm[cptcod]=0.;
1.266     brouard  9799:        sumnewmr[cptcod]=0.;
1.222     brouard  9800:        for (i=1; i<=nlstate;i++){
                   9801:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9802:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9803:        } 
                   9804:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9805:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   9806:           agemingoodr[cptcod]=age;
                   9807:           for (i=1; i<=nlstate;i++)
                   9808:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9809:         }else{ /* bad we change the value with the values of good ages */
                   9810:           for (i=1; i<=nlstate;i++){
                   9811:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   9812:           } /* i */
                   9813:         } /* end bad */
                   9814:        }else{
                   9815:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9816:           agemingood[cptcod]=age;
                   9817:         }else{ /* bad */
                   9818:           for (i=1; i<=nlstate;i++){
                   9819:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   9820:           } /* i */
                   9821:         } /* end bad */
                   9822:        }/* end else */
                   9823:        sum=0.;sumr=0.;
                   9824:        for (i=1; i<=nlstate;i++){
                   9825:         sum+=mobaverage[(int)age][i][cptcod];
                   9826:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  9827:        }
1.266     brouard  9828:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  9829:         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  9830:        } /* end bad */
                   9831:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9832:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  9833:         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  9834:        } /* end bad */
                   9835:      }/* age */
1.266     brouard  9836: 
1.222     brouard  9837:                
                   9838:      for (age=bage; age<=fage; age++){
1.235     brouard  9839:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  9840:        sumnewp[cptcod]=0.;
                   9841:        sumnewm[cptcod]=0.;
                   9842:        for (i=1; i<=nlstate;i++){
                   9843:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   9844:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9845:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   9846:        }
                   9847:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   9848:      }
                   9849:      /* printf("\n"); */
                   9850:      /* } */
1.266     brouard  9851: 
1.222     brouard  9852:      /* brutal averaging */
1.266     brouard  9853:      /* for (i=1; i<=nlstate;i++){ */
                   9854:      /*   for (age=1; age<=bage; age++){ */
                   9855:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   9856:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9857:      /*   }     */
                   9858:      /*   for (age=fage; age<=AGESUP; age++){ */
                   9859:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   9860:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9861:      /*   } */
                   9862:      /* } /\* end i status *\/ */
                   9863:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   9864:      /*   for (age=1; age<=AGESUP; age++){ */
                   9865:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   9866:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   9867:      /*   } */
                   9868:      /* } */
1.222     brouard  9869:    }/* end cptcod */
1.266     brouard  9870:    free_vector(agemaxgoodr,1, ncovcombmax);
                   9871:    free_vector(agemaxgood,1, ncovcombmax);
                   9872:    free_vector(agemingood,1, ncovcombmax);
                   9873:    free_vector(agemingoodr,1, ncovcombmax);
                   9874:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  9875:    free_vector(sumnewm,1, ncovcombmax);
                   9876:    free_vector(sumnewp,1, ncovcombmax);
                   9877:    return 0;
                   9878:  }/* End movingaverage */
1.218     brouard  9879:  
1.126     brouard  9880: 
1.296     brouard  9881:  
1.126     brouard  9882: /************** Forecasting ******************/
1.296     brouard  9883: /* 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)*/
                   9884: 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){
                   9885:   /* dateintemean, mean date of interviews
                   9886:      dateprojd, year, month, day of starting projection 
                   9887:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  9888:      agemin, agemax range of age
                   9889:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   9890:   */
1.296     brouard  9891:   /* double anprojd, mprojd, jprojd; */
                   9892:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  9893:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  9894:   double agec; /* generic age */
1.296     brouard  9895:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  9896:   double *popeffectif,*popcount;
                   9897:   double ***p3mat;
1.218     brouard  9898:   /* double ***mobaverage; */
1.126     brouard  9899:   char fileresf[FILENAMELENGTH];
                   9900: 
                   9901:   agelim=AGESUP;
1.211     brouard  9902:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9903:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9904:      We still use firstpass and lastpass as another selection.
                   9905:   */
1.214     brouard  9906:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9907:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  9908:  
1.201     brouard  9909:   strcpy(fileresf,"F_"); 
                   9910:   strcat(fileresf,fileresu);
1.126     brouard  9911:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   9912:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   9913:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   9914:   }
1.235     brouard  9915:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   9916:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  9917: 
1.225     brouard  9918:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  9919: 
                   9920: 
                   9921:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9922:   if (stepm<=12) stepsize=1;
                   9923:   if(estepm < stepm){
                   9924:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9925:   }
1.270     brouard  9926:   else{
                   9927:     hstepm=estepm;   
                   9928:   }
                   9929:   if(estepm > stepm){ /* Yes every two year */
                   9930:     stepsize=2;
                   9931:   }
1.296     brouard  9932:   hstepm=hstepm/stepm;
1.126     brouard  9933: 
1.296     brouard  9934:   
                   9935:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9936:   /*                              fractional in yp1 *\/ */
                   9937:   /* aintmean=yp; */
                   9938:   /* yp2=modf((yp1*12),&yp); */
                   9939:   /* mintmean=yp; */
                   9940:   /* yp1=modf((yp2*30.5),&yp); */
                   9941:   /* jintmean=yp; */
                   9942:   /* if(jintmean==0) jintmean=1; */
                   9943:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  9944: 
1.296     brouard  9945: 
                   9946:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   9947:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   9948:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.351     brouard  9949:   /* i1=pow(2,cptcoveff); */
                   9950:   /* if (cptcovn < 1){i1=1;} */
1.126     brouard  9951:   
1.296     brouard  9952:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  9953:   
                   9954:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  9955:   
1.126     brouard  9956: /*           if (h==(int)(YEARM*yearp)){ */
1.351     brouard  9957:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9958:     k=TKresult[nres];
                   9959:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   9960:     /*  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) *\/ */
                   9961:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   9962:     /*   continue; */
                   9963:     /* if(invalidvarcomb[k]){ */
                   9964:     /*   printf("\nCombination (%d) projection ignored because no cases \n",k);  */
                   9965:     /*   continue; */
                   9966:     /* } */
1.227     brouard  9967:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
1.351     brouard  9968:     for(j=1;j<=cptcovs;j++){
                   9969:       /* for(j=1;j<=cptcoveff;j++) { */
                   9970:     /*   /\* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); *\/ */
                   9971:     /*   fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9972:     /* } */
                   9973:     /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9974:     /*   fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   9975:     /* } */
                   9976:       fprintf(ficresf," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.235     brouard  9977:     }
1.351     brouard  9978:  
1.227     brouard  9979:     fprintf(ficresf," yearproj age");
                   9980:     for(j=1; j<=nlstate+ndeath;j++){ 
                   9981:       for(i=1; i<=nlstate;i++)               
                   9982:        fprintf(ficresf," p%d%d",i,j);
                   9983:       fprintf(ficresf," wp.%d",j);
                   9984:     }
1.296     brouard  9985:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  9986:       fprintf(ficresf,"\n");
1.296     brouard  9987:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  9988:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   9989:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  9990:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   9991:        nhstepm = nhstepm/hstepm; 
                   9992:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9993:        oldm=oldms;savm=savms;
1.268     brouard  9994:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  9995:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  9996:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  9997:        for (h=0; h<=nhstepm; h++){
                   9998:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  9999:            break;
                   10000:          }
                   10001:        }
                   10002:        fprintf(ficresf,"\n");
1.351     brouard  10003:        /* for(j=1;j<=cptcoveff;j++)  */
                   10004:        for(j=1;j<=cptcovs;j++) 
                   10005:          fprintf(ficresf,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.332     brouard  10006:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
1.351     brouard  10007:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* TnsdVar[Tvaraff]  correct *\/ */
1.296     brouard  10008:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  10009:        
                   10010:        for(j=1; j<=nlstate+ndeath;j++) {
                   10011:          ppij=0.;
                   10012:          for(i=1; i<=nlstate;i++) {
1.278     brouard  10013:            if (mobilav>=1)
                   10014:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   10015:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   10016:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   10017:            }
1.268     brouard  10018:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   10019:          } /* end i */
                   10020:          fprintf(ficresf," %.3f", ppij);
                   10021:        }/* end j */
1.227     brouard  10022:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10023:       } /* end agec */
1.266     brouard  10024:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   10025:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  10026:     } /* end yearp */
                   10027:   } /* end  k */
1.219     brouard  10028:        
1.126     brouard  10029:   fclose(ficresf);
1.215     brouard  10030:   printf("End of Computing forecasting \n");
                   10031:   fprintf(ficlog,"End of Computing forecasting\n");
                   10032: 
1.126     brouard  10033: }
                   10034: 
1.269     brouard  10035: /************** Back Forecasting ******************/
1.296     brouard  10036:  /* 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){ */
                   10037:  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){
                   10038:   /* back1, year, month, day of starting backprojection
1.267     brouard  10039:      agemin, agemax range of age
                   10040:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  10041:      anback2 year of end of backprojection (same day and month as back1).
                   10042:      prevacurrent and prev are prevalences.
1.267     brouard  10043:   */
                   10044:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   10045:   double agec; /* generic age */
1.302     brouard  10046:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  10047:   double *popeffectif,*popcount;
                   10048:   double ***p3mat;
                   10049:   /* double ***mobaverage; */
                   10050:   char fileresfb[FILENAMELENGTH];
                   10051:  
1.268     brouard  10052:   agelim=AGEINF;
1.267     brouard  10053:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   10054:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   10055:      We still use firstpass and lastpass as another selection.
                   10056:   */
                   10057:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   10058:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   10059: 
                   10060:   /*Do we need to compute prevalence again?*/
                   10061: 
                   10062:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   10063:   
                   10064:   strcpy(fileresfb,"FB_");
                   10065:   strcat(fileresfb,fileresu);
                   10066:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   10067:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   10068:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   10069:   }
                   10070:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   10071:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   10072:   
                   10073:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   10074:   
                   10075:    
                   10076:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10077:   if (stepm<=12) stepsize=1;
                   10078:   if(estepm < stepm){
                   10079:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   10080:   }
1.270     brouard  10081:   else{
                   10082:     hstepm=estepm;   
                   10083:   }
                   10084:   if(estepm >= stepm){ /* Yes every two year */
                   10085:     stepsize=2;
                   10086:   }
1.267     brouard  10087:   
                   10088:   hstepm=hstepm/stepm;
1.296     brouard  10089:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   10090:   /*                              fractional in yp1 *\/ */
                   10091:   /* aintmean=yp; */
                   10092:   /* yp2=modf((yp1*12),&yp); */
                   10093:   /* mintmean=yp; */
                   10094:   /* yp1=modf((yp2*30.5),&yp); */
                   10095:   /* jintmean=yp; */
                   10096:   /* if(jintmean==0) jintmean=1; */
                   10097:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  10098:   
1.351     brouard  10099:   /* i1=pow(2,cptcoveff); */
                   10100:   /* if (cptcovn < 1){i1=1;} */
1.267     brouard  10101:   
1.296     brouard  10102:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   10103:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  10104:   
                   10105:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   10106:   
1.351     brouard  10107:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10108:     k=TKresult[nres];
                   10109:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   10110:   /* for(k=1; k<=i1;k++){ */
                   10111:   /*   if(i1 != 1 && TKresult[nres]!= k) */
                   10112:   /*     continue; */
                   10113:   /*   if(invalidvarcomb[k]){ */
                   10114:   /*     printf("\nCombination (%d) projection ignored because no cases \n",k);  */
                   10115:   /*     continue; */
                   10116:   /*   } */
1.268     brouard  10117:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.351     brouard  10118:     for(j=1;j<=cptcovs;j++){
                   10119:     /* for(j=1;j<=cptcoveff;j++) { */
                   10120:     /*   fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10121:     /* } */
                   10122:       fprintf(ficresfb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.267     brouard  10123:     }
1.351     brouard  10124:    /*  fprintf(ficrespij,"******\n"); */
                   10125:    /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10126:    /*    fprintf(ficresfb," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10127:    /*  } */
1.267     brouard  10128:     fprintf(ficresfb," yearbproj age");
                   10129:     for(j=1; j<=nlstate+ndeath;j++){
                   10130:       for(i=1; i<=nlstate;i++)
1.268     brouard  10131:        fprintf(ficresfb," b%d%d",i,j);
                   10132:       fprintf(ficresfb," b.%d",j);
1.267     brouard  10133:     }
1.296     brouard  10134:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  10135:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   10136:       fprintf(ficresfb,"\n");
1.296     brouard  10137:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  10138:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  10139:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   10140:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  10141:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  10142:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  10143:        nhstepm = nhstepm/hstepm;
                   10144:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10145:        oldm=oldms;savm=savms;
1.268     brouard  10146:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  10147:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  10148:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  10149:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   10150:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   10151:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  10152:        for (h=0; h<=nhstepm; h++){
1.268     brouard  10153:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   10154:            break;
                   10155:          }
                   10156:        }
                   10157:        fprintf(ficresfb,"\n");
1.351     brouard  10158:        /* for(j=1;j<=cptcoveff;j++) */
                   10159:        for(j=1;j<=cptcovs;j++)
                   10160:          fprintf(ficresfb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10161:          /* fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.296     brouard  10162:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  10163:        for(i=1; i<=nlstate+ndeath;i++) {
                   10164:          ppij=0.;ppi=0.;
                   10165:          for(j=1; j<=nlstate;j++) {
                   10166:            /* if (mobilav==1) */
1.269     brouard  10167:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   10168:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   10169:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   10170:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  10171:              /* else { */
                   10172:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   10173:              /* } */
1.268     brouard  10174:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   10175:          } /* end j */
                   10176:          if(ppi <0.99){
                   10177:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   10178:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   10179:          }
                   10180:          fprintf(ficresfb," %.3f", ppij);
                   10181:        }/* end j */
1.267     brouard  10182:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10183:       } /* end agec */
                   10184:     } /* end yearp */
                   10185:   } /* end k */
1.217     brouard  10186:   
1.267     brouard  10187:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  10188:   
1.267     brouard  10189:   fclose(ficresfb);
                   10190:   printf("End of Computing Back forecasting \n");
                   10191:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  10192:        
1.267     brouard  10193: }
1.217     brouard  10194: 
1.269     brouard  10195: /* Variance of prevalence limit: varprlim */
                   10196:  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  10197:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  10198:  
                   10199:    char fileresvpl[FILENAMELENGTH];  
                   10200:    FILE *ficresvpl;
                   10201:    double **oldm, **savm;
                   10202:    double **varpl; /* Variances of prevalence limits by age */   
                   10203:    int i1, k, nres, j ;
                   10204:    
                   10205:     strcpy(fileresvpl,"VPL_");
                   10206:     strcat(fileresvpl,fileresu);
                   10207:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  10208:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  10209:       exit(0);
                   10210:     }
1.288     brouard  10211:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   10212:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  10213:     
                   10214:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   10215:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   10216:     
                   10217:     i1=pow(2,cptcoveff);
                   10218:     if (cptcovn < 1){i1=1;}
                   10219: 
1.337     brouard  10220:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10221:        k=TKresult[nres];
1.338     brouard  10222:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  10223:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
1.269     brouard  10224:       if(i1 != 1 && TKresult[nres]!= k)
                   10225:        continue;
                   10226:       fprintf(ficresvpl,"\n#****** ");
                   10227:       printf("\n#****** ");
                   10228:       fprintf(ficlog,"\n#****** ");
1.337     brouard  10229:       for(j=1;j<=cptcovs;j++) {
                   10230:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10231:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10232:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10233:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10234:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.269     brouard  10235:       }
1.337     brouard  10236:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   10237:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10238:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10239:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10240:       /* }      */
1.269     brouard  10241:       fprintf(ficresvpl,"******\n");
                   10242:       printf("******\n");
                   10243:       fprintf(ficlog,"******\n");
                   10244:       
                   10245:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10246:       oldm=oldms;savm=savms;
                   10247:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   10248:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   10249:       /*}*/
                   10250:     }
                   10251:     
                   10252:     fclose(ficresvpl);
1.288     brouard  10253:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   10254:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  10255: 
                   10256:  }
                   10257: /* Variance of back prevalence: varbprlim */
                   10258:  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){
                   10259:       /*------- Variance of back (stable) prevalence------*/
                   10260: 
                   10261:    char fileresvbl[FILENAMELENGTH];  
                   10262:    FILE  *ficresvbl;
                   10263: 
                   10264:    double **oldm, **savm;
                   10265:    double **varbpl; /* Variances of back prevalence limits by age */   
                   10266:    int i1, k, nres, j ;
                   10267: 
                   10268:    strcpy(fileresvbl,"VBL_");
                   10269:    strcat(fileresvbl,fileresu);
                   10270:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   10271:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   10272:      exit(0);
                   10273:    }
                   10274:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   10275:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   10276:    
                   10277:    
                   10278:    i1=pow(2,cptcoveff);
                   10279:    if (cptcovn < 1){i1=1;}
                   10280:    
1.337     brouard  10281:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10282:      k=TKresult[nres];
1.338     brouard  10283:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  10284:     /* for(k=1; k<=i1;k++){ */
                   10285:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   10286:     /*          continue; */
1.269     brouard  10287:        fprintf(ficresvbl,"\n#****** ");
                   10288:        printf("\n#****** ");
                   10289:        fprintf(ficlog,"\n#****** ");
1.337     brouard  10290:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
1.338     brouard  10291:         printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10292:         fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10293:         fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
1.337     brouard  10294:        /* for(j=1;j<=cptcoveff;j++) { */
                   10295:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10296:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10297:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10298:        /* } */
                   10299:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   10300:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10301:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10302:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
1.269     brouard  10303:        }
                   10304:        fprintf(ficresvbl,"******\n");
                   10305:        printf("******\n");
                   10306:        fprintf(ficlog,"******\n");
                   10307:        
                   10308:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10309:        oldm=oldms;savm=savms;
                   10310:        
                   10311:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   10312:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   10313:        /*}*/
                   10314:      }
                   10315:    
                   10316:    fclose(ficresvbl);
                   10317:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   10318:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   10319: 
                   10320:  } /* End of varbprlim */
                   10321: 
1.126     brouard  10322: /************** Forecasting *****not tested NB*************/
1.227     brouard  10323: /* 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  10324:   
1.227     brouard  10325: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   10326: /*   int *popage; */
                   10327: /*   double calagedatem, agelim, kk1, kk2; */
                   10328: /*   double *popeffectif,*popcount; */
                   10329: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   10330: /*   /\* double ***mobaverage; *\/ */
                   10331: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  10332: 
1.227     brouard  10333: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10334: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10335: /*   agelim=AGESUP; */
                   10336: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  10337:   
1.227     brouard  10338: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  10339:   
                   10340:   
1.227     brouard  10341: /*   strcpy(filerespop,"POP_");  */
                   10342: /*   strcat(filerespop,fileresu); */
                   10343: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   10344: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   10345: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   10346: /*   } */
                   10347: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   10348: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  10349: 
1.227     brouard  10350: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  10351: 
1.227     brouard  10352: /*   /\* if (mobilav!=0) { *\/ */
                   10353: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   10354: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   10355: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10356: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10357: /*   /\*   } *\/ */
                   10358: /*   /\* } *\/ */
1.126     brouard  10359: 
1.227     brouard  10360: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   10361: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  10362:   
1.227     brouard  10363: /*   agelim=AGESUP; */
1.126     brouard  10364:   
1.227     brouard  10365: /*   hstepm=1; */
                   10366: /*   hstepm=hstepm/stepm;  */
1.218     brouard  10367:        
1.227     brouard  10368: /*   if (popforecast==1) { */
                   10369: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   10370: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   10371: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   10372: /*     }  */
                   10373: /*     popage=ivector(0,AGESUP); */
                   10374: /*     popeffectif=vector(0,AGESUP); */
                   10375: /*     popcount=vector(0,AGESUP); */
1.126     brouard  10376:     
1.227     brouard  10377: /*     i=1;    */
                   10378: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  10379:     
1.227     brouard  10380: /*     imx=i; */
                   10381: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   10382: /*   } */
1.218     brouard  10383:   
1.227     brouard  10384: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   10385: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   10386: /*       k=k+1; */
                   10387: /*       fprintf(ficrespop,"\n#******"); */
                   10388: /*       for(j=1;j<=cptcoveff;j++) { */
                   10389: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   10390: /*       } */
                   10391: /*       fprintf(ficrespop,"******\n"); */
                   10392: /*       fprintf(ficrespop,"# Age"); */
                   10393: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   10394: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  10395:       
1.227     brouard  10396: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   10397: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  10398:        
1.227     brouard  10399: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10400: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10401: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10402:          
1.227     brouard  10403: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10404: /*       oldm=oldms;savm=savms; */
                   10405: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  10406:          
1.227     brouard  10407: /*       for (h=0; h<=nhstepm; h++){ */
                   10408: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10409: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10410: /*         }  */
                   10411: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10412: /*           kk1=0.;kk2=0; */
                   10413: /*           for(i=1; i<=nlstate;i++) {               */
                   10414: /*             if (mobilav==1)  */
                   10415: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   10416: /*             else { */
                   10417: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   10418: /*             } */
                   10419: /*           } */
                   10420: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   10421: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   10422: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   10423: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   10424: /*           } */
                   10425: /*         } */
                   10426: /*         for(i=1; i<=nlstate;i++){ */
                   10427: /*           kk1=0.; */
                   10428: /*           for(j=1; j<=nlstate;j++){ */
                   10429: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   10430: /*           } */
                   10431: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   10432: /*         } */
1.218     brouard  10433:            
1.227     brouard  10434: /*         if (h==(int)(calagedatem+12*cpt)) */
                   10435: /*           for(j=1; j<=nlstate;j++)  */
                   10436: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   10437: /*       } */
                   10438: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10439: /*     } */
                   10440: /*       } */
1.218     brouard  10441:       
1.227     brouard  10442: /*       /\******\/ */
1.218     brouard  10443:       
1.227     brouard  10444: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   10445: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   10446: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10447: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10448: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10449:          
1.227     brouard  10450: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10451: /*       oldm=oldms;savm=savms; */
                   10452: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   10453: /*       for (h=0; h<=nhstepm; h++){ */
                   10454: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10455: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10456: /*         }  */
                   10457: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10458: /*           kk1=0.;kk2=0; */
                   10459: /*           for(i=1; i<=nlstate;i++) {               */
                   10460: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   10461: /*           } */
                   10462: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   10463: /*         } */
                   10464: /*       } */
                   10465: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10466: /*     } */
                   10467: /*       } */
                   10468: /*     }  */
                   10469: /*   } */
1.218     brouard  10470:   
1.227     brouard  10471: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  10472:   
1.227     brouard  10473: /*   if (popforecast==1) { */
                   10474: /*     free_ivector(popage,0,AGESUP); */
                   10475: /*     free_vector(popeffectif,0,AGESUP); */
                   10476: /*     free_vector(popcount,0,AGESUP); */
                   10477: /*   } */
                   10478: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10479: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10480: /*   fclose(ficrespop); */
                   10481: /* } /\* End of popforecast *\/ */
1.218     brouard  10482:  
1.126     brouard  10483: int fileappend(FILE *fichier, char *optionfich)
                   10484: {
                   10485:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   10486:     printf("Problem with file: %s\n", optionfich);
                   10487:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   10488:     return (0);
                   10489:   }
                   10490:   fflush(fichier);
                   10491:   return (1);
                   10492: }
                   10493: 
                   10494: 
                   10495: /**************** function prwizard **********************/
                   10496: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   10497: {
                   10498: 
                   10499:   /* Wizard to print covariance matrix template */
                   10500: 
1.164     brouard  10501:   char ca[32], cb[32];
                   10502:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  10503:   int numlinepar;
                   10504: 
                   10505:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10506:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10507:   for(i=1; i <=nlstate; i++){
                   10508:     jj=0;
                   10509:     for(j=1; j <=nlstate+ndeath; j++){
                   10510:       if(j==i) continue;
                   10511:       jj++;
                   10512:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   10513:       printf("%1d%1d",i,j);
                   10514:       fprintf(ficparo,"%1d%1d",i,j);
                   10515:       for(k=1; k<=ncovmodel;k++){
                   10516:        /*        printf(" %lf",param[i][j][k]); */
                   10517:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   10518:        printf(" 0.");
                   10519:        fprintf(ficparo," 0.");
                   10520:       }
                   10521:       printf("\n");
                   10522:       fprintf(ficparo,"\n");
                   10523:     }
                   10524:   }
                   10525:   printf("# Scales (for hessian or gradient estimation)\n");
                   10526:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   10527:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   10528:   for(i=1; i <=nlstate; i++){
                   10529:     jj=0;
                   10530:     for(j=1; j <=nlstate+ndeath; j++){
                   10531:       if(j==i) continue;
                   10532:       jj++;
                   10533:       fprintf(ficparo,"%1d%1d",i,j);
                   10534:       printf("%1d%1d",i,j);
                   10535:       fflush(stdout);
                   10536:       for(k=1; k<=ncovmodel;k++){
                   10537:        /*      printf(" %le",delti3[i][j][k]); */
                   10538:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   10539:        printf(" 0.");
                   10540:        fprintf(ficparo," 0.");
                   10541:       }
                   10542:       numlinepar++;
                   10543:       printf("\n");
                   10544:       fprintf(ficparo,"\n");
                   10545:     }
                   10546:   }
                   10547:   printf("# Covariance matrix\n");
                   10548: /* # 121 Var(a12)\n\ */
                   10549: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10550: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10551: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10552: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10553: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10554: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10555: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10556:   fflush(stdout);
                   10557:   fprintf(ficparo,"# Covariance matrix\n");
                   10558:   /* # 121 Var(a12)\n\ */
                   10559:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10560:   /* #   ...\n\ */
                   10561:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   10562:   
                   10563:   for(itimes=1;itimes<=2;itimes++){
                   10564:     jj=0;
                   10565:     for(i=1; i <=nlstate; i++){
                   10566:       for(j=1; j <=nlstate+ndeath; j++){
                   10567:        if(j==i) continue;
                   10568:        for(k=1; k<=ncovmodel;k++){
                   10569:          jj++;
                   10570:          ca[0]= k+'a'-1;ca[1]='\0';
                   10571:          if(itimes==1){
                   10572:            printf("#%1d%1d%d",i,j,k);
                   10573:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   10574:          }else{
                   10575:            printf("%1d%1d%d",i,j,k);
                   10576:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   10577:            /*  printf(" %.5le",matcov[i][j]); */
                   10578:          }
                   10579:          ll=0;
                   10580:          for(li=1;li <=nlstate; li++){
                   10581:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   10582:              if(lj==li) continue;
                   10583:              for(lk=1;lk<=ncovmodel;lk++){
                   10584:                ll++;
                   10585:                if(ll<=jj){
                   10586:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   10587:                  if(ll<jj){
                   10588:                    if(itimes==1){
                   10589:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10590:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10591:                    }else{
                   10592:                      printf(" 0.");
                   10593:                      fprintf(ficparo," 0.");
                   10594:                    }
                   10595:                  }else{
                   10596:                    if(itimes==1){
                   10597:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   10598:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   10599:                    }else{
                   10600:                      printf(" 0.");
                   10601:                      fprintf(ficparo," 0.");
                   10602:                    }
                   10603:                  }
                   10604:                }
                   10605:              } /* end lk */
                   10606:            } /* end lj */
                   10607:          } /* end li */
                   10608:          printf("\n");
                   10609:          fprintf(ficparo,"\n");
                   10610:          numlinepar++;
                   10611:        } /* end k*/
                   10612:       } /*end j */
                   10613:     } /* end i */
                   10614:   } /* end itimes */
                   10615: 
                   10616: } /* end of prwizard */
                   10617: /******************* Gompertz Likelihood ******************************/
                   10618: double gompertz(double x[])
                   10619: { 
1.302     brouard  10620:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  10621:   int i,n=0; /* n is the size of the sample */
                   10622: 
1.220     brouard  10623:   for (i=1;i<=imx ; i++) {
1.126     brouard  10624:     sump=sump+weight[i];
                   10625:     /*    sump=sump+1;*/
                   10626:     num=num+1;
                   10627:   }
1.302     brouard  10628:   L=0.0;
                   10629:   /* agegomp=AGEGOMP; */
1.126     brouard  10630:   /* for (i=0; i<=imx; i++) 
                   10631:      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]);*/
                   10632: 
1.302     brouard  10633:   for (i=1;i<=imx ; i++) {
                   10634:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   10635:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   10636:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   10637:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   10638:      * +
                   10639:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   10640:      */
                   10641:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   10642:        if (cens[i] == 1){
                   10643:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   10644:        } else if (cens[i] == 0){
1.126     brouard  10645:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  10646:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   10647:       } else
                   10648:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  10649:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  10650:        L=L+A*weight[i];
1.126     brouard  10651:        /*      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  10652:      }
                   10653:   }
1.126     brouard  10654: 
1.302     brouard  10655:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  10656:  
                   10657:   return -2*L*num/sump;
                   10658: }
                   10659: 
1.136     brouard  10660: #ifdef GSL
                   10661: /******************* Gompertz_f Likelihood ******************************/
                   10662: double gompertz_f(const gsl_vector *v, void *params)
                   10663: { 
1.302     brouard  10664:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  10665:   double *x= (double *) v->data;
                   10666:   int i,n=0; /* n is the size of the sample */
                   10667: 
                   10668:   for (i=0;i<=imx-1 ; i++) {
                   10669:     sump=sump+weight[i];
                   10670:     /*    sump=sump+1;*/
                   10671:     num=num+1;
                   10672:   }
                   10673:  
                   10674:  
                   10675:   /* for (i=0; i<=imx; i++) 
                   10676:      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]);*/
                   10677:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   10678:   for (i=1;i<=imx ; i++)
                   10679:     {
                   10680:       if (cens[i] == 1 && wav[i]>1)
                   10681:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   10682:       
                   10683:       if (cens[i] == 0 && wav[i]>1)
                   10684:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   10685:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   10686:       
                   10687:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   10688:       if (wav[i] > 1 ) { /* ??? */
                   10689:        LL=LL+A*weight[i];
                   10690:        /*      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]);*/
                   10691:       }
                   10692:     }
                   10693: 
                   10694:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   10695:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   10696:  
                   10697:   return -2*LL*num/sump;
                   10698: }
                   10699: #endif
                   10700: 
1.126     brouard  10701: /******************* Printing html file ***********/
1.201     brouard  10702: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  10703:                  int lastpass, int stepm, int weightopt, char model[],\
                   10704:                  int imx,  double p[],double **matcov,double agemortsup){
                   10705:   int i,k;
                   10706: 
                   10707:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   10708:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   10709:   for (i=1;i<=2;i++) 
                   10710:     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  10711:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  10712:   fprintf(fichtm,"</ul>");
                   10713: 
                   10714: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   10715: 
                   10716:  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>");
                   10717: 
                   10718:  for (k=agegomp;k<(agemortsup-2);k++) 
                   10719:    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]);
                   10720: 
                   10721:  
                   10722:   fflush(fichtm);
                   10723: }
                   10724: 
                   10725: /******************* Gnuplot file **************/
1.201     brouard  10726: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  10727: 
                   10728:   char dirfileres[132],optfileres[132];
1.164     brouard  10729: 
1.126     brouard  10730:   int ng;
                   10731: 
                   10732: 
                   10733:   /*#ifdef windows */
                   10734:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   10735:     /*#endif */
                   10736: 
                   10737: 
                   10738:   strcpy(dirfileres,optionfilefiname);
                   10739:   strcpy(optfileres,"vpl");
1.199     brouard  10740:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  10741:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  10742:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  10743:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  10744:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   10745: 
                   10746: } 
                   10747: 
1.136     brouard  10748: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   10749: {
1.126     brouard  10750: 
1.136     brouard  10751:   /*-------- data file ----------*/
                   10752:   FILE *fic;
                   10753:   char dummy[]="                         ";
1.240     brouard  10754:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  10755:   int lstra;
1.136     brouard  10756:   int linei, month, year,iout;
1.302     brouard  10757:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  10758:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  10759:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  10760:   char *stratrunc;
1.223     brouard  10761: 
1.349     brouard  10762:   /* DummyV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
                   10763:   /* FixedV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
1.339     brouard  10764:   
                   10765:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
                   10766:   
1.136     brouard  10767:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  10768:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10769:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  10770:   }
1.126     brouard  10771: 
1.302     brouard  10772:     /* Is it a BOM UTF-8 Windows file? */
                   10773:   /* First data line */
                   10774:   linei=0;
                   10775:   while(fgets(line, MAXLINE, fic)) {
                   10776:     noffset=0;
                   10777:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   10778:     {
                   10779:       noffset=noffset+3;
                   10780:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   10781:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   10782:       fflush(ficlog); return 1;
                   10783:     }
                   10784:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   10785:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   10786:     {
                   10787:       noffset=noffset+2;
1.304     brouard  10788:       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);
                   10789:       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  10790:       fflush(ficlog); return 1;
                   10791:     }
                   10792:     else if( line[0] == 0 && line[1] == 0)
                   10793:     {
                   10794:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   10795:        noffset=noffset+4;
1.304     brouard  10796:        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);
                   10797:        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  10798:        fflush(ficlog); return 1;
                   10799:       }
                   10800:     } else{
                   10801:       ;/*printf(" Not a BOM file\n");*/
                   10802:     }
                   10803:         /* If line starts with a # it is a comment */
                   10804:     if (line[noffset] == '#') {
                   10805:       linei=linei+1;
                   10806:       break;
                   10807:     }else{
                   10808:       break;
                   10809:     }
                   10810:   }
                   10811:   fclose(fic);
                   10812:   if((fic=fopen(datafile,"r"))==NULL)    {
                   10813:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10814:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   10815:   }
                   10816:   /* Not a Bom file */
                   10817:   
1.136     brouard  10818:   i=1;
                   10819:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   10820:     linei=linei+1;
                   10821:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   10822:       if(line[j] == '\t')
                   10823:        line[j] = ' ';
                   10824:     }
                   10825:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   10826:       ;
                   10827:     };
                   10828:     line[j+1]=0;  /* Trims blanks at end of line */
                   10829:     if(line[0]=='#'){
                   10830:       fprintf(ficlog,"Comment line\n%s\n",line);
                   10831:       printf("Comment line\n%s\n",line);
                   10832:       continue;
                   10833:     }
                   10834:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  10835:     strcpy(line, linetmp);
1.223     brouard  10836:     
                   10837:     /* Loops on waves */
                   10838:     for (j=maxwav;j>=1;j--){
                   10839:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  10840:        cutv(stra, strb, line, ' '); 
                   10841:        if(strb[0]=='.') { /* Missing value */
                   10842:          lval=-1;
                   10843:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
1.341     brouard  10844:          cotvar[j][ncovcol+nqv+ntv+iv][i]=-1; /* For performance reasons */
1.238     brouard  10845:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   10846:            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);
                   10847:            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);
                   10848:            return 1;
                   10849:          }
                   10850:        }else{
                   10851:          errno=0;
                   10852:          /* what_kind_of_number(strb); */
                   10853:          dval=strtod(strb,&endptr); 
                   10854:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   10855:          /* if(strb != endptr && *endptr == '\0') */
                   10856:          /*    dval=dlval; */
                   10857:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10858:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10859:            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);
                   10860:            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);
                   10861:            return 1;
                   10862:          }
                   10863:          cotqvar[j][iv][i]=dval; 
1.341     brouard  10864:          cotvar[j][ncovcol+nqv+ntv+iv][i]=dval; /* because cotvar starts now at first ntv */ 
1.238     brouard  10865:        }
                   10866:        strcpy(line,stra);
1.223     brouard  10867:       }/* end loop ntqv */
1.225     brouard  10868:       
1.223     brouard  10869:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  10870:        cutv(stra, strb, line, ' '); 
                   10871:        if(strb[0]=='.') { /* Missing value */
                   10872:          lval=-1;
                   10873:        }else{
                   10874:          errno=0;
                   10875:          lval=strtol(strb,&endptr,10); 
                   10876:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10877:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10878:            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);
                   10879:            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);
                   10880:            return 1;
                   10881:          }
                   10882:        }
                   10883:        if(lval <-1 || lval >1){
                   10884:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10885:  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  10886:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10887:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10888:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10889:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10890:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10891:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10892:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  10893:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10894:  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  10895:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10896:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10897:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10898:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10899:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10900:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10901:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  10902:          return 1;
                   10903:        }
1.341     brouard  10904:        cotvar[j][ncovcol+nqv+iv][i]=(double)(lval);
1.238     brouard  10905:        strcpy(line,stra);
1.223     brouard  10906:       }/* end loop ntv */
1.225     brouard  10907:       
1.223     brouard  10908:       /* Statuses  at wave */
1.137     brouard  10909:       cutv(stra, strb, line, ' '); 
1.223     brouard  10910:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  10911:        lval=-1;
1.136     brouard  10912:       }else{
1.238     brouard  10913:        errno=0;
                   10914:        lval=strtol(strb,&endptr,10); 
                   10915:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
1.347     brouard  10916:        if( strb[0]=='\0' || (*endptr != '\0' )){
                   10917:          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);
                   10918:          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);
                   10919:          return 1;
                   10920:        }else if( lval==0 || lval > nlstate+ndeath){
1.348     brouard  10921:          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);
                   10922:          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  10923:          return 1;
                   10924:        }
1.136     brouard  10925:       }
1.225     brouard  10926:       
1.136     brouard  10927:       s[j][i]=lval;
1.225     brouard  10928:       
1.223     brouard  10929:       /* Date of Interview */
1.136     brouard  10930:       strcpy(line,stra);
                   10931:       cutv(stra, strb,line,' ');
1.169     brouard  10932:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10933:       }
1.169     brouard  10934:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  10935:        month=99;
                   10936:        year=9999;
1.136     brouard  10937:       }else{
1.225     brouard  10938:        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);
                   10939:        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);
                   10940:        return 1;
1.136     brouard  10941:       }
                   10942:       anint[j][i]= (double) year; 
1.302     brouard  10943:       mint[j][i]= (double)month;
                   10944:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   10945:       /*       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]); */
                   10946:       /*       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]); */
                   10947:       /* } */
1.136     brouard  10948:       strcpy(line,stra);
1.223     brouard  10949:     } /* End loop on waves */
1.225     brouard  10950:     
1.223     brouard  10951:     /* Date of death */
1.136     brouard  10952:     cutv(stra, strb,line,' '); 
1.169     brouard  10953:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10954:     }
1.169     brouard  10955:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  10956:       month=99;
                   10957:       year=9999;
                   10958:     }else{
1.141     brouard  10959:       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  10960:       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);
                   10961:       return 1;
1.136     brouard  10962:     }
                   10963:     andc[i]=(double) year; 
                   10964:     moisdc[i]=(double) month; 
                   10965:     strcpy(line,stra);
                   10966:     
1.223     brouard  10967:     /* Date of birth */
1.136     brouard  10968:     cutv(stra, strb,line,' '); 
1.169     brouard  10969:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10970:     }
1.169     brouard  10971:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  10972:       month=99;
                   10973:       year=9999;
                   10974:     }else{
1.141     brouard  10975:       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);
                   10976:       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  10977:       return 1;
1.136     brouard  10978:     }
                   10979:     if (year==9999) {
1.141     brouard  10980:       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);
                   10981:       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  10982:       return 1;
                   10983:       
1.136     brouard  10984:     }
                   10985:     annais[i]=(double)(year);
1.302     brouard  10986:     moisnais[i]=(double)(month);
                   10987:     for (j=1;j<=maxwav;j++){
                   10988:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   10989:        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]);
                   10990:        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]);
                   10991:       }
                   10992:     }
                   10993: 
1.136     brouard  10994:     strcpy(line,stra);
1.225     brouard  10995:     
1.223     brouard  10996:     /* Sample weight */
1.136     brouard  10997:     cutv(stra, strb,line,' '); 
                   10998:     errno=0;
                   10999:     dval=strtod(strb,&endptr); 
                   11000:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  11001:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   11002:       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  11003:       fflush(ficlog);
                   11004:       return 1;
                   11005:     }
                   11006:     weight[i]=dval; 
                   11007:     strcpy(line,stra);
1.225     brouard  11008:     
1.223     brouard  11009:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   11010:       cutv(stra, strb, line, ' '); 
                   11011:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  11012:        lval=-1;
1.311     brouard  11013:        coqvar[iv][i]=NAN; 
                   11014:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  11015:       }else{
1.225     brouard  11016:        errno=0;
                   11017:        /* what_kind_of_number(strb); */
                   11018:        dval=strtod(strb,&endptr);
                   11019:        /* if(strb != endptr && *endptr == '\0') */
                   11020:        /*   dval=dlval; */
                   11021:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   11022:        if( strb[0]=='\0' || (*endptr != '\0')){
                   11023:          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);
                   11024:          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);
                   11025:          return 1;
                   11026:        }
                   11027:        coqvar[iv][i]=dval; 
1.226     brouard  11028:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  11029:       }
                   11030:       strcpy(line,stra);
                   11031:     }/* end loop nqv */
1.136     brouard  11032:     
1.223     brouard  11033:     /* Covariate values */
1.136     brouard  11034:     for (j=ncovcol;j>=1;j--){
                   11035:       cutv(stra, strb,line,' '); 
1.223     brouard  11036:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  11037:        lval=-1;
1.136     brouard  11038:       }else{
1.225     brouard  11039:        errno=0;
                   11040:        lval=strtol(strb,&endptr,10); 
                   11041:        if( strb[0]=='\0' || (*endptr != '\0')){
                   11042:          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);
                   11043:          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);
                   11044:          return 1;
                   11045:        }
1.136     brouard  11046:       }
                   11047:       if(lval <-1 || lval >1){
1.225     brouard  11048:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  11049:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   11050:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  11051:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   11052:  build V1=0 V2=0 for the reference value (1),\n                                \
                   11053:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  11054:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  11055:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  11056:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  11057:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  11058:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   11059:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  11060:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   11061:  build V1=0 V2=0 for the reference value (1),\n                                \
                   11062:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  11063:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  11064:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  11065:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  11066:        return 1;
1.136     brouard  11067:       }
                   11068:       covar[j][i]=(double)(lval);
                   11069:       strcpy(line,stra);
                   11070:     }  
                   11071:     lstra=strlen(stra);
1.225     brouard  11072:     
1.136     brouard  11073:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   11074:       stratrunc = &(stra[lstra-9]);
                   11075:       num[i]=atol(stratrunc);
                   11076:     }
                   11077:     else
                   11078:       num[i]=atol(stra);
                   11079:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   11080:       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;}*/
                   11081:     
                   11082:     i=i+1;
                   11083:   } /* End loop reading  data */
1.225     brouard  11084:   
1.136     brouard  11085:   *imax=i-1; /* Number of individuals */
                   11086:   fclose(fic);
1.225     brouard  11087:   
1.136     brouard  11088:   return (0);
1.164     brouard  11089:   /* endread: */
1.225     brouard  11090:   printf("Exiting readdata: ");
                   11091:   fclose(fic);
                   11092:   return (1);
1.223     brouard  11093: }
1.126     brouard  11094: 
1.234     brouard  11095: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  11096:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  11097:   while (*p2 == ' ')
1.234     brouard  11098:     p2++; 
                   11099:   /* while ((*p1++ = *p2++) !=0) */
                   11100:   /*   ; */
                   11101:   /* do */
                   11102:   /*   while (*p2 == ' ') */
                   11103:   /*     p2++; */
                   11104:   /* while (*p1++ == *p2++); */
                   11105:   *stri=p2; 
1.145     brouard  11106: }
                   11107: 
1.330     brouard  11108: int decoderesult( char resultline[], int nres)
1.230     brouard  11109: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   11110: {
1.235     brouard  11111:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  11112:   char resultsav[MAXLINE];
1.330     brouard  11113:   /* int resultmodel[MAXLINE]; */
1.334     brouard  11114:   /* int modelresult[MAXLINE]; */
1.230     brouard  11115:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   11116: 
1.234     brouard  11117:   removefirstspace(&resultline);
1.332     brouard  11118:   printf("decoderesult:%s\n",resultline);
1.230     brouard  11119: 
1.332     brouard  11120:   strcpy(resultsav,resultline);
1.342     brouard  11121:   /* printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline); */
1.230     brouard  11122:   if (strlen(resultsav) >1){
1.334     brouard  11123:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  11124:   }
1.353   ! brouard  11125:   if(j == 0 && cptcovs== 0){ /* Resultline but no =  and no covariate in the model */
1.253     brouard  11126:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   11127:     return (0);
                   11128:   }
1.234     brouard  11129:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.353   ! brouard  11130:     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);
        !          11131:     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);
        !          11132:     if(j==0)
        !          11133:       return 1;
1.234     brouard  11134:   }
1.334     brouard  11135:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  11136:     if(nbocc(resultsav,'=') >1){
1.318     brouard  11137:       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  11138:       /* 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  11139:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  11140:       /* If a blank, then strc="V4=" and strd='\0' */
                   11141:       if(strc[0]=='\0'){
                   11142:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   11143:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   11144:        return 1;
                   11145:       }
1.234     brouard  11146:     }else
                   11147:       cutl(strc,strd,resultsav,'=');
1.318     brouard  11148:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  11149:     
1.230     brouard  11150:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  11151:     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  11152:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   11153:     /* cptcovsel++;     */
                   11154:     if (nbocc(stra,'=') >0)
                   11155:       strcpy(resultsav,stra); /* and analyzes it */
                   11156:   }
1.235     brouard  11157:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  11158:   /* 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  11159:   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  11160:     if(Typevar[k1]==0){ /* Single covariate in model */
                   11161:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  11162:       match=0;
1.318     brouard  11163:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11164:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  11165:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  11166:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  11167:          break;
                   11168:        }
                   11169:       }
                   11170:       if(match == 0){
1.338     brouard  11171:        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]);
                   11172:        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  11173:        return 1;
1.234     brouard  11174:       }
1.332     brouard  11175:     }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*/
                   11176:       /* We feed resultmodel[k1]=k2; */
                   11177:       match=0;
                   11178:       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 */
                   11179:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  11180:          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  11181:          resultmodel[nres][k1]=k2; /* Added here */
1.342     brouard  11182:          /* printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]); */
1.332     brouard  11183:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11184:          break;
                   11185:        }
                   11186:       }
                   11187:       if(match == 0){
1.338     brouard  11188:        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]);
                   11189:        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  11190:       return 1;
                   11191:       }
1.349     brouard  11192:     }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  11193:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   11194:       match=0;
1.342     brouard  11195:       /* 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  11196:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11197:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   11198:          /* modelresult[k2]=k1; */
1.342     brouard  11199:          /* printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]); */
1.332     brouard  11200:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11201:        }
                   11202:       }
                   11203:       if(match == 0){
1.349     brouard  11204:        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);
                   11205:        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  11206:        return 1;
                   11207:       }
                   11208:       match=0;
                   11209:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11210:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   11211:          /* modelresult[k2]=k1;*/
1.342     brouard  11212:          /* printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]); */
1.332     brouard  11213:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11214:          break;
                   11215:        }
                   11216:       }
                   11217:       if(match == 0){
1.349     brouard  11218:        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);
                   11219:        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  11220:        return 1;
                   11221:       }
                   11222:     }/* End of testing */
1.333     brouard  11223:   }/* End loop cptcovt */
1.235     brouard  11224:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  11225:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  11226:   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)
                   11227:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  11228:     match=0;
1.318     brouard  11229:     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  11230:       if(Typevar[k1]==0){ /* Single only */
1.349     brouard  11231:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4  What if a product?  */
1.330     brouard  11232:          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  11233:          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  11234:          ++match;
                   11235:        }
                   11236:       }
                   11237:     }
                   11238:     if(match == 0){
1.338     brouard  11239:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   11240:       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  11241:       return 1;
1.234     brouard  11242:     }else if(match > 1){
1.338     brouard  11243:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   11244:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
1.310     brouard  11245:       return 1;
1.234     brouard  11246:     }
                   11247:   }
1.334     brouard  11248:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  11249:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  11250:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  11251:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   11252:   /* 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*/
                   11253:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  11254:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   11255:   /*    1 0 0 0 */
                   11256:   /*    2 1 0 0 */
                   11257:   /*    3 0 1 0 */ 
1.330     brouard  11258:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  11259:   /*    5 0 0 1 */
1.330     brouard  11260:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  11261:   /*    7 0 1 1 */
                   11262:   /*    8 1 1 1 */
1.237     brouard  11263:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   11264:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   11265:   /* V5*age V5 known which value for nres?  */
                   11266:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  11267:   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.
                   11268:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  11269:     /* k counting number of combination of single dummies in the equation model */
                   11270:     /* k4 counting single dummies in the equation model */
                   11271:     /* k4q counting single quantitatives in the equation model */
1.344     brouard  11272:     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  11273:        /* 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  11274:       /* 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  11275:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  11276:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   11277:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   11278:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   11279:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   11280:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  11281:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  11282:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  11283:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  11284:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   11285:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   11286:       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  11287:       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  11288:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  11289:       /* Tinvresult[nres][4]=1 */
1.334     brouard  11290:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   11291:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   11292:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11293:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  11294:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  11295:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.342     brouard  11296:       /* 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  11297:       k4++;;
1.331     brouard  11298:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  11299:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  11300:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  11301:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  11302:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   11303:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   11304:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  11305:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   11306:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11307:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   11308:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   11309:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   11310:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  11311:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  11312:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  11313:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  11314:       /* 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  11315:       k4q++;;
1.350     brouard  11316:     }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"*/
                   11317:       /* Tvar[k1]; */ /* Age variable */ /* 17 age*V6*V2 ?*/
1.332     brouard  11318:       /* Wrong we want the value of variable name Tvar[k1] */
1.350     brouard  11319:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   11320:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   11321:       /* 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]]); */
                   11322:       }else{
                   11323:        k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   11324:        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)*/
                   11325:        TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
                   11326:        precov[nres][k1]=Tvalsel[k3];
                   11327:       }
1.342     brouard  11328:       /* 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  11329:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
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:        k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
                   11335:        k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
                   11336:        TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
                   11337:        precov[nres][k1]=Tvalsel[k3q];
                   11338:       }
1.342     brouard  11339:       /* 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  11340:     }else if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
1.332     brouard  11341:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
1.342     brouard  11342:       /* 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  11343:     }else{
1.332     brouard  11344:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   11345:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  11346:     }
                   11347:   }
1.234     brouard  11348:   
1.334     brouard  11349:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  11350:   return (0);
                   11351: }
1.235     brouard  11352: 
1.230     brouard  11353: int decodemodel( char model[], int lastobs)
                   11354:  /**< This routine decodes the model and returns:
1.224     brouard  11355:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   11356:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   11357:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   11358:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   11359:        * - cptcovage number of covariates with age*products =2
                   11360:        * - cptcovs number of simple covariates
1.339     brouard  11361:        * ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
1.224     brouard  11362:        * - 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  11363:        *     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
1.319     brouard  11364:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  11365:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   11366:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   11367:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   11368:        */
1.319     brouard  11369: /* 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  11370: {
1.238     brouard  11371:   int i, j, k, ks, v;
1.349     brouard  11372:   int n,m;
                   11373:   int  j1, k1, k11, k12, k2, k3, k4;
                   11374:   char modelsav[300];
                   11375:   char stra[300], strb[300], strc[300], strd[300],stre[300],strf[300];
1.187     brouard  11376:   char *strpt;
1.349     brouard  11377:   int  **existcomb;
                   11378:   
                   11379:   existcomb=imatrix(1,NCOVMAX,1,NCOVMAX);
                   11380:   for(i=1;i<=NCOVMAX;i++)
                   11381:     for(j=1;j<=NCOVMAX;j++)
                   11382:       existcomb[i][j]=0;
                   11383:     
1.145     brouard  11384:   /*removespace(model);*/
1.136     brouard  11385:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.349     brouard  11386:     j=0, j1=0, k1=0, k12=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  11387:     if (strstr(model,"AGE") !=0){
1.192     brouard  11388:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   11389:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  11390:       return 1;
                   11391:     }
1.141     brouard  11392:     if (strstr(model,"v") !=0){
1.338     brouard  11393:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
                   11394:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
1.141     brouard  11395:       return 1;
                   11396:     }
1.187     brouard  11397:     strcpy(modelsav,model); 
                   11398:     if ((strpt=strstr(model,"age*age")) !=0){
1.338     brouard  11399:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
1.187     brouard  11400:       if(strpt != model){
1.338     brouard  11401:        printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11402:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11403:  corresponding column of parameters.\n",model);
1.338     brouard  11404:        fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11405:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11406:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  11407:        return 1;
1.225     brouard  11408:       }
1.187     brouard  11409:       nagesqr=1;
                   11410:       if (strstr(model,"+age*age") !=0)
1.234     brouard  11411:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  11412:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  11413:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  11414:       else 
1.234     brouard  11415:        substrchaine(modelsav, model, "age*age");
1.187     brouard  11416:     }else
                   11417:       nagesqr=0;
1.349     brouard  11418:     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  11419:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   11420:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.351     brouard  11421:       cptcovs=0; /**<  Number of simple covariates V1 +V1*age +V3 +V3*V4 +age*age => V1 + V3 =4+1-3=2  Wrong */
1.187     brouard  11422:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  11423:                     * cst, age and age*age 
                   11424:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   11425:       /* including age products which are counted in cptcovage.
                   11426:        * but the covariates which are products must be treated 
                   11427:        * separately: ncovn=4- 2=2 (V1+V3). */
1.349     brouard  11428:       cptcovprod=0; /**< Number of products  V1*V2 +v3*age = 2 */
                   11429:       cptcovdageprod=0; /* Number of doouble products with age age*Vn*VM or Vn*age*Vm or Vn*Vm*age */
1.187     brouard  11430:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.349     brouard  11431:       cptcovprodage=0;
                   11432:       /* cptcovprodage=nboccstr(modelsav,"age");*/
1.225     brouard  11433:       
1.187     brouard  11434:       /*   Design
                   11435:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   11436:        *  <          ncovcol=8                >
                   11437:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   11438:        *   k=  1    2      3       4     5       6      7        8
                   11439:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
1.345     brouard  11440:        *  covar[k,i], are for fixed covariates, value of kth covariate if not including age for individual i:
1.224     brouard  11441:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   11442:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  11443:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   11444:        *  Tage[++cptcovage]=k
1.345     brouard  11445:        *       if products, new covar are created after ncovcol + nqv (quanti fixed) with k1
1.187     brouard  11446:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   11447:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   11448:        *  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
                   11449:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   11450:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   11451:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
1.345     brouard  11452:        *  <          ncovcol=8  8 fixed covariate. Additional starts at 9 (V5*V6) and 10(V7*V8)              >
1.187     brouard  11453:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   11454:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
1.345     brouard  11455:        *     Tvard[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   11456:        * p Tvar[1]@12={2,   1,     3,      3,   9,     10,     8,       8}
1.187     brouard  11457:        * p Tprod[1]@2={                         6, 5}
                   11458:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   11459:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   11460:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  11461:        *How to reorganize? Tvars(orted)
1.187     brouard  11462:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   11463:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   11464:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   11465:        * Struct []
                   11466:        */
1.225     brouard  11467:       
1.187     brouard  11468:       /* This loop fills the array Tvar from the string 'model'.*/
                   11469:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   11470:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   11471:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   11472:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   11473:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   11474:       /*       k=1 Tvar[1]=2 (from V2) */
                   11475:       /*       k=5 Tvar[5] */
                   11476:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  11477:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  11478:       /*       } */
1.198     brouard  11479:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  11480:       /*
                   11481:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  11482:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   11483:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   11484:       }
1.187     brouard  11485:       cptcovage=0;
1.351     brouard  11486: 
                   11487:       /* First loop in order to calculate */
                   11488:       /* for age*VN*Vm
                   11489:        * Provides, Typevar[k], Tage[cptcovage], existcomb[n][m], FixedV[ncovcolt+k12]
                   11490:        * Tprod[k1]=k  Tposprod[k]=k1;    Tvard[k1][1] =m;
                   11491:       */
                   11492:       /* Needs  FixedV[Tvardk[k][1]] */
                   11493:       /* For others:
                   11494:        * Sets  Typevar[k];
                   11495:        * Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   11496:        *       Tposprod[k]=k11;
                   11497:        *       Tprod[k11]=k;
                   11498:        *       Tvardk[k][1] =m;
                   11499:        * Needs FixedV[Tvardk[k][1]] == 0
                   11500:       */
                   11501:       
1.319     brouard  11502:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   11503:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   11504:                                         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" */
                   11505:        if (nbocc(modelsav,'+')==0)
                   11506:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  11507:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   11508:        /*scanf("%d",i);*/
1.349     brouard  11509:        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 */
                   11510:          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  */
                   11511:          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   */
                   11512:            Typevar[k]=3;  /* 3 for age and double product age*Vn*Vm varying of fixed */
                   11513:             if(strstr(strc,"age")!=0) { /* It means that strc=V2*age or age*V2 and thus that strd=Vn */
                   11514:               cutl(stre,strf,strc,'*') ; /* strf=age or Vm, stre=Vm or age. If strc=V6*V2 then strf=V6 and stre=V2 */
                   11515:              strcpy(strc,strb); /* save strb(=age*Vn*Vm) into strc */
                   11516:              /* We want strb=Vn*Vm */
                   11517:               if(strcmp(strf,"age")==0){ /* strf is "age" so that stre=Vm =V2 . */
                   11518:                 strcpy(strb,strd);
                   11519:                 strcat(strb,"*");
                   11520:                 strcat(strb,stre);
                   11521:               }else{  /* strf=Vm  If strf=V6 then stre=V2 */
                   11522:                 strcpy(strb,strf);
                   11523:                 strcat(strb,"*");
                   11524:                 strcat(strb,stre);
                   11525:                 strcpy(strd,strb); /* in order for strd to not be "age"  for next test (will be Vn*Vm */
                   11526:               }
1.351     brouard  11527:              /* 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]]]); */
                   11528:              /* FixedV[Tvar[Tage[k]]]=0; /\* HERY not sure if V7*V4*age Fixed might not exist  yet*\/ */
1.349     brouard  11529:             }else{  /* strc=Vn*Vm (and strd=age) and should be strb=Vn*Vm but want to keep original strb double product  */
                   11530:              strcpy(stre,strb); /* save full b in stre */
                   11531:              strcpy(strb,strc); /* save short c in new short b for next block strb=Vn*Vm*/
                   11532:              strcpy(strf,strc); /* save short c in new short f */
                   11533:               cutl(strc,strd,strf,'*'); /* We get strd=Vn and strc=Vm for next block (strb=Vn*Vm)*/
                   11534:              /* strcpy(strc,stre);*/ /* save full e in c for future */
                   11535:             }
                   11536:             cptcovdageprod++; /* double product with age  Which product is it? */
                   11537:             /* 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 *\/ */
                   11538:             /* cutl(strc,strd,strb,'*'); /\* strd=  V6    or   V2     or    age and  strc=  V2 or    age or    V2 *\/ */
1.234     brouard  11539:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
1.349     brouard  11540:            n=atoi(stre);
1.234     brouard  11541:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.349     brouard  11542:            m=atoi(strc);
                   11543:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   11544:            Tage[cptcovage]=k; /* For age*V3*V2 gives the position in model of covariates associated with age Tage[1]=6 HERY too*/
                   11545:            if(existcomb[n][m] == 0){
                   11546:              /*  r /home/brouard/Documents/Recherches/REVES/Zachary/Zach-2022/Feinuo_Sun/Feinuo-threeway/femV12V15_3wayintNBe.imach */
                   11547:              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);
                   11548:              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);
                   11549:              fflush(ficlog);
                   11550:              k1++;  /* The combination Vn*Vm will be in the model so we create it at k1 */
                   11551:              k12++;
                   11552:              existcomb[n][m]=k1;
                   11553:              existcomb[m][n]=k1;
                   11554:              Tvar[k]=ncovcol+nqv+ntv+nqtv+k1;
                   11555:              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*/
                   11556:              Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 Gives the k1 double product  Vn*Vm or age*Vn*Vm at the k position */
                   11557:              Tvard[k1][1] =m; /* m 1 for V1*/
                   11558:              Tvardk[k][1] =m; /* m 1 for V1*/
                   11559:              Tvard[k1][2] =n; /* n 4 for V4*/
                   11560:              Tvardk[k][2] =n; /* n 4 for V4*/
1.351     brouard  11561: /*           Tvar[Tage[cptcovage]]=k1;*/ /* Tvar[6=age*V3*V2]=9 (new fixed covariate) */ /* We don't know about Fixed yet HERE */
1.349     brouard  11562:              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 */
                   11563:                for (i=1; i<=lastobs;i++){/* For fixed product */
                   11564:                  /* Computes the new covariate which is a product of
                   11565:                     covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   11566:                  covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   11567:                }
                   11568:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11569:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   11570:                k12++;
                   11571:                FixedV[ncovcolt+k12]=0;
                   11572:              }else{ /*End of FixedV */
                   11573:                cptcovprodvage++; /* Counting the number of varying covariate with age */
                   11574:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   11575:                k12++;
                   11576:                FixedV[ncovcolt+k12]=1;
                   11577:              }
                   11578:            }else{  /* k1 Vn*Vm already exists */
                   11579:              k11=existcomb[n][m];
                   11580:              Tposprod[k]=k11; /* OK */
                   11581:              Tvar[k]=Tvar[Tprod[k11]]; /* HERY */
                   11582:              Tvardk[k][1]=m;
                   11583:              Tvardk[k][2]=n;
                   11584:              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 */
                   11585:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   11586:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11587:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   11588:                Tvar[Tage[cptcovage]]=k1;
                   11589:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   11590:                k12++;
                   11591:                FixedV[ncovcolt+k12]=0;
                   11592:              }else{ /* Already exists but time varying (and age) */
                   11593:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   11594:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   11595:                /* Tvar[Tage[cptcovage]]=k1; */
                   11596:                cptcovprodvage++;
                   11597:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   11598:                k12++;
                   11599:                FixedV[ncovcolt+k12]=1;
                   11600:              }
                   11601:            }
                   11602:            /* Tage[cptcovage]=k;  /\*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   11603:            /* Tvar[k]=k11; /\* HERY *\/ */
                   11604:          } 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 */
                   11605:             cptcovprod++;
                   11606:             if (strcmp(strc,"age")==0) { /**< Model includes age: strb= Vn*age c=age d=Vn*/
                   11607:               /* covar is not filled and then is empty */
                   11608:               cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   11609:               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 */
                   11610:               Typevar[k]=1;  /* 1 for age product */
                   11611:               cptcovage++; /* Counts the number of covariates which include age as a product */
                   11612:               Tage[cptcovage]=k;  /*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   11613:              if( FixedV[Tvar[k]] == 0){
                   11614:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11615:              }else{
                   11616:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
                   11617:              }
                   11618:               /*printf("stre=%s ", stre);*/
                   11619:             } else if (strcmp(strd,"age")==0) { /* strb= age*Vn c=Vn */
                   11620:               cutl(stre,strb,strc,'V');
                   11621:               Tvar[k]=atoi(stre);
                   11622:               Typevar[k]=1;  /* 1 for age product */
                   11623:               cptcovage++;
                   11624:               Tage[cptcovage]=k;
                   11625:              if( FixedV[Tvar[k]] == 0){
                   11626:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11627:              }else{
                   11628:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
1.339     brouard  11629:              }
1.349     brouard  11630:             }else{ /*  for product Vn*Vm */
                   11631:              Typevar[k]=2;  /* 2 for product Vn*Vm */
                   11632:              cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   11633:              n=atoi(stre);
                   11634:              cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   11635:              m=atoi(strc);
                   11636:              k1++;
                   11637:              cptcovprodnoage++;
                   11638:              if(existcomb[n][m] != 0 || existcomb[m][n] != 0){
                   11639:                printf("Warning in model combination V%d*V%d already exists in the model in position k1=%d!\n",n,m,existcomb[n][m]);
                   11640:                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]);
                   11641:                fflush(ficlog);
                   11642:                k11=existcomb[n][m];
                   11643:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   11644:                Tposprod[k]=k11;
                   11645:                Tprod[k11]=k;
                   11646:                Tvardk[k][1] =m; /* m 1 for V1*/
                   11647:                /* Tvard[k11][1] =m; /\* n 4 for V4*\/ */
                   11648:                Tvardk[k][2] =n; /* n 4 for V4*/                
                   11649:                /* Tvard[k11][2] =n; /\* n 4 for V4*\/ */
                   11650:              }else{ /* combination Vn*Vm doesn't exist we create it (no age)*/
                   11651:                existcomb[n][m]=k1;
                   11652:                existcomb[m][n]=k1;
                   11653:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
                   11654:                                                    because this model-covariate is a construction we invent a new column
                   11655:                                                    which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   11656:                                                    If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
                   11657:                                                    thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
                   11658:                                                    Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
                   11659:                /* Please remark that the new variables are model dependent */
                   11660:                /* If we have 4 variable but the model uses only 3, like in
                   11661:                 * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   11662:                 *  k=     1     2      3   4     5        6        7       8
                   11663:                 * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   11664:                 * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   11665:                 * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   11666:                 */
                   11667:                /* We need to feed some variables like TvarVV, but later on next loop because of ncovv (k2) is not correct */
                   11668:                Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 +V6*V2*age  */
                   11669:                Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
                   11670:                Tvard[k1][1] =m; /* m 1 for V1*/
                   11671:                Tvardk[k][1] =m; /* m 1 for V1*/
                   11672:                Tvard[k1][2] =n; /* n 4 for V4*/
                   11673:                Tvardk[k][2] =n; /* n 4 for V4*/
                   11674:                k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   11675:                /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   11676:                /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
                   11677:                /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
                   11678:                /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   11679:                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 */
                   11680:                  for (i=1; i<=lastobs;i++){/* For fixed product */
                   11681:                    /* Computes the new covariate which is a product of
                   11682:                       covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   11683:                    covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   11684:                  }
                   11685:                  /* TvarVV[k2]=n; */
                   11686:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11687:                  /* TvarVV[k2+1]=m; */
                   11688:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11689:                }else{ /* not FixedV */
                   11690:                  /* TvarVV[k2]=n; */
                   11691:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11692:                  /* TvarVV[k2+1]=m; */
                   11693:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11694:                }                 
                   11695:              }  /* End of creation of Vn*Vm if not created by age*Vn*Vm earlier  */
                   11696:            } /*  End of product Vn*Vm */
                   11697:           } /* End of age*double product or simple product */
                   11698:        }else { /* not a product */
1.234     brouard  11699:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   11700:          /*  scanf("%d",i);*/
                   11701:          cutl(strd,strc,strb,'V');
                   11702:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   11703:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   11704:          Tvar[k]=atoi(strd);
                   11705:          Typevar[k]=0;  /* 0 for simple covariates */
                   11706:        }
                   11707:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  11708:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  11709:                                  scanf("%d",i);*/
1.187     brouard  11710:       } /* end of loop + on total covariates */
1.351     brouard  11711: 
                   11712:       
1.187     brouard  11713:     } /* end if strlen(modelsave == 0) age*age might exist */
                   11714:   } /* end if strlen(model == 0) */
1.349     brouard  11715:   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  */
                   11716: 
1.136     brouard  11717:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   11718:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  11719:   
1.136     brouard  11720:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  11721:      printf("cptcovprod=%d ", cptcovprod);
                   11722:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   11723:      scanf("%d ",i);*/
                   11724: 
                   11725: 
1.230     brouard  11726: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   11727:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  11728: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   11729:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   11730:    k =           1    2   3     4       5       6      7      8        9
                   11731:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  11732:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  11733:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   11734:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   11735:          Tmodelind[combination of covar]=k;
1.225     brouard  11736: */  
                   11737: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  11738:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  11739:   /* 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  11740:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  11741:   printf("Model=1+age+%s\n\
1.349     brouard  11742: 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  11743: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11744: 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  11745:   fprintf(ficlog,"Model=1+age+%s\n\
1.349     brouard  11746: 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  11747: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11748: 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  11749:   for(k=-1;k<=NCOVMAX; k++){ Fixed[k]=0; Dummy[k]=0;}
                   11750:   for(k=1;k<=NCOVMAX; k++){TvarFind[k]=0; TvarVind[k]=0;}
1.351     brouard  11751: 
                   11752: 
                   11753:   /* Second loop for calculating  Fixed[k], Dummy[k]*/
                   11754: 
                   11755:   
1.349     brouard  11756:   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  11757:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  11758:       Fixed[k]= 0;
                   11759:       Dummy[k]= 0;
1.225     brouard  11760:       ncoveff++;
1.232     brouard  11761:       ncovf++;
1.234     brouard  11762:       nsd++;
                   11763:       modell[k].maintype= FTYPE;
                   11764:       TvarsD[nsd]=Tvar[k];
                   11765:       TvarsDind[nsd]=k;
1.330     brouard  11766:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  11767:       TvarF[ncovf]=Tvar[k];
                   11768:       TvarFind[ncovf]=k;
                   11769:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11770:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.339     brouard  11771:     /* }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  11772:     }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  11773:       Fixed[k]= 0;
                   11774:       Dummy[k]= 1;
1.230     brouard  11775:       nqfveff++;
1.234     brouard  11776:       modell[k].maintype= FTYPE;
                   11777:       modell[k].subtype= FQ;
                   11778:       nsq++;
1.334     brouard  11779:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   11780:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  11781:       ncovf++;
1.234     brouard  11782:       TvarF[ncovf]=Tvar[k];
                   11783:       TvarFind[ncovf]=k;
1.231     brouard  11784:       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  11785:       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  11786:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.339     brouard  11787:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11788:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11789:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11790:       ncovvt++;
                   11791:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11792:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
                   11793: 
1.227     brouard  11794:       Fixed[k]= 1;
                   11795:       Dummy[k]= 0;
1.225     brouard  11796:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  11797:       modell[k].maintype= VTYPE;
                   11798:       modell[k].subtype= VD;
                   11799:       nsd++;
                   11800:       TvarsD[nsd]=Tvar[k];
                   11801:       TvarsDind[nsd]=k;
1.330     brouard  11802:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  11803:       ncovv++; /* Only simple time varying variables */
                   11804:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11805:       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  11806:       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 */
                   11807:       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  11808:       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);
                   11809:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  11810:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.339     brouard  11811:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11812:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11813:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11814:       ncovvt++;
                   11815:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11816:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11817:       
1.234     brouard  11818:       Fixed[k]= 1;
                   11819:       Dummy[k]= 1;
                   11820:       nqtveff++;
                   11821:       modell[k].maintype= VTYPE;
                   11822:       modell[k].subtype= VQ;
                   11823:       ncovv++; /* Only simple time varying variables */
                   11824:       nsq++;
1.334     brouard  11825:       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) */
                   11826:       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  11827:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11828:       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  11829:       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 */
                   11830:       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  11831:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   11832:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
1.349     brouard  11833:       /* 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  11834:       /* printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv); */
1.227     brouard  11835:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  11836:       ncova++;
                   11837:       TvarA[ncova]=Tvar[k];
                   11838:       TvarAind[ncova]=k;
1.349     brouard  11839:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   11840:       /** 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  11841:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  11842:        Fixed[k]= 2;
                   11843:        Dummy[k]= 2;
                   11844:        modell[k].maintype= ATYPE;
                   11845:        modell[k].subtype= APFD;
1.349     brouard  11846:        ncovta++;
                   11847:        TvarAVVA[ncovta]=Tvar[k]; /*  (2)age*V3 */
                   11848:        TvarAVVAind[ncovta]=k;
1.240     brouard  11849:        /* ncoveff++; */
1.227     brouard  11850:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  11851:        Fixed[k]= 2;
                   11852:        Dummy[k]= 3;
                   11853:        modell[k].maintype= ATYPE;
                   11854:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
1.349     brouard  11855:        ncovta++;
                   11856:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   11857:        TvarAVVAind[ncovta]=k;
1.240     brouard  11858:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  11859:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  11860:        Fixed[k]= 3;
                   11861:        Dummy[k]= 2;
                   11862:        modell[k].maintype= ATYPE;
                   11863:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
1.349     brouard  11864:        ncovva++;
                   11865:        TvarVVA[ncovva]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   11866:        TvarVVAind[ncovva]=k;
                   11867:        ncovta++;
                   11868:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   11869:        TvarAVVAind[ncovta]=k;
1.240     brouard  11870:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  11871:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  11872:        Fixed[k]= 3;
                   11873:        Dummy[k]= 3;
                   11874:        modell[k].maintype= ATYPE;
                   11875:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
1.349     brouard  11876:        ncovva++;
                   11877:        TvarVVA[ncovva]=Tvar[k]; /*   */
                   11878:        TvarVVAind[ncovva]=k;
                   11879:        ncovta++;
                   11880:        TvarAVVA[ncovta]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   11881:        TvarAVVAind[ncovta]=k;
1.240     brouard  11882:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  11883:       }
1.349     brouard  11884:     }else if( Tposprod[k]>0  &&  Typevar[k]==2){  /* Detects if fixed product no age Vm*Vn */
                   11885:       printf("MEMORY ERRORR k=%d  Tposprod[k]=%d, Typevar[k]=%d\n ",k, Tposprod[k], Typevar[k]);
                   11886:       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 */
                   11887:       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]]);
                   11888:        Fixed[k]= 0;
                   11889:        Dummy[k]= 0;
                   11890:        ncoveff++;
                   11891:        ncovf++;
                   11892:        /* ncovv++; */
                   11893:        /* TvarVV[ncovv]=Tvardk[k][1]; */
                   11894:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11895:        /* ncovv++; */
                   11896:        /* TvarVV[ncovv]=Tvardk[k][2]; */
                   11897:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11898:        modell[k].maintype= FTYPE;
                   11899:        TvarF[ncovf]=Tvar[k];
                   11900:        /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
                   11901:        TvarFind[ncovf]=k;
                   11902:        TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11903:        TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11904:       }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  */
                   11905:        /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11906:        /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   11907:        /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11908:        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 */
                   11909:        ncovvt++;
                   11910:        TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   11911:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11912:        ncovvt++;
                   11913:        TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   11914:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11915:        
                   11916:        /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   11917:        /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   11918:        
                   11919:        if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   11920:          if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
                   11921:            Fixed[k]= 1;
                   11922:            Dummy[k]= 0;
                   11923:            modell[k].maintype= FTYPE;
                   11924:            modell[k].subtype= FPDD;            /*      Product fixed dummy * fixed dummy */
                   11925:            ncovf++; /* Fixed variables without age */
                   11926:            TvarF[ncovf]=Tvar[k];
                   11927:            TvarFind[ncovf]=k;
                   11928:          }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
                   11929:            Fixed[k]= 0;  /* Fixed product */
                   11930:            Dummy[k]= 1;
                   11931:            modell[k].maintype= FTYPE;
                   11932:            modell[k].subtype= FPDQ;            /*      Product fixed dummy * fixed quantitative */
                   11933:            ncovf++; /* Varying variables without age */
                   11934:            TvarF[ncovf]=Tvar[k];
                   11935:            TvarFind[ncovf]=k;
                   11936:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
                   11937:            Fixed[k]= 1;
                   11938:            Dummy[k]= 0;
                   11939:            modell[k].maintype= VTYPE;
                   11940:            modell[k].subtype= VPDD;            /*      Product fixed dummy * varying dummy */
                   11941:            ncovv++; /* Varying variables without age */
                   11942:            TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   11943:            TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
                   11944:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
                   11945:            Fixed[k]= 1;
                   11946:            Dummy[k]= 1;
                   11947:            modell[k].maintype= VTYPE;
                   11948:            modell[k].subtype= VPDQ;            /*      Product fixed dummy * varying quantitative */
                   11949:            ncovv++; /* Varying variables without age */
                   11950:            TvarV[ncovv]=Tvar[k];
                   11951:            TvarVind[ncovv]=k;
                   11952:          }
                   11953:        }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   11954:          if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
                   11955:            Fixed[k]= 0;  /*  Fixed product */
                   11956:            Dummy[k]= 1;
                   11957:            modell[k].maintype= FTYPE;
                   11958:            modell[k].subtype= FPDQ;            /*      Product fixed quantitative * fixed dummy */
                   11959:            ncovf++; /* Fixed variables without age */
                   11960:            TvarF[ncovf]=Tvar[k];
                   11961:            TvarFind[ncovf]=k;
                   11962:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
                   11963:            Fixed[k]= 1;
                   11964:            Dummy[k]= 1;
                   11965:            modell[k].maintype= VTYPE;
                   11966:            modell[k].subtype= VPDQ;            /*      Product fixed quantitative * varying dummy */
                   11967:            ncovv++; /* Varying variables without age */
                   11968:            TvarV[ncovv]=Tvar[k];
                   11969:            TvarVind[ncovv]=k;
                   11970:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
                   11971:            Fixed[k]= 1;
                   11972:            Dummy[k]= 1;
                   11973:            modell[k].maintype= VTYPE;
                   11974:            modell[k].subtype= VPQQ;            /*      Product fixed quantitative * varying quantitative */
                   11975:            ncovv++; /* Varying variables without age */
                   11976:            TvarV[ncovv]=Tvar[k];
                   11977:            TvarVind[ncovv]=k;
                   11978:            ncovv++; /* Varying variables without age */
                   11979:            TvarV[ncovv]=Tvar[k];
                   11980:            TvarVind[ncovv]=k;
                   11981:          }
                   11982:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
                   11983:          if(Tvard[k1][2] <=ncovcol){
                   11984:            Fixed[k]= 1;
                   11985:            Dummy[k]= 1;
                   11986:            modell[k].maintype= VTYPE;
                   11987:            modell[k].subtype= VPDD;            /*      Product time varying dummy * fixed dummy */
                   11988:            ncovv++; /* Varying variables without age */
                   11989:            TvarV[ncovv]=Tvar[k];
                   11990:            TvarVind[ncovv]=k;
                   11991:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11992:            Fixed[k]= 1;
                   11993:            Dummy[k]= 1;
                   11994:            modell[k].maintype= VTYPE;
                   11995:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * fixed quantitative */
                   11996:            ncovv++; /* Varying variables without age */
                   11997:            TvarV[ncovv]=Tvar[k];
                   11998:            TvarVind[ncovv]=k;
                   11999:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   12000:            Fixed[k]= 1;
                   12001:            Dummy[k]= 0;
                   12002:            modell[k].maintype= VTYPE;
                   12003:            modell[k].subtype= VPDD;            /*      Product time varying dummy * time varying dummy */
                   12004:            ncovv++; /* Varying variables without age */
                   12005:            TvarV[ncovv]=Tvar[k];
                   12006:            TvarVind[ncovv]=k;
                   12007:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   12008:            Fixed[k]= 1;
                   12009:            Dummy[k]= 1;
                   12010:            modell[k].maintype= VTYPE;
                   12011:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * time varying quantitative */
                   12012:            ncovv++; /* Varying variables without age */
                   12013:            TvarV[ncovv]=Tvar[k];
                   12014:            TvarVind[ncovv]=k;
                   12015:          }
                   12016:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
                   12017:          if(Tvard[k1][2] <=ncovcol){
                   12018:            Fixed[k]= 1;
                   12019:            Dummy[k]= 1;
                   12020:            modell[k].maintype= VTYPE;
                   12021:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * fixed dummy */
                   12022:            ncovv++; /* Varying variables without age */
                   12023:            TvarV[ncovv]=Tvar[k];
                   12024:            TvarVind[ncovv]=k;
                   12025:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   12026:            Fixed[k]= 1;
                   12027:            Dummy[k]= 1;
                   12028:            modell[k].maintype= VTYPE;
                   12029:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * fixed quantitative */
                   12030:            ncovv++; /* Varying variables without age */
                   12031:            TvarV[ncovv]=Tvar[k];
                   12032:            TvarVind[ncovv]=k;
                   12033:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   12034:            Fixed[k]= 1;
                   12035:            Dummy[k]= 1;
                   12036:            modell[k].maintype= VTYPE;
                   12037:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * time varying dummy */
                   12038:            ncovv++; /* Varying variables without age */
                   12039:            TvarV[ncovv]=Tvar[k];
                   12040:            TvarVind[ncovv]=k;
                   12041:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   12042:            Fixed[k]= 1;
                   12043:            Dummy[k]= 1;
                   12044:            modell[k].maintype= VTYPE;
                   12045:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * time varying quantitative */
                   12046:            ncovv++; /* Varying variables without age */
                   12047:            TvarV[ncovv]=Tvar[k];
                   12048:            TvarVind[ncovv]=k;
                   12049:          }
                   12050:        }else{
                   12051:          printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12052:          fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12053:        } /*end k1*/
                   12054:       }
                   12055:     }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  12056:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  12057:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   12058:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   12059:       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 */
                   12060:       ncova++;
                   12061:       TvarA[ncova]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   12062:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   12063:       ncova++;
                   12064:       TvarA[ncova]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   12065:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
1.339     brouard  12066: 
1.349     brouard  12067:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   12068:       /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   12069:       if( FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){
                   12070:        ncovta++;
                   12071:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12072:        TvarAVVAind[ncovta]=k;
                   12073:        ncovta++;
                   12074:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12075:        TvarAVVAind[ncovta]=k;
                   12076:       }else{
                   12077:        ncovva++;  /* HERY  reached */
                   12078:        TvarVVA[ncovva]=Tvard[k1][1]; /*  age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4  */
                   12079:        TvarVVAind[ncovva]=k;
                   12080:        ncovva++;
                   12081:        TvarVVA[ncovva]=Tvard[k1][2]; /*   */
                   12082:        TvarVVAind[ncovva]=k;
                   12083:        ncovta++;
                   12084:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12085:        TvarAVVAind[ncovta]=k;
                   12086:        ncovta++;
                   12087:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12088:        TvarAVVAind[ncovta]=k;
                   12089:       }
1.339     brouard  12090:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   12091:        if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
1.349     brouard  12092:          Fixed[k]= 2;
                   12093:          Dummy[k]= 2;
1.240     brouard  12094:          modell[k].maintype= FTYPE;
                   12095:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
1.349     brouard  12096:          /* TvarF[ncova]=Tvar[k];   /\* Problem to solve *\/ */
                   12097:          /* TvarFind[ncova]=k; */
1.339     brouard  12098:        }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
1.349     brouard  12099:          Fixed[k]= 2;  /* Fixed product */
                   12100:          Dummy[k]= 3;
1.240     brouard  12101:          modell[k].maintype= FTYPE;
                   12102:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
1.349     brouard  12103:          /* TvarF[ncova]=Tvar[k]; */
                   12104:          /* TvarFind[ncova]=k; */
1.339     brouard  12105:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
1.349     brouard  12106:          Fixed[k]= 3;
                   12107:          Dummy[k]= 2;
1.240     brouard  12108:          modell[k].maintype= VTYPE;
                   12109:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
1.349     brouard  12110:          TvarV[ncova]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   12111:          TvarVind[ncova]=k;/* TvarVind[1]=5 */ 
1.339     brouard  12112:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
1.349     brouard  12113:          Fixed[k]= 3;
                   12114:          Dummy[k]= 3;
1.240     brouard  12115:          modell[k].maintype= VTYPE;
                   12116:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
1.349     brouard  12117:          /* ncovv++; /\* Varying variables without age *\/ */
                   12118:          /* TvarV[ncovv]=Tvar[k]; */
                   12119:          /* TvarVind[ncovv]=k; */
1.240     brouard  12120:        }
1.339     brouard  12121:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   12122:        if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
1.349     brouard  12123:          Fixed[k]= 2;  /*  Fixed product */
                   12124:          Dummy[k]= 2;
1.240     brouard  12125:          modell[k].maintype= FTYPE;
                   12126:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
1.349     brouard  12127:          /* ncova++; /\* Fixed variables with age *\/ */
                   12128:          /* TvarF[ncovf]=Tvar[k]; */
                   12129:          /* TvarFind[ncovf]=k; */
1.339     brouard  12130:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
1.349     brouard  12131:          Fixed[k]= 2;
                   12132:          Dummy[k]= 3;
1.240     brouard  12133:          modell[k].maintype= VTYPE;
                   12134:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
1.349     brouard  12135:          /* ncova++; /\* Varying variables with age *\/ */
                   12136:          /* TvarV[ncova]=Tvar[k]; */
                   12137:          /* TvarVind[ncova]=k; */
1.339     brouard  12138:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
1.349     brouard  12139:          Fixed[k]= 3;
                   12140:          Dummy[k]= 2;
1.240     brouard  12141:          modell[k].maintype= VTYPE;
                   12142:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
1.349     brouard  12143:          ncova++; /* Varying variables without age */
                   12144:          TvarV[ncova]=Tvar[k];
                   12145:          TvarVind[ncova]=k;
                   12146:          /* ncova++; /\* Varying variables without age *\/ */
                   12147:          /* TvarV[ncova]=Tvar[k]; */
                   12148:          /* TvarVind[ncova]=k; */
1.240     brouard  12149:        }
1.339     brouard  12150:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
1.240     brouard  12151:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  12152:          Fixed[k]= 2;
                   12153:          Dummy[k]= 2;
1.240     brouard  12154:          modell[k].maintype= VTYPE;
                   12155:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
1.349     brouard  12156:          /* ncova++; /\* Varying variables with age *\/ */
                   12157:          /* TvarV[ncova]=Tvar[k]; */
                   12158:          /* TvarVind[ncova]=k; */
1.240     brouard  12159:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  12160:          Fixed[k]= 2;
                   12161:          Dummy[k]= 3;
1.240     brouard  12162:          modell[k].maintype= VTYPE;
                   12163:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
1.349     brouard  12164:          /* ncova++; /\* Varying variables with age *\/ */
                   12165:          /* TvarV[ncova]=Tvar[k]; */
                   12166:          /* TvarVind[ncova]=k; */
1.240     brouard  12167:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349     brouard  12168:          Fixed[k]= 3;
                   12169:          Dummy[k]= 2;
1.240     brouard  12170:          modell[k].maintype= VTYPE;
                   12171:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
1.349     brouard  12172:          /* ncova++; /\* Varying variables with age *\/ */
                   12173:          /* TvarV[ncova]=Tvar[k]; */
                   12174:          /* TvarVind[ncova]=k; */
1.240     brouard  12175:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  12176:          Fixed[k]= 3;
                   12177:          Dummy[k]= 3;
1.240     brouard  12178:          modell[k].maintype= VTYPE;
                   12179:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
1.349     brouard  12180:          /* ncova++; /\* Varying variables with age *\/ */
                   12181:          /* TvarV[ncova]=Tvar[k]; */
                   12182:          /* TvarVind[ncova]=k; */
1.240     brouard  12183:        }
1.339     brouard  12184:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
1.240     brouard  12185:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  12186:          Fixed[k]= 2;
                   12187:          Dummy[k]= 2;
1.240     brouard  12188:          modell[k].maintype= VTYPE;
                   12189:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
1.349     brouard  12190:          /* ncova++; /\* Varying variables with age *\/ */
                   12191:          /* TvarV[ncova]=Tvar[k]; */
                   12192:          /* TvarVind[ncova]=k; */
1.240     brouard  12193:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  12194:          Fixed[k]= 2;
                   12195:          Dummy[k]= 3;
1.240     brouard  12196:          modell[k].maintype= VTYPE;
                   12197:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
1.349     brouard  12198:          /* ncova++; /\* Varying variables with age *\/ */
                   12199:          /* TvarV[ncova]=Tvar[k]; */
                   12200:          /* TvarVind[ncova]=k; */
1.240     brouard  12201:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349     brouard  12202:          Fixed[k]= 3;
                   12203:          Dummy[k]= 2;
1.240     brouard  12204:          modell[k].maintype= VTYPE;
                   12205:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
1.349     brouard  12206:          /* ncova++; /\* Varying variables with age *\/ */
                   12207:          /* TvarV[ncova]=Tvar[k]; */
                   12208:          /* TvarVind[ncova]=k; */
1.240     brouard  12209:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  12210:          Fixed[k]= 3;
                   12211:          Dummy[k]= 3;
1.240     brouard  12212:          modell[k].maintype= VTYPE;
                   12213:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
1.349     brouard  12214:          /* ncova++; /\* Varying variables with age *\/ */
                   12215:          /* TvarV[ncova]=Tvar[k]; */
                   12216:          /* TvarVind[ncova]=k; */
1.240     brouard  12217:        }
1.227     brouard  12218:       }else{
1.240     brouard  12219:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12220:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12221:       } /*end k1*/
1.349     brouard  12222:     } else{
1.226     brouard  12223:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   12224:       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  12225:     }
1.342     brouard  12226:     /* 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]); */
                   12227:     /* printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype); */
1.227     brouard  12228:     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]);
                   12229:   }
1.349     brouard  12230:   ncovvta=ncovva;
1.227     brouard  12231:   /* Searching for doublons in the model */
                   12232:   for(k1=1; k1<= cptcovt;k1++){
                   12233:     for(k2=1; k2 <k1;k2++){
1.285     brouard  12234:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   12235:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  12236:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   12237:          if(Tvar[k1]==Tvar[k2]){
1.338     brouard  12238:            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]);
                   12239:            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  12240:            return(1);
                   12241:          }
                   12242:        }else if (Typevar[k1] ==2){
                   12243:          k3=Tposprod[k1];
                   12244:          k4=Tposprod[k2];
                   12245:          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  12246:            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]]);
                   12247:            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  12248:            return(1);
                   12249:          }
                   12250:        }
1.227     brouard  12251:       }
                   12252:     }
1.225     brouard  12253:   }
                   12254:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   12255:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  12256:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   12257:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.349     brouard  12258: 
                   12259:   free_imatrix(existcomb,1,NCOVMAX,1,NCOVMAX);
1.137     brouard  12260:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  12261:   /*endread:*/
1.225     brouard  12262:   printf("Exiting decodemodel: ");
                   12263:   return (1);
1.136     brouard  12264: }
                   12265: 
1.169     brouard  12266: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  12267: {/* Check ages at death */
1.136     brouard  12268:   int i, m;
1.218     brouard  12269:   int firstone=0;
                   12270:   
1.136     brouard  12271:   for (i=1; i<=imx; i++) {
                   12272:     for(m=2; (m<= maxwav); m++) {
                   12273:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   12274:        anint[m][i]=9999;
1.216     brouard  12275:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   12276:          s[m][i]=-1;
1.136     brouard  12277:       }
                   12278:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  12279:        *nberr = *nberr + 1;
1.218     brouard  12280:        if(firstone == 0){
                   12281:          firstone=1;
1.260     brouard  12282:        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  12283:        }
1.262     brouard  12284:        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  12285:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  12286:       }
                   12287:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  12288:        (*nberr)++;
1.259     brouard  12289:        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  12290:        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  12291:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  12292:       }
                   12293:     }
                   12294:   }
                   12295: 
                   12296:   for (i=1; i<=imx; i++)  {
                   12297:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   12298:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  12299:       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  12300:        if (s[m][i] >= nlstate+1) {
1.169     brouard  12301:          if(agedc[i]>0){
                   12302:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  12303:              agev[m][i]=agedc[i];
1.214     brouard  12304:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  12305:            }else {
1.136     brouard  12306:              if ((int)andc[i]!=9999){
                   12307:                nbwarn++;
                   12308:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   12309:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   12310:                agev[m][i]=-1;
                   12311:              }
                   12312:            }
1.169     brouard  12313:          } /* agedc > 0 */
1.214     brouard  12314:        } /* end if */
1.136     brouard  12315:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   12316:                                 years but with the precision of a month */
                   12317:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   12318:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   12319:            agev[m][i]=1;
                   12320:          else if(agev[m][i] < *agemin){ 
                   12321:            *agemin=agev[m][i];
                   12322:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   12323:          }
                   12324:          else if(agev[m][i] >*agemax){
                   12325:            *agemax=agev[m][i];
1.156     brouard  12326:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  12327:          }
                   12328:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   12329:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  12330:        } /* en if 9*/
1.136     brouard  12331:        else { /* =9 */
1.214     brouard  12332:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  12333:          agev[m][i]=1;
                   12334:          s[m][i]=-1;
                   12335:        }
                   12336:       }
1.214     brouard  12337:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  12338:        agev[m][i]=1;
1.214     brouard  12339:       else{
                   12340:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   12341:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   12342:        agev[m][i]=0;
                   12343:       }
                   12344:     } /* End for lastpass */
                   12345:   }
1.136     brouard  12346:     
                   12347:   for (i=1; i<=imx; i++)  {
                   12348:     for(m=firstpass; (m<=lastpass); m++){
                   12349:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  12350:        (*nberr)++;
1.136     brouard  12351:        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);     
                   12352:        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);     
                   12353:        return 1;
                   12354:       }
                   12355:     }
                   12356:   }
                   12357: 
                   12358:   /*for (i=1; i<=imx; i++){
                   12359:   for (m=firstpass; (m<lastpass); m++){
                   12360:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   12361: }
                   12362: 
                   12363: }*/
                   12364: 
                   12365: 
1.139     brouard  12366:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   12367:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  12368: 
                   12369:   return (0);
1.164     brouard  12370:  /* endread:*/
1.136     brouard  12371:     printf("Exiting calandcheckages: ");
                   12372:     return (1);
                   12373: }
                   12374: 
1.172     brouard  12375: #if defined(_MSC_VER)
                   12376: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   12377: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   12378: //#include "stdafx.h"
                   12379: //#include <stdio.h>
                   12380: //#include <tchar.h>
                   12381: //#include <windows.h>
                   12382: //#include <iostream>
                   12383: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   12384: 
                   12385: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   12386: 
                   12387: BOOL IsWow64()
                   12388: {
                   12389:        BOOL bIsWow64 = FALSE;
                   12390: 
                   12391:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   12392:        //  (HANDLE, PBOOL);
                   12393: 
                   12394:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   12395: 
                   12396:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   12397:        const char funcName[] = "IsWow64Process";
                   12398:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   12399:                GetProcAddress(module, funcName);
                   12400: 
                   12401:        if (NULL != fnIsWow64Process)
                   12402:        {
                   12403:                if (!fnIsWow64Process(GetCurrentProcess(),
                   12404:                        &bIsWow64))
                   12405:                        //throw std::exception("Unknown error");
                   12406:                        printf("Unknown error\n");
                   12407:        }
                   12408:        return bIsWow64 != FALSE;
                   12409: }
                   12410: #endif
1.177     brouard  12411: 
1.191     brouard  12412: void syscompilerinfo(int logged)
1.292     brouard  12413: {
                   12414: #include <stdint.h>
                   12415: 
                   12416:   /* #include "syscompilerinfo.h"*/
1.185     brouard  12417:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   12418:    /* /GS /W3 /Gy
                   12419:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   12420:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   12421:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  12422:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   12423:    */ 
                   12424:    /* 64 bits */
1.185     brouard  12425:    /*
                   12426:      /GS /W3 /Gy
                   12427:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   12428:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   12429:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   12430:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   12431:    /* Optimization are useless and O3 is slower than O2 */
                   12432:    /*
                   12433:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   12434:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   12435:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   12436:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   12437:    */
1.186     brouard  12438:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  12439:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   12440:       /PDB:"visual studio
                   12441:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   12442:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   12443:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   12444:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   12445:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   12446:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   12447:       uiAccess='false'"
                   12448:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   12449:       /NOLOGO /TLBID:1
                   12450:    */
1.292     brouard  12451: 
                   12452: 
1.177     brouard  12453: #if defined __INTEL_COMPILER
1.178     brouard  12454: #if defined(__GNUC__)
                   12455:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   12456: #endif
1.177     brouard  12457: #elif defined(__GNUC__) 
1.179     brouard  12458: #ifndef  __APPLE__
1.174     brouard  12459: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  12460: #endif
1.177     brouard  12461:    struct utsname sysInfo;
1.178     brouard  12462:    int cross = CROSS;
                   12463:    if (cross){
                   12464:           printf("Cross-");
1.191     brouard  12465:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  12466:    }
1.174     brouard  12467: #endif
                   12468: 
1.191     brouard  12469:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  12470: #if defined(__clang__)
1.191     brouard  12471:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  12472: #endif
                   12473: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  12474:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  12475: #endif
                   12476: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  12477:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  12478: #endif
                   12479: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  12480:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  12481: #endif
                   12482: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  12483:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  12484: #endif
                   12485: #if defined(_MSC_VER)
1.191     brouard  12486:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  12487: #endif
                   12488: #if defined(__PGI)
1.191     brouard  12489:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  12490: #endif
                   12491: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  12492:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  12493: #endif
1.191     brouard  12494:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  12495:    
1.167     brouard  12496: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   12497: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   12498:     // Windows (x64 and x86)
1.191     brouard  12499:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  12500: #elif __unix__ // all unices, not all compilers
                   12501:     // Unix
1.191     brouard  12502:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  12503: #elif __linux__
                   12504:     // linux
1.191     brouard  12505:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  12506: #elif __APPLE__
1.174     brouard  12507:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  12508:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  12509: #endif
                   12510: 
                   12511: /*  __MINGW32__          */
                   12512: /*  __CYGWIN__  */
                   12513: /* __MINGW64__  */
                   12514: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   12515: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   12516: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   12517: /* _WIN64  // Defined for applications for Win64. */
                   12518: /* _M_X64 // Defined for compilations that target x64 processors. */
                   12519: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  12520: 
1.167     brouard  12521: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  12522:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  12523: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  12524:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  12525: #else
1.191     brouard  12526:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  12527: #endif
                   12528: 
1.169     brouard  12529: #if defined(__GNUC__)
                   12530: # if defined(__GNUC_PATCHLEVEL__)
                   12531: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   12532:                             + __GNUC_MINOR__ * 100 \
                   12533:                             + __GNUC_PATCHLEVEL__)
                   12534: # else
                   12535: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   12536:                             + __GNUC_MINOR__ * 100)
                   12537: # endif
1.174     brouard  12538:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  12539:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  12540: 
                   12541:    if (uname(&sysInfo) != -1) {
                   12542:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  12543:         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  12544:    }
                   12545:    else
                   12546:       perror("uname() error");
1.179     brouard  12547:    //#ifndef __INTEL_COMPILER 
                   12548: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  12549:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  12550:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  12551: #endif
1.169     brouard  12552: #endif
1.172     brouard  12553: 
1.286     brouard  12554:    //   void main ()
1.172     brouard  12555:    //   {
1.169     brouard  12556: #if defined(_MSC_VER)
1.174     brouard  12557:    if (IsWow64()){
1.191     brouard  12558:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   12559:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  12560:    }
                   12561:    else{
1.191     brouard  12562:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   12563:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  12564:    }
1.172     brouard  12565:    //     printf("\nPress Enter to continue...");
                   12566:    //     getchar();
                   12567:    //   }
                   12568: 
1.169     brouard  12569: #endif
                   12570:    
1.167     brouard  12571: 
1.219     brouard  12572: }
1.136     brouard  12573: 
1.219     brouard  12574: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  12575:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  12576:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  12577:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  12578:   /* double ftolpl = 1.e-10; */
1.180     brouard  12579:   double age, agebase, agelim;
1.203     brouard  12580:   double tot;
1.180     brouard  12581: 
1.202     brouard  12582:   strcpy(filerespl,"PL_");
                   12583:   strcat(filerespl,fileresu);
                   12584:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  12585:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   12586:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  12587:   }
1.288     brouard  12588:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   12589:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  12590:   pstamp(ficrespl);
1.288     brouard  12591:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  12592:   fprintf(ficrespl,"#Age ");
                   12593:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   12594:   fprintf(ficrespl,"\n");
1.180     brouard  12595:   
1.219     brouard  12596:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  12597: 
1.219     brouard  12598:   agebase=ageminpar;
                   12599:   agelim=agemaxpar;
1.180     brouard  12600: 
1.227     brouard  12601:   /* i1=pow(2,ncoveff); */
1.234     brouard  12602:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  12603:   if (cptcovn < 1){i1=1;}
1.180     brouard  12604: 
1.337     brouard  12605:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
1.238     brouard  12606:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  12607:       k=TKresult[nres];
1.338     brouard  12608:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12609:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
                   12610:       /*       continue; */
1.235     brouard  12611: 
1.238     brouard  12612:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12613:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   12614:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   12615:       /* k=k+1; */
                   12616:       /* to clean */
1.332     brouard  12617:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  12618:       fprintf(ficrespl,"#******");
                   12619:       printf("#******");
                   12620:       fprintf(ficlog,"#******");
1.337     brouard  12621:       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  12622:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
1.337     brouard  12623:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12624:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12625:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12626:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12627:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12628:       }
                   12629:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   12630:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12631:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12632:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12633:       /* } */
1.238     brouard  12634:       fprintf(ficrespl,"******\n");
                   12635:       printf("******\n");
                   12636:       fprintf(ficlog,"******\n");
                   12637:       if(invalidvarcomb[k]){
                   12638:        printf("\nCombination (%d) ignored because no case \n",k); 
                   12639:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   12640:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   12641:        continue;
                   12642:       }
1.219     brouard  12643: 
1.238     brouard  12644:       fprintf(ficrespl,"#Age ");
1.337     brouard  12645:       /* for(j=1;j<=cptcoveff;j++) { */
                   12646:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12647:       /* } */
                   12648:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
                   12649:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12650:       }
                   12651:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   12652:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  12653:     
1.238     brouard  12654:       for (age=agebase; age<=agelim; age++){
                   12655:        /* for (age=agebase; age<=agebase; age++){ */
1.337     brouard  12656:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
                   12657:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
1.238     brouard  12658:        fprintf(ficrespl,"%.0f ",age );
1.337     brouard  12659:        /* for(j=1;j<=cptcoveff;j++) */
                   12660:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12661:        for(j=1;j<=cptcovs;j++)
                   12662:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12663:        tot=0.;
                   12664:        for(i=1; i<=nlstate;i++){
                   12665:          tot +=  prlim[i][i];
                   12666:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   12667:        }
                   12668:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   12669:       } /* Age */
                   12670:       /* was end of cptcod */
1.337     brouard  12671:     } /* nres */
                   12672:   /* } /\* for each combination *\/ */
1.219     brouard  12673:   return 0;
1.180     brouard  12674: }
                   12675: 
1.218     brouard  12676: 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  12677:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  12678:        
                   12679:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   12680:    * at any age between ageminpar and agemaxpar
                   12681:         */
1.235     brouard  12682:   int i, j, k, i1, nres=0 ;
1.217     brouard  12683:   /* double ftolpl = 1.e-10; */
                   12684:   double age, agebase, agelim;
                   12685:   double tot;
1.218     brouard  12686:   /* double ***mobaverage; */
                   12687:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  12688: 
                   12689:   strcpy(fileresplb,"PLB_");
                   12690:   strcat(fileresplb,fileresu);
                   12691:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  12692:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   12693:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  12694:   }
1.288     brouard  12695:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   12696:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  12697:   pstamp(ficresplb);
1.288     brouard  12698:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  12699:   fprintf(ficresplb,"#Age ");
                   12700:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   12701:   fprintf(ficresplb,"\n");
                   12702:   
1.218     brouard  12703:   
                   12704:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   12705:   
                   12706:   agebase=ageminpar;
                   12707:   agelim=agemaxpar;
                   12708:   
                   12709:   
1.227     brouard  12710:   i1=pow(2,cptcoveff);
1.218     brouard  12711:   if (cptcovn < 1){i1=1;}
1.227     brouard  12712:   
1.238     brouard  12713:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.338     brouard  12714:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12715:       k=TKresult[nres];
                   12716:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   12717:      /* if(i1 != 1 && TKresult[nres]!= k) */
                   12718:      /*        continue; */
                   12719:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
1.238     brouard  12720:       fprintf(ficresplb,"#******");
                   12721:       printf("#******");
                   12722:       fprintf(ficlog,"#******");
1.338     brouard  12723:       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) */
                   12724:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12725:        fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12726:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12727:       }
1.338     brouard  12728:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
                   12729:       /*       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12730:       /*       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12731:       /*       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12732:       /* } */
                   12733:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12734:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12735:       /*       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12736:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12737:       /* } */
1.238     brouard  12738:       fprintf(ficresplb,"******\n");
                   12739:       printf("******\n");
                   12740:       fprintf(ficlog,"******\n");
                   12741:       if(invalidvarcomb[k]){
                   12742:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   12743:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   12744:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   12745:        continue;
                   12746:       }
1.218     brouard  12747:     
1.238     brouard  12748:       fprintf(ficresplb,"#Age ");
1.338     brouard  12749:       for(j=1;j<=cptcovs;j++) {
                   12750:        fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12751:       }
                   12752:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   12753:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  12754:     
                   12755:     
1.238     brouard  12756:       for (age=agebase; age<=agelim; age++){
                   12757:        /* for (age=agebase; age<=agebase; age++){ */
                   12758:        if(mobilavproj > 0){
                   12759:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   12760:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12761:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  12762:        }else if (mobilavproj == 0){
                   12763:          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);
                   12764:          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);
                   12765:          exit(1);
                   12766:        }else{
                   12767:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12768:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  12769:          /* printf("TOTOT\n"); */
                   12770:           /* exit(1); */
1.238     brouard  12771:        }
                   12772:        fprintf(ficresplb,"%.0f ",age );
1.338     brouard  12773:        for(j=1;j<=cptcovs;j++)
                   12774:          fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12775:        tot=0.;
                   12776:        for(i=1; i<=nlstate;i++){
                   12777:          tot +=  bprlim[i][i];
                   12778:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   12779:        }
                   12780:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   12781:       } /* Age */
                   12782:       /* was end of cptcod */
1.255     brouard  12783:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.338     brouard  12784:     /* } /\* end of any combination *\/ */
1.238     brouard  12785:   } /* end of nres */  
1.218     brouard  12786:   /* hBijx(p, bage, fage); */
                   12787:   /* fclose(ficrespijb); */
                   12788:   
                   12789:   return 0;
1.217     brouard  12790: }
1.218     brouard  12791:  
1.180     brouard  12792: int hPijx(double *p, int bage, int fage){
                   12793:     /*------------- h Pij x at various ages ------------*/
1.336     brouard  12794:   /* to be optimized with precov */
1.180     brouard  12795:   int stepsize;
                   12796:   int agelim;
                   12797:   int hstepm;
                   12798:   int nhstepm;
1.235     brouard  12799:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  12800: 
                   12801:   double agedeb;
                   12802:   double ***p3mat;
                   12803: 
1.337     brouard  12804:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   12805:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   12806:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12807:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12808:   }
                   12809:   printf("Computing pij: result on file '%s' \n", filerespij);
                   12810:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   12811:   
                   12812:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12813:   /*if (stepm<=24) stepsize=2;*/
                   12814:   
                   12815:   agelim=AGESUP;
                   12816:   hstepm=stepsize*YEARM; /* Every year of age */
                   12817:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   12818:   
                   12819:   /* hstepm=1;   aff par mois*/
                   12820:   pstamp(ficrespij);
                   12821:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   12822:   i1= pow(2,cptcoveff);
                   12823:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12824:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12825:   /*   k=k+1;  */
                   12826:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   12827:     k=TKresult[nres];
1.338     brouard  12828:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12829:     /* for(k=1; k<=i1;k++){ */
                   12830:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   12831:     /*         continue; */
                   12832:     fprintf(ficrespij,"\n#****** ");
                   12833:     for(j=1;j<=cptcovs;j++){
                   12834:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12835:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12836:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   12837:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12838:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12839:     }
                   12840:     fprintf(ficrespij,"******\n");
                   12841:     
                   12842:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   12843:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   12844:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   12845:       
                   12846:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12847:       
                   12848:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12849:       oldm=oldms;savm=savms;
                   12850:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
                   12851:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   12852:       for(i=1; i<=nlstate;i++)
                   12853:        for(j=1; j<=nlstate+ndeath;j++)
                   12854:          fprintf(ficrespij," %1d-%1d",i,j);
                   12855:       fprintf(ficrespij,"\n");
                   12856:       for (h=0; h<=nhstepm; h++){
                   12857:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12858:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.183     brouard  12859:        for(i=1; i<=nlstate;i++)
                   12860:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12861:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.183     brouard  12862:        fprintf(ficrespij,"\n");
                   12863:       }
1.337     brouard  12864:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12865:       fprintf(ficrespij,"\n");
1.180     brouard  12866:     }
1.337     brouard  12867:   }
                   12868:   /*}*/
                   12869:   return 0;
1.180     brouard  12870: }
1.218     brouard  12871:  
                   12872:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  12873:     /*------------- h Bij x at various ages ------------*/
1.336     brouard  12874:     /* To be optimized with precov */
1.217     brouard  12875:   int stepsize;
1.218     brouard  12876:   /* int agelim; */
                   12877:        int ageminl;
1.217     brouard  12878:   int hstepm;
                   12879:   int nhstepm;
1.238     brouard  12880:   int h, i, i1, j, k, nres;
1.218     brouard  12881:        
1.217     brouard  12882:   double agedeb;
                   12883:   double ***p3mat;
1.218     brouard  12884:        
                   12885:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   12886:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   12887:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12888:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12889:   }
                   12890:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   12891:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   12892:   
                   12893:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12894:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  12895:   
1.218     brouard  12896:   /* agelim=AGESUP; */
1.289     brouard  12897:   ageminl=AGEINF; /* was 30 */
1.218     brouard  12898:   hstepm=stepsize*YEARM; /* Every year of age */
                   12899:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   12900:   
                   12901:   /* hstepm=1;   aff par mois*/
                   12902:   pstamp(ficrespijb);
1.255     brouard  12903:   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  12904:   i1= pow(2,cptcoveff);
1.218     brouard  12905:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12906:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12907:   /*   k=k+1;  */
1.238     brouard  12908:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  12909:     k=TKresult[nres];
1.338     brouard  12910:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12911:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12912:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   12913:     /*         continue; */
                   12914:     fprintf(ficrespijb,"\n#****** ");
                   12915:     for(j=1;j<=cptcovs;j++){
1.338     brouard  12916:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.337     brouard  12917:       /* for(j=1;j<=cptcoveff;j++) */
                   12918:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12919:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12920:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12921:     }
                   12922:     fprintf(ficrespijb,"******\n");
                   12923:     if(invalidvarcomb[k]){  /* Is it necessary here? */
                   12924:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   12925:       continue;
                   12926:     }
                   12927:     
                   12928:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   12929:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   12930:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   12931:       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 */
                   12932:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
                   12933:       
                   12934:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12935:       
                   12936:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   12937:       /* and memory limitations if stepm is small */
                   12938:       
                   12939:       /* oldm=oldms;savm=savms; */
                   12940:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   12941:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
                   12942:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   12943:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
                   12944:       for(i=1; i<=nlstate;i++)
                   12945:        for(j=1; j<=nlstate+ndeath;j++)
                   12946:          fprintf(ficrespijb," %1d-%1d",i,j);
                   12947:       fprintf(ficrespijb,"\n");
                   12948:       for (h=0; h<=nhstepm; h++){
                   12949:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12950:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   12951:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  12952:        for(i=1; i<=nlstate;i++)
                   12953:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12954:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.217     brouard  12955:        fprintf(ficrespijb,"\n");
1.337     brouard  12956:       }
                   12957:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12958:       fprintf(ficrespijb,"\n");
                   12959:     } /* end age deb */
                   12960:     /* } /\* end combination *\/ */
1.238     brouard  12961:   } /* end nres */
1.218     brouard  12962:   return 0;
                   12963:  } /*  hBijx */
1.217     brouard  12964: 
1.180     brouard  12965: 
1.136     brouard  12966: /***********************************************/
                   12967: /**************** Main Program *****************/
                   12968: /***********************************************/
                   12969: 
                   12970: int main(int argc, char *argv[])
                   12971: {
                   12972: #ifdef GSL
                   12973:   const gsl_multimin_fminimizer_type *T;
                   12974:   size_t iteri = 0, it;
                   12975:   int rval = GSL_CONTINUE;
                   12976:   int status = GSL_SUCCESS;
                   12977:   double ssval;
                   12978: #endif
                   12979:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  12980:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   12981:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  12982:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  12983:   int jj, ll, li, lj, lk;
1.136     brouard  12984:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  12985:   int num_filled;
1.136     brouard  12986:   int itimes;
                   12987:   int NDIM=2;
                   12988:   int vpopbased=0;
1.235     brouard  12989:   int nres=0;
1.258     brouard  12990:   int endishere=0;
1.277     brouard  12991:   int noffset=0;
1.274     brouard  12992:   int ncurrv=0; /* Temporary variable */
                   12993:   
1.164     brouard  12994:   char ca[32], cb[32];
1.136     brouard  12995:   /*  FILE *fichtm; *//* Html File */
                   12996:   /* FILE *ficgp;*/ /*Gnuplot File */
                   12997:   struct stat info;
1.191     brouard  12998:   double agedeb=0.;
1.194     brouard  12999: 
                   13000:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  13001:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  13002: 
1.165     brouard  13003:   double fret;
1.191     brouard  13004:   double dum=0.; /* Dummy variable */
1.136     brouard  13005:   double ***p3mat;
1.218     brouard  13006:   /* double ***mobaverage; */
1.319     brouard  13007:   double wald;
1.164     brouard  13008: 
1.351     brouard  13009:   char line[MAXLINE], linetmp[MAXLINE];
1.197     brouard  13010:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   13011: 
1.234     brouard  13012:   char  modeltemp[MAXLINE];
1.332     brouard  13013:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  13014:   
1.136     brouard  13015:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  13016:   char *tok, *val; /* pathtot */
1.334     brouard  13017:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.195     brouard  13018:   int c,  h , cpt, c2;
1.191     brouard  13019:   int jl=0;
                   13020:   int i1, j1, jk, stepsize=0;
1.194     brouard  13021:   int count=0;
                   13022: 
1.164     brouard  13023:   int *tab; 
1.136     brouard  13024:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  13025:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   13026:   /* double anprojf, mprojf, jprojf; */
                   13027:   /* double jintmean,mintmean,aintmean;   */
                   13028:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   13029:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   13030:   double yrfproj= 10.0; /* Number of years of forward projections */
                   13031:   double yrbproj= 10.0; /* Number of years of backward projections */
                   13032:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  13033:   int mobilav=0,popforecast=0;
1.191     brouard  13034:   int hstepm=0, nhstepm=0;
1.136     brouard  13035:   int agemortsup;
                   13036:   float  sumlpop=0.;
                   13037:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   13038:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   13039: 
1.191     brouard  13040:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  13041:   double ftolpl=FTOL;
                   13042:   double **prlim;
1.217     brouard  13043:   double **bprlim;
1.317     brouard  13044:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   13045:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  13046:   double ***paramstart; /* Matrix of starting parameter values */
                   13047:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  13048:   double **matcov; /* Matrix of covariance */
1.203     brouard  13049:   double **hess; /* Hessian matrix */
1.136     brouard  13050:   double ***delti3; /* Scale */
                   13051:   double *delti; /* Scale */
                   13052:   double ***eij, ***vareij;
                   13053:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  13054: 
1.136     brouard  13055:   double *epj, vepp;
1.164     brouard  13056: 
1.273     brouard  13057:   double dateprev1, dateprev2;
1.296     brouard  13058:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   13059:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   13060: 
1.217     brouard  13061: 
1.136     brouard  13062:   double **ximort;
1.145     brouard  13063:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  13064:   int *dcwave;
                   13065: 
1.164     brouard  13066:   char z[1]="c";
1.136     brouard  13067: 
                   13068:   /*char  *strt;*/
                   13069:   char strtend[80];
1.126     brouard  13070: 
1.164     brouard  13071: 
1.126     brouard  13072: /*   setlocale (LC_ALL, ""); */
                   13073: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   13074: /*   textdomain (PACKAGE); */
                   13075: /*   setlocale (LC_CTYPE, ""); */
                   13076: /*   setlocale (LC_MESSAGES, ""); */
                   13077: 
                   13078:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  13079:   rstart_time = time(NULL);  
                   13080:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   13081:   start_time = *localtime(&rstart_time);
1.126     brouard  13082:   curr_time=start_time;
1.157     brouard  13083:   /*tml = *localtime(&start_time.tm_sec);*/
                   13084:   /* strcpy(strstart,asctime(&tml)); */
                   13085:   strcpy(strstart,asctime(&start_time));
1.126     brouard  13086: 
                   13087: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  13088: /*  tp.tm_sec = tp.tm_sec +86400; */
                   13089: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  13090: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   13091: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   13092: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  13093: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  13094: /*   strt=asctime(&tmg); */
                   13095: /*   printf("Time(after) =%s",strstart);  */
                   13096: /*  (void) time (&time_value);
                   13097: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   13098: *  tm = *localtime(&time_value);
                   13099: *  strstart=asctime(&tm);
                   13100: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   13101: */
                   13102: 
                   13103:   nberr=0; /* Number of errors and warnings */
                   13104:   nbwarn=0;
1.184     brouard  13105: #ifdef WIN32
                   13106:   _getcwd(pathcd, size);
                   13107: #else
1.126     brouard  13108:   getcwd(pathcd, size);
1.184     brouard  13109: #endif
1.191     brouard  13110:   syscompilerinfo(0);
1.196     brouard  13111:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  13112:   if(argc <=1){
                   13113:     printf("\nEnter the parameter file name: ");
1.205     brouard  13114:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   13115:       printf("ERROR Empty parameter file name\n");
                   13116:       goto end;
                   13117:     }
1.126     brouard  13118:     i=strlen(pathr);
                   13119:     if(pathr[i-1]=='\n')
                   13120:       pathr[i-1]='\0';
1.156     brouard  13121:     i=strlen(pathr);
1.205     brouard  13122:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  13123:       pathr[i-1]='\0';
1.205     brouard  13124:     }
                   13125:     i=strlen(pathr);
                   13126:     if( i==0 ){
                   13127:       printf("ERROR Empty parameter file name\n");
                   13128:       goto end;
                   13129:     }
                   13130:     for (tok = pathr; tok != NULL; ){
1.126     brouard  13131:       printf("Pathr |%s|\n",pathr);
                   13132:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   13133:       printf("val= |%s| pathr=%s\n",val,pathr);
                   13134:       strcpy (pathtot, val);
                   13135:       if(pathr[0] == '\0') break; /* Dirty */
                   13136:     }
                   13137:   }
1.281     brouard  13138:   else if (argc<=2){
                   13139:     strcpy(pathtot,argv[1]);
                   13140:   }
1.126     brouard  13141:   else{
                   13142:     strcpy(pathtot,argv[1]);
1.281     brouard  13143:     strcpy(z,argv[2]);
                   13144:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  13145:   }
                   13146:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   13147:   /*cygwin_split_path(pathtot,path,optionfile);
                   13148:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   13149:   /* cutv(path,optionfile,pathtot,'\\');*/
                   13150: 
                   13151:   /* Split argv[0], imach program to get pathimach */
                   13152:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   13153:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   13154:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   13155:  /*   strcpy(pathimach,argv[0]); */
                   13156:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   13157:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   13158:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  13159: #ifdef WIN32
                   13160:   _chdir(path); /* Can be a relative path */
                   13161:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   13162: #else
1.126     brouard  13163:   chdir(path); /* Can be a relative path */
1.184     brouard  13164:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   13165: #endif
                   13166:   printf("Current directory %s!\n",pathcd);
1.126     brouard  13167:   strcpy(command,"mkdir ");
                   13168:   strcat(command,optionfilefiname);
                   13169:   if((outcmd=system(command)) != 0){
1.169     brouard  13170:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  13171:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   13172:     /* fclose(ficlog); */
                   13173: /*     exit(1); */
                   13174:   }
                   13175: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   13176: /*     perror("mkdir"); */
                   13177: /*   } */
                   13178: 
                   13179:   /*-------- arguments in the command line --------*/
                   13180: 
1.186     brouard  13181:   /* Main Log file */
1.126     brouard  13182:   strcat(filelog, optionfilefiname);
                   13183:   strcat(filelog,".log");    /* */
                   13184:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   13185:     printf("Problem with logfile %s\n",filelog);
                   13186:     goto end;
                   13187:   }
                   13188:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  13189:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  13190:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   13191:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   13192:  path=%s \n\
                   13193:  optionfile=%s\n\
                   13194:  optionfilext=%s\n\
1.156     brouard  13195:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  13196: 
1.197     brouard  13197:   syscompilerinfo(1);
1.167     brouard  13198: 
1.126     brouard  13199:   printf("Local time (at start):%s",strstart);
                   13200:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   13201:   fflush(ficlog);
                   13202: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  13203: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  13204: 
                   13205:   /* */
                   13206:   strcpy(fileres,"r");
                   13207:   strcat(fileres, optionfilefiname);
1.201     brouard  13208:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  13209:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  13210:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  13211: 
1.186     brouard  13212:   /* Main ---------arguments file --------*/
1.126     brouard  13213: 
                   13214:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  13215:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   13216:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  13217:     fflush(ficlog);
1.149     brouard  13218:     /* goto end; */
                   13219:     exit(70); 
1.126     brouard  13220:   }
                   13221: 
                   13222:   strcpy(filereso,"o");
1.201     brouard  13223:   strcat(filereso,fileresu);
1.126     brouard  13224:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   13225:     printf("Problem with Output resultfile: %s\n", filereso);
                   13226:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   13227:     fflush(ficlog);
                   13228:     goto end;
                   13229:   }
1.278     brouard  13230:       /*-------- Rewriting parameter file ----------*/
                   13231:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   13232:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   13233:   strcat(rfileres,".");    /* */
                   13234:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   13235:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   13236:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   13237:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   13238:     fflush(ficlog);
                   13239:     goto end;
                   13240:   }
                   13241:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  13242: 
1.278     brouard  13243:                                      
1.126     brouard  13244:   /* Reads comments: lines beginning with '#' */
                   13245:   numlinepar=0;
1.277     brouard  13246:   /* Is it a BOM UTF-8 Windows file? */
                   13247:   /* First parameter line */
1.197     brouard  13248:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  13249:     noffset=0;
                   13250:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   13251:     {
                   13252:       noffset=noffset+3;
                   13253:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   13254:     }
1.302     brouard  13255: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   13256:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  13257:     {
                   13258:       noffset=noffset+2;
                   13259:       printf("# File is an UTF16BE BOM file\n");
                   13260:     }
                   13261:     else if( line[0] == 0 && line[1] == 0)
                   13262:     {
                   13263:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   13264:        noffset=noffset+4;
                   13265:        printf("# File is an UTF16BE BOM file\n");
                   13266:       }
                   13267:     } else{
                   13268:       ;/*printf(" Not a BOM file\n");*/
                   13269:     }
                   13270:   
1.197     brouard  13271:     /* If line starts with a # it is a comment */
1.277     brouard  13272:     if (line[noffset] == '#') {
1.197     brouard  13273:       numlinepar++;
                   13274:       fputs(line,stdout);
                   13275:       fputs(line,ficparo);
1.278     brouard  13276:       fputs(line,ficres);
1.197     brouard  13277:       fputs(line,ficlog);
                   13278:       continue;
                   13279:     }else
                   13280:       break;
                   13281:   }
                   13282:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   13283:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   13284:     if (num_filled != 5) {
                   13285:       printf("Should be 5 parameters\n");
1.283     brouard  13286:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  13287:     }
1.126     brouard  13288:     numlinepar++;
1.197     brouard  13289:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  13290:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   13291:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   13292:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  13293:   }
                   13294:   /* Second parameter line */
                   13295:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  13296:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   13297:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  13298:     if (line[0] == '#') {
                   13299:       numlinepar++;
1.283     brouard  13300:       printf("%s",line);
                   13301:       fprintf(ficres,"%s",line);
                   13302:       fprintf(ficparo,"%s",line);
                   13303:       fprintf(ficlog,"%s",line);
1.197     brouard  13304:       continue;
                   13305:     }else
                   13306:       break;
                   13307:   }
1.223     brouard  13308:   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", \
                   13309:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   13310:     if (num_filled != 11) {
                   13311:       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  13312:       printf("but line=%s\n",line);
1.283     brouard  13313:       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");
                   13314:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  13315:     }
1.286     brouard  13316:     if( lastpass > maxwav){
                   13317:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   13318:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   13319:       fflush(ficlog);
                   13320:       goto end;
                   13321:     }
                   13322:       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  13323:     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  13324:     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  13325:     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  13326:   }
1.203     brouard  13327:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  13328:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  13329:   /* Third parameter line */
                   13330:   while(fgets(line, MAXLINE, ficpar)) {
                   13331:     /* If line starts with a # it is a comment */
                   13332:     if (line[0] == '#') {
                   13333:       numlinepar++;
1.283     brouard  13334:       printf("%s",line);
                   13335:       fprintf(ficres,"%s",line);
                   13336:       fprintf(ficparo,"%s",line);
                   13337:       fprintf(ficlog,"%s",line);
1.197     brouard  13338:       continue;
                   13339:     }else
                   13340:       break;
                   13341:   }
1.351     brouard  13342:   if((num_filled=sscanf(line,"model=%[^.\n]", model)) !=EOF){ /* Every character after model but dot and  return */
                   13343:     if (num_filled != 1){
                   13344:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   13345:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   13346:       model[0]='\0';
                   13347:       goto end;
                   13348:     }else{
                   13349:       trimbtab(linetmp,line); /* Trims multiple blanks in line */
                   13350:       strcpy(line, linetmp);
                   13351:     }
                   13352:   }
                   13353:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){ /* Every character after 1+age but dot and  return */
1.279     brouard  13354:     if (num_filled != 1){
1.302     brouard  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);
1.197     brouard  13357:       model[0]='\0';
                   13358:       goto end;
                   13359:     }
                   13360:     else{
                   13361:       if (model[0]=='+'){
                   13362:        for(i=1; i<=strlen(model);i++)
                   13363:          modeltemp[i-1]=model[i];
1.201     brouard  13364:        strcpy(model,modeltemp); 
1.197     brouard  13365:       }
                   13366:     }
1.338     brouard  13367:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  13368:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  13369:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   13370:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   13371:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  13372:   }
                   13373:   /* 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); */
                   13374:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   13375:   /* 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  13376:   /* 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); */
                   13377:   /* 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  13378:   fflush(ficlog);
1.190     brouard  13379:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   13380:   if(model[0]=='#'){
1.279     brouard  13381:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   13382:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   13383:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  13384:     if(mle != -1){
1.279     brouard  13385:       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  13386:       exit(1);
                   13387:     }
                   13388:   }
1.126     brouard  13389:   while((c=getc(ficpar))=='#' && c!= EOF){
                   13390:     ungetc(c,ficpar);
                   13391:     fgets(line, MAXLINE, ficpar);
                   13392:     numlinepar++;
1.195     brouard  13393:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   13394:       z[0]=line[1];
1.342     brouard  13395:     }else if(line[1]=='d'){ /* For debugging individual values of covariates in ficresilk */
1.343     brouard  13396:       debugILK=1;printf("DebugILK\n");
1.195     brouard  13397:     }
                   13398:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  13399:     fputs(line, stdout);
                   13400:     //puts(line);
1.126     brouard  13401:     fputs(line,ficparo);
                   13402:     fputs(line,ficlog);
                   13403:   }
                   13404:   ungetc(c,ficpar);
                   13405: 
                   13406:    
1.290     brouard  13407:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   13408:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   13409:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
1.341     brouard  13410:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /\**< Time varying covariate (dummy and quantitative)*\/ */
                   13411:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /**< Might be better */
1.136     brouard  13412:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   13413:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   13414:      v1+v2*age+v2*v3 makes cptcovn = 3
                   13415:   */
                   13416:   if (strlen(model)>1) 
1.187     brouard  13417:     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  13418:   else
1.187     brouard  13419:     ncovmodel=2; /* Constant and age */
1.133     brouard  13420:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   13421:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  13422:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   13423:     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);
                   13424:     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);
                   13425:     fflush(stdout);
                   13426:     fclose (ficlog);
                   13427:     goto end;
                   13428:   }
1.126     brouard  13429:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   13430:   delti=delti3[1][1];
                   13431:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   13432:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  13433: /* We could also provide initial parameters values giving by simple logistic regression 
                   13434:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   13435:       /* for(i=1;i<nlstate;i++){ */
                   13436:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   13437:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   13438:       /* } */
1.126     brouard  13439:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  13440:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   13441:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  13442:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   13443:     fclose (ficparo);
                   13444:     fclose (ficlog);
                   13445:     goto end;
                   13446:     exit(0);
1.220     brouard  13447:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  13448:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  13449:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   13450:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  13451:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   13452:     matcov=matrix(1,npar,1,npar);
1.203     brouard  13453:     hess=matrix(1,npar,1,npar);
1.220     brouard  13454:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  13455:     /* Read guessed parameters */
1.126     brouard  13456:     /* Reads comments: lines beginning with '#' */
                   13457:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13458:       ungetc(c,ficpar);
                   13459:       fgets(line, MAXLINE, ficpar);
                   13460:       numlinepar++;
1.141     brouard  13461:       fputs(line,stdout);
1.126     brouard  13462:       fputs(line,ficparo);
                   13463:       fputs(line,ficlog);
                   13464:     }
                   13465:     ungetc(c,ficpar);
                   13466:     
                   13467:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  13468:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  13469:     for(i=1; i <=nlstate; i++){
1.234     brouard  13470:       j=0;
1.126     brouard  13471:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  13472:        if(jj==i) continue;
                   13473:        j++;
1.292     brouard  13474:        while((c=getc(ficpar))=='#' && c!= EOF){
                   13475:          ungetc(c,ficpar);
                   13476:          fgets(line, MAXLINE, ficpar);
                   13477:          numlinepar++;
                   13478:          fputs(line,stdout);
                   13479:          fputs(line,ficparo);
                   13480:          fputs(line,ficlog);
                   13481:        }
                   13482:        ungetc(c,ficpar);
1.234     brouard  13483:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   13484:        if ((i1 != i) || (j1 != jj)){
                   13485:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  13486: It might be a problem of design; if ncovcol and the model are correct\n \
                   13487: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  13488:          exit(1);
                   13489:        }
                   13490:        fprintf(ficparo,"%1d%1d",i1,j1);
                   13491:        if(mle==1)
                   13492:          printf("%1d%1d",i,jj);
                   13493:        fprintf(ficlog,"%1d%1d",i,jj);
                   13494:        for(k=1; k<=ncovmodel;k++){
                   13495:          fscanf(ficpar," %lf",&param[i][j][k]);
                   13496:          if(mle==1){
                   13497:            printf(" %lf",param[i][j][k]);
                   13498:            fprintf(ficlog," %lf",param[i][j][k]);
                   13499:          }
                   13500:          else
                   13501:            fprintf(ficlog," %lf",param[i][j][k]);
                   13502:          fprintf(ficparo," %lf",param[i][j][k]);
                   13503:        }
                   13504:        fscanf(ficpar,"\n");
                   13505:        numlinepar++;
                   13506:        if(mle==1)
                   13507:          printf("\n");
                   13508:        fprintf(ficlog,"\n");
                   13509:        fprintf(ficparo,"\n");
1.126     brouard  13510:       }
                   13511:     }  
                   13512:     fflush(ficlog);
1.234     brouard  13513:     
1.251     brouard  13514:     /* Reads parameters values */
1.126     brouard  13515:     p=param[1][1];
1.251     brouard  13516:     pstart=paramstart[1][1];
1.126     brouard  13517:     
                   13518:     /* Reads comments: lines beginning with '#' */
                   13519:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13520:       ungetc(c,ficpar);
                   13521:       fgets(line, MAXLINE, ficpar);
                   13522:       numlinepar++;
1.141     brouard  13523:       fputs(line,stdout);
1.126     brouard  13524:       fputs(line,ficparo);
                   13525:       fputs(line,ficlog);
                   13526:     }
                   13527:     ungetc(c,ficpar);
                   13528: 
                   13529:     for(i=1; i <=nlstate; i++){
                   13530:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  13531:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   13532:        if ( (i1-i) * (j1-j) != 0){
                   13533:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   13534:          exit(1);
                   13535:        }
                   13536:        printf("%1d%1d",i,j);
                   13537:        fprintf(ficparo,"%1d%1d",i1,j1);
                   13538:        fprintf(ficlog,"%1d%1d",i1,j1);
                   13539:        for(k=1; k<=ncovmodel;k++){
                   13540:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   13541:          printf(" %le",delti3[i][j][k]);
                   13542:          fprintf(ficparo," %le",delti3[i][j][k]);
                   13543:          fprintf(ficlog," %le",delti3[i][j][k]);
                   13544:        }
                   13545:        fscanf(ficpar,"\n");
                   13546:        numlinepar++;
                   13547:        printf("\n");
                   13548:        fprintf(ficparo,"\n");
                   13549:        fprintf(ficlog,"\n");
1.126     brouard  13550:       }
                   13551:     }
                   13552:     fflush(ficlog);
1.234     brouard  13553:     
1.145     brouard  13554:     /* Reads covariance matrix */
1.126     brouard  13555:     delti=delti3[1][1];
1.220     brouard  13556:                
                   13557:                
1.126     brouard  13558:     /* 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  13559:                
1.126     brouard  13560:     /* Reads comments: lines beginning with '#' */
                   13561:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13562:       ungetc(c,ficpar);
                   13563:       fgets(line, MAXLINE, ficpar);
                   13564:       numlinepar++;
1.141     brouard  13565:       fputs(line,stdout);
1.126     brouard  13566:       fputs(line,ficparo);
                   13567:       fputs(line,ficlog);
                   13568:     }
                   13569:     ungetc(c,ficpar);
1.220     brouard  13570:                
1.126     brouard  13571:     matcov=matrix(1,npar,1,npar);
1.203     brouard  13572:     hess=matrix(1,npar,1,npar);
1.131     brouard  13573:     for(i=1; i <=npar; i++)
                   13574:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  13575:                
1.194     brouard  13576:     /* Scans npar lines */
1.126     brouard  13577:     for(i=1; i <=npar; i++){
1.226     brouard  13578:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  13579:       if(count != 3){
1.226     brouard  13580:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  13581: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   13582: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  13583:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  13584: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   13585: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  13586:        exit(1);
1.220     brouard  13587:       }else{
1.226     brouard  13588:        if(mle==1)
                   13589:          printf("%1d%1d%d",i1,j1,jk);
                   13590:       }
                   13591:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   13592:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  13593:       for(j=1; j <=i; j++){
1.226     brouard  13594:        fscanf(ficpar," %le",&matcov[i][j]);
                   13595:        if(mle==1){
                   13596:          printf(" %.5le",matcov[i][j]);
                   13597:        }
                   13598:        fprintf(ficlog," %.5le",matcov[i][j]);
                   13599:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  13600:       }
                   13601:       fscanf(ficpar,"\n");
                   13602:       numlinepar++;
                   13603:       if(mle==1)
1.220     brouard  13604:                                printf("\n");
1.126     brouard  13605:       fprintf(ficlog,"\n");
                   13606:       fprintf(ficparo,"\n");
                   13607:     }
1.194     brouard  13608:     /* End of read covariance matrix npar lines */
1.126     brouard  13609:     for(i=1; i <=npar; i++)
                   13610:       for(j=i+1;j<=npar;j++)
1.226     brouard  13611:        matcov[i][j]=matcov[j][i];
1.126     brouard  13612:     
                   13613:     if(mle==1)
                   13614:       printf("\n");
                   13615:     fprintf(ficlog,"\n");
                   13616:     
                   13617:     fflush(ficlog);
                   13618:     
                   13619:   }    /* End of mle != -3 */
1.218     brouard  13620:   
1.186     brouard  13621:   /*  Main data
                   13622:    */
1.290     brouard  13623:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   13624:   /* num=lvector(1,n); */
                   13625:   /* moisnais=vector(1,n); */
                   13626:   /* annais=vector(1,n); */
                   13627:   /* moisdc=vector(1,n); */
                   13628:   /* andc=vector(1,n); */
                   13629:   /* weight=vector(1,n); */
                   13630:   /* agedc=vector(1,n); */
                   13631:   /* cod=ivector(1,n); */
                   13632:   /* for(i=1;i<=n;i++){ */
                   13633:   num=lvector(firstobs,lastobs);
                   13634:   moisnais=vector(firstobs,lastobs);
                   13635:   annais=vector(firstobs,lastobs);
                   13636:   moisdc=vector(firstobs,lastobs);
                   13637:   andc=vector(firstobs,lastobs);
                   13638:   weight=vector(firstobs,lastobs);
                   13639:   agedc=vector(firstobs,lastobs);
                   13640:   cod=ivector(firstobs,lastobs);
                   13641:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  13642:     num[i]=0;
                   13643:     moisnais[i]=0;
                   13644:     annais[i]=0;
                   13645:     moisdc[i]=0;
                   13646:     andc[i]=0;
                   13647:     agedc[i]=0;
                   13648:     cod[i]=0;
                   13649:     weight[i]=1.0; /* Equal weights, 1 by default */
                   13650:   }
1.290     brouard  13651:   mint=matrix(1,maxwav,firstobs,lastobs);
                   13652:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  13653:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
1.336     brouard  13654:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
1.126     brouard  13655:   tab=ivector(1,NCOVMAX);
1.144     brouard  13656:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  13657:   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  13658: 
1.136     brouard  13659:   /* Reads data from file datafile */
                   13660:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   13661:     goto end;
                   13662: 
                   13663:   /* Calculation of the number of parameters from char model */
1.234     brouard  13664:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  13665:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   13666:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   13667:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   13668:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  13669:   */
                   13670:   
                   13671:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   13672:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  13673:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335     brouard  13674:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  13675:   TvarsD=ivector(1,NCOVMAX); /*  */
                   13676:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   13677:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  13678:   TvarF=ivector(1,NCOVMAX); /*  */
                   13679:   TvarFind=ivector(1,NCOVMAX); /*  */
                   13680:   TvarV=ivector(1,NCOVMAX); /*  */
                   13681:   TvarVind=ivector(1,NCOVMAX); /*  */
                   13682:   TvarA=ivector(1,NCOVMAX); /*  */
                   13683:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  13684:   TvarFD=ivector(1,NCOVMAX); /*  */
                   13685:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   13686:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   13687:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   13688:   TvarVD=ivector(1,NCOVMAX); /*  */
                   13689:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   13690:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   13691:   TvarVQind=ivector(1,NCOVMAX); /*  */
1.339     brouard  13692:   TvarVV=ivector(1,NCOVMAX); /*  */
                   13693:   TvarVVind=ivector(1,NCOVMAX); /*  */
1.349     brouard  13694:   TvarVVA=ivector(1,NCOVMAX); /*  */
                   13695:   TvarVVAind=ivector(1,NCOVMAX); /*  */
                   13696:   TvarAVVA=ivector(1,NCOVMAX); /*  */
                   13697:   TvarAVVAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  13698: 
1.230     brouard  13699:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  13700:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  13701:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   13702:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   13703:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.349     brouard  13704:   DummyV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   13705:   FixedV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   13706: 
1.137     brouard  13707:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   13708:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   13709:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   13710:   */
                   13711:   /* For model-covariate k tells which data-covariate to use but
                   13712:     because this model-covariate is a construction we invent a new column
                   13713:     ncovcol + k1
                   13714:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   13715:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  13716:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   13717:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  13718:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   13719:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  13720:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  13721:   */
1.145     brouard  13722:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   13723:   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  13724:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   13725:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.351     brouard  13726:   Tvardk=imatrix(0,NCOVMAX,1,2);
1.145     brouard  13727:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  13728:                         4 covariates (3 plus signs)
                   13729:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  13730:                           */  
                   13731:   for(i=1;i<NCOVMAX;i++)
                   13732:     Tage[i]=0;
1.230     brouard  13733:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  13734:                                * individual dummy, fixed or varying:
                   13735:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   13736:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  13737:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   13738:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   13739:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   13740:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   13741:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  13742:                                * individual quantitative, fixed or varying:
                   13743:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   13744:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   13745:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.349     brouard  13746: 
                   13747: /* Probably useless zeroes */
                   13748:   for(i=1;i<NCOVMAX;i++){
                   13749:     DummyV[i]=0;
                   13750:     FixedV[i]=0;
                   13751:   }
                   13752: 
                   13753:   for(i=1; i <=ncovcol;i++){
                   13754:     DummyV[i]=0;
                   13755:     FixedV[i]=0;
                   13756:   }
                   13757:   for(i=ncovcol+1; i <=ncovcol+nqv;i++){
                   13758:     DummyV[i]=1;
                   13759:     FixedV[i]=0;
                   13760:   }
                   13761:   for(i=ncovcol+nqv+1; i <=ncovcol+nqv+ntv;i++){
                   13762:     DummyV[i]=0;
                   13763:     FixedV[i]=1;
                   13764:   }
                   13765:   for(i=ncovcol+nqv+ntv+1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   13766:     DummyV[i]=1;
                   13767:     FixedV[i]=1;
                   13768:   }
                   13769:   for(i=1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   13770:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",i,i,DummyV[i],i,FixedV[i]);
                   13771:     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]);
                   13772:   }
                   13773: 
                   13774: 
                   13775: 
1.186     brouard  13776: /* Main decodemodel */
                   13777: 
1.187     brouard  13778: 
1.223     brouard  13779:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  13780:     goto end;
                   13781: 
1.137     brouard  13782:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   13783:     nbwarn++;
                   13784:     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); 
                   13785:     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); 
                   13786:   }
1.136     brouard  13787:     /*  if(mle==1){*/
1.137     brouard  13788:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   13789:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  13790:   }
                   13791: 
                   13792:     /*-calculation of age at interview from date of interview and age at death -*/
                   13793:   agev=matrix(1,maxwav,1,imx);
                   13794: 
                   13795:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   13796:     goto end;
                   13797: 
1.126     brouard  13798: 
1.136     brouard  13799:   agegomp=(int)agemin;
1.290     brouard  13800:   free_vector(moisnais,firstobs,lastobs);
                   13801:   free_vector(annais,firstobs,lastobs);
1.126     brouard  13802:   /* free_matrix(mint,1,maxwav,1,n);
                   13803:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  13804:   /* free_vector(moisdc,1,n); */
                   13805:   /* free_vector(andc,1,n); */
1.145     brouard  13806:   /* */
                   13807:   
1.126     brouard  13808:   wav=ivector(1,imx);
1.214     brouard  13809:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13810:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13811:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13812:   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.*/
                   13813:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   13814:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  13815:    
                   13816:   /* Concatenates waves */
1.214     brouard  13817:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   13818:      Death is a valid wave (if date is known).
                   13819:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   13820:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   13821:      and mw[mi+1][i]. dh depends on stepm.
                   13822:   */
                   13823: 
1.126     brouard  13824:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  13825:   /* Concatenates waves */
1.145     brouard  13826:  
1.290     brouard  13827:   free_vector(moisdc,firstobs,lastobs);
                   13828:   free_vector(andc,firstobs,lastobs);
1.215     brouard  13829: 
1.126     brouard  13830:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   13831:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   13832:   ncodemax[1]=1;
1.145     brouard  13833:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  13834:   cptcoveff=0;
1.220     brouard  13835:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335     brouard  13836:     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  13837:   }
                   13838:   
                   13839:   ncovcombmax=pow(2,cptcoveff);
1.338     brouard  13840:   invalidvarcomb=ivector(0, ncovcombmax); 
                   13841:   for(i=0;i<ncovcombmax;i++)
1.227     brouard  13842:     invalidvarcomb[i]=0;
                   13843:   
1.211     brouard  13844:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  13845:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  13846:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  13847:   
1.200     brouard  13848:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  13849:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  13850:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  13851:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   13852:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   13853:    * (currently 0 or 1) in the data.
                   13854:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   13855:    * corresponding modality (h,j).
                   13856:    */
                   13857: 
1.145     brouard  13858:   h=0;
                   13859:   /*if (cptcovn > 0) */
1.126     brouard  13860:   m=pow(2,cptcoveff);
                   13861:  
1.144     brouard  13862:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  13863:           * For k=4 covariates, h goes from 1 to m=2**k
                   13864:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   13865:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  13866:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   13867:           *______________________________   *______________________
                   13868:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   13869:           *     2     2     1     1     1   *     1     0  0  0  1 
                   13870:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   13871:           *     4     2     2     1     1   *     3     0  0  1  1 
                   13872:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   13873:           *     6     2     1     2     1   *     5     0  1  0  1 
                   13874:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   13875:           *     8     2     2     2     1   *     7     0  1  1  1 
                   13876:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   13877:           *    10     2     1     1     2   *     9     1  0  0  1 
                   13878:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   13879:           *    12     2     2     1     2   *    11     1  0  1  1 
                   13880:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   13881:           *    14     2     1     2     2   *    13     1  1  0  1 
                   13882:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   13883:           *    16     2     2     2     2   *    15     1  1  1  1          
                   13884:           */                                     
1.212     brouard  13885:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  13886:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   13887:      * and the value of each covariate?
                   13888:      * V1=1, V2=1, V3=2, V4=1 ?
                   13889:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   13890:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   13891:      * In order to get the real value in the data, we use nbcode
                   13892:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   13893:      * We are keeping this crazy system in order to be able (in the future?) 
                   13894:      * to have more than 2 values (0 or 1) for a covariate.
                   13895:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   13896:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   13897:      *              bbbbbbbb
                   13898:      *              76543210     
                   13899:      *   h-1        00000101 (6-1=5)
1.219     brouard  13900:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  13901:      *           &
                   13902:      *     1        00000001 (1)
1.219     brouard  13903:      *              00000000        = 1 & ((h-1) >> (k-1))
                   13904:      *          +1= 00000001 =1 
1.211     brouard  13905:      *
                   13906:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   13907:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   13908:      *    >>k'            11
                   13909:      *          &   00000001
                   13910:      *            = 00000001
                   13911:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   13912:      * Reverse h=6 and m=16?
                   13913:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   13914:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   13915:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   13916:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   13917:      * V3=decodtabm(14,3,2**4)=2
                   13918:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   13919:      *(h-1) >> (j-1)    0011 =13 >> 2
                   13920:      *          &1 000000001
                   13921:      *           = 000000001
                   13922:      *         +1= 000000010 =2
                   13923:      *                  2211
                   13924:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   13925:      *                  V3=2
1.220     brouard  13926:                 * codtabm and decodtabm are identical
1.211     brouard  13927:      */
                   13928: 
1.145     brouard  13929: 
                   13930:  free_ivector(Ndum,-1,NCOVMAX);
                   13931: 
                   13932: 
1.126     brouard  13933:     
1.186     brouard  13934:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  13935:   strcpy(optionfilegnuplot,optionfilefiname);
                   13936:   if(mle==-3)
1.201     brouard  13937:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  13938:   strcat(optionfilegnuplot,".gp");
                   13939: 
                   13940:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   13941:     printf("Problem with file %s",optionfilegnuplot);
                   13942:   }
                   13943:   else{
1.204     brouard  13944:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  13945:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  13946:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   13947:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  13948:   }
                   13949:   /*  fclose(ficgp);*/
1.186     brouard  13950: 
                   13951: 
                   13952:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  13953: 
                   13954:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   13955:   if(mle==-3)
1.201     brouard  13956:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  13957:   strcat(optionfilehtm,".htm");
                   13958:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  13959:     printf("Problem with %s \n",optionfilehtm);
                   13960:     exit(0);
1.126     brouard  13961:   }
                   13962: 
                   13963:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   13964:   strcat(optionfilehtmcov,"-cov.htm");
                   13965:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   13966:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   13967:   }
                   13968:   else{
                   13969:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   13970: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13971: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  13972:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   13973:   }
                   13974: 
1.335     brouard  13975:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   13976: <title>IMaCh %s</title></head>\n\
                   13977:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   13978: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   13979: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   13980: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   13981: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   13982:   
                   13983:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13984: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  13985: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.337     brouard  13986: 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  13987: \n\
                   13988: <hr  size=\"2\" color=\"#EC5E5E\">\
                   13989:  <ul><li><h4>Parameter files</h4>\n\
                   13990:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   13991:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   13992:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   13993:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   13994:  - Date and time at start: %s</ul>\n",\
1.335     brouard  13995:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  13996:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   13997:          fileres,fileres,\
                   13998:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   13999:   fflush(fichtm);
                   14000: 
                   14001:   strcpy(pathr,path);
                   14002:   strcat(pathr,optionfilefiname);
1.184     brouard  14003: #ifdef WIN32
                   14004:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   14005: #else
1.126     brouard  14006:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  14007: #endif
                   14008:          
1.126     brouard  14009:   
1.220     brouard  14010:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   14011:                 and for any valid combination of covariates
1.126     brouard  14012:      and prints on file fileres'p'. */
1.251     brouard  14013:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  14014:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  14015: 
                   14016:   fprintf(fichtm,"\n");
1.286     brouard  14017:   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  14018:          ftol, stepm);
                   14019:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   14020:   ncurrv=1;
                   14021:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   14022:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   14023:   ncurrv=i;
                   14024:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  14025:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  14026:   ncurrv=i;
                   14027:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  14028:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  14029:   ncurrv=i;
                   14030:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   14031:   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", \
                   14032:           nlstate, ndeath, maxwav, mle, weightopt);
                   14033: 
                   14034:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   14035: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   14036: 
                   14037:   
1.317     brouard  14038:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  14039: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   14040: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  14041:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  14042:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  14043:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14044:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14045:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14046:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  14047: 
1.126     brouard  14048:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   14049:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   14050:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   14051: 
                   14052:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  14053:   /* For mortality only */
1.126     brouard  14054:   if (mle==-3){
1.136     brouard  14055:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  14056:     for(i=1;i<=NDIM;i++)
                   14057:       for(j=1;j<=NDIM;j++)
                   14058:        ximort[i][j]=0.;
1.186     brouard  14059:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  14060:     cens=ivector(firstobs,lastobs);
                   14061:     ageexmed=vector(firstobs,lastobs);
                   14062:     agecens=vector(firstobs,lastobs);
                   14063:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  14064:                
1.126     brouard  14065:     for (i=1; i<=imx; i++){
                   14066:       dcwave[i]=-1;
                   14067:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  14068:        if (s[m][i]>nlstate) {
                   14069:          dcwave[i]=m;
                   14070:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   14071:          break;
                   14072:        }
1.126     brouard  14073:     }
1.226     brouard  14074:     
1.126     brouard  14075:     for (i=1; i<=imx; i++) {
                   14076:       if (wav[i]>0){
1.226     brouard  14077:        ageexmed[i]=agev[mw[1][i]][i];
                   14078:        j=wav[i];
                   14079:        agecens[i]=1.; 
                   14080:        
                   14081:        if (ageexmed[i]> 1 && wav[i] > 0){
                   14082:          agecens[i]=agev[mw[j][i]][i];
                   14083:          cens[i]= 1;
                   14084:        }else if (ageexmed[i]< 1) 
                   14085:          cens[i]= -1;
                   14086:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   14087:          cens[i]=0 ;
1.126     brouard  14088:       }
                   14089:       else cens[i]=-1;
                   14090:     }
                   14091:     
                   14092:     for (i=1;i<=NDIM;i++) {
                   14093:       for (j=1;j<=NDIM;j++)
1.226     brouard  14094:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  14095:     }
                   14096:     
1.302     brouard  14097:     p[1]=0.0268; p[NDIM]=0.083;
                   14098:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  14099:     
                   14100:     
1.136     brouard  14101: #ifdef GSL
                   14102:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  14103: #else
1.126     brouard  14104:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  14105: #endif
1.201     brouard  14106:     strcpy(filerespow,"POW-MORT_"); 
                   14107:     strcat(filerespow,fileresu);
1.126     brouard  14108:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   14109:       printf("Problem with resultfile: %s\n", filerespow);
                   14110:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   14111:     }
1.136     brouard  14112: #ifdef GSL
                   14113:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  14114: #else
1.126     brouard  14115:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  14116: #endif
1.126     brouard  14117:     /*  for (i=1;i<=nlstate;i++)
                   14118:        for(j=1;j<=nlstate+ndeath;j++)
                   14119:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   14120:     */
                   14121:     fprintf(ficrespow,"\n");
1.136     brouard  14122: #ifdef GSL
                   14123:     /* gsl starts here */ 
                   14124:     T = gsl_multimin_fminimizer_nmsimplex;
                   14125:     gsl_multimin_fminimizer *sfm = NULL;
                   14126:     gsl_vector *ss, *x;
                   14127:     gsl_multimin_function minex_func;
                   14128: 
                   14129:     /* Initial vertex size vector */
                   14130:     ss = gsl_vector_alloc (NDIM);
                   14131:     
                   14132:     if (ss == NULL){
                   14133:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   14134:     }
                   14135:     /* Set all step sizes to 1 */
                   14136:     gsl_vector_set_all (ss, 0.001);
                   14137: 
                   14138:     /* Starting point */
1.126     brouard  14139:     
1.136     brouard  14140:     x = gsl_vector_alloc (NDIM);
                   14141:     
                   14142:     if (x == NULL){
                   14143:       gsl_vector_free(ss);
                   14144:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   14145:     }
                   14146:   
                   14147:     /* Initialize method and iterate */
                   14148:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  14149:     /*     gsl_vector_set(x, 0, 0.0268); */
                   14150:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  14151:     gsl_vector_set(x, 0, p[1]);
                   14152:     gsl_vector_set(x, 1, p[2]);
                   14153: 
                   14154:     minex_func.f = &gompertz_f;
                   14155:     minex_func.n = NDIM;
                   14156:     minex_func.params = (void *)&p; /* ??? */
                   14157:     
                   14158:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   14159:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   14160:     
                   14161:     printf("Iterations beginning .....\n\n");
                   14162:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   14163: 
                   14164:     iteri=0;
                   14165:     while (rval == GSL_CONTINUE){
                   14166:       iteri++;
                   14167:       status = gsl_multimin_fminimizer_iterate(sfm);
                   14168:       
                   14169:       if (status) printf("error: %s\n", gsl_strerror (status));
                   14170:       fflush(0);
                   14171:       
                   14172:       if (status) 
                   14173:         break;
                   14174:       
                   14175:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   14176:       ssval = gsl_multimin_fminimizer_size (sfm);
                   14177:       
                   14178:       if (rval == GSL_SUCCESS)
                   14179:         printf ("converged to a local maximum at\n");
                   14180:       
                   14181:       printf("%5d ", iteri);
                   14182:       for (it = 0; it < NDIM; it++){
                   14183:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   14184:       }
                   14185:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   14186:     }
                   14187:     
                   14188:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   14189:     
                   14190:     gsl_vector_free(x); /* initial values */
                   14191:     gsl_vector_free(ss); /* inital step size */
                   14192:     for (it=0; it<NDIM; it++){
                   14193:       p[it+1]=gsl_vector_get(sfm->x,it);
                   14194:       fprintf(ficrespow," %.12lf", p[it]);
                   14195:     }
                   14196:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   14197: #endif
                   14198: #ifdef POWELL
                   14199:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   14200: #endif  
1.126     brouard  14201:     fclose(ficrespow);
                   14202:     
1.203     brouard  14203:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  14204: 
                   14205:     for(i=1; i <=NDIM; i++)
                   14206:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  14207:                                matcov[i][j]=matcov[j][i];
1.126     brouard  14208:     
                   14209:     printf("\nCovariance matrix\n ");
1.203     brouard  14210:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  14211:     for(i=1; i <=NDIM; i++) {
                   14212:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  14213:                                printf("%f ",matcov[i][j]);
                   14214:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  14215:       }
1.203     brouard  14216:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  14217:     }
                   14218:     
                   14219:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  14220:     for (i=1;i<=NDIM;i++) {
1.126     brouard  14221:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  14222:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   14223:     }
1.302     brouard  14224:     lsurv=vector(agegomp,AGESUP);
                   14225:     lpop=vector(agegomp,AGESUP);
                   14226:     tpop=vector(agegomp,AGESUP);
1.126     brouard  14227:     lsurv[agegomp]=100000;
                   14228:     
                   14229:     for (k=agegomp;k<=AGESUP;k++) {
                   14230:       agemortsup=k;
                   14231:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   14232:     }
                   14233:     
                   14234:     for (k=agegomp;k<agemortsup;k++)
                   14235:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   14236:     
                   14237:     for (k=agegomp;k<agemortsup;k++){
                   14238:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   14239:       sumlpop=sumlpop+lpop[k];
                   14240:     }
                   14241:     
                   14242:     tpop[agegomp]=sumlpop;
                   14243:     for (k=agegomp;k<(agemortsup-3);k++){
                   14244:       /*  tpop[k+1]=2;*/
                   14245:       tpop[k+1]=tpop[k]-lpop[k];
                   14246:     }
                   14247:     
                   14248:     
                   14249:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   14250:     for (k=agegomp;k<(agemortsup-2);k++) 
                   14251:       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]);
                   14252:     
                   14253:     
                   14254:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  14255:                ageminpar=50;
                   14256:                agemaxpar=100;
1.194     brouard  14257:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   14258:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   14259: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14260: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   14261:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   14262: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14263: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  14264:     }else{
                   14265:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   14266:                        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  14267:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  14268:                }
1.201     brouard  14269:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  14270:                     stepm, weightopt,\
                   14271:                     model,imx,p,matcov,agemortsup);
                   14272:     
1.302     brouard  14273:     free_vector(lsurv,agegomp,AGESUP);
                   14274:     free_vector(lpop,agegomp,AGESUP);
                   14275:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  14276:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  14277:     free_ivector(dcwave,firstobs,lastobs);
                   14278:     free_vector(agecens,firstobs,lastobs);
                   14279:     free_vector(ageexmed,firstobs,lastobs);
                   14280:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  14281: #ifdef GSL
1.136     brouard  14282: #endif
1.186     brouard  14283:   } /* Endof if mle==-3 mortality only */
1.205     brouard  14284:   /* Standard  */
                   14285:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   14286:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   14287:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  14288:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  14289:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   14290:     for (k=1; k<=npar;k++)
                   14291:       printf(" %d %8.5f",k,p[k]);
                   14292:     printf("\n");
1.205     brouard  14293:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   14294:       /* mlikeli uses func not funcone */
1.247     brouard  14295:       /* for(i=1;i<nlstate;i++){ */
                   14296:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   14297:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   14298:       /* } */
1.205     brouard  14299:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   14300:     }
                   14301:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   14302:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   14303:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   14304:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   14305:     }
                   14306:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  14307:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   14308:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335     brouard  14309:           /* exit(0); */
1.126     brouard  14310:     for (k=1; k<=npar;k++)
                   14311:       printf(" %d %8.5f",k,p[k]);
                   14312:     printf("\n");
                   14313:     
                   14314:     /*--------- results files --------------*/
1.283     brouard  14315:     /* 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  14316:     
                   14317:     
                   14318:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  14319:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  14320:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  14321: 
                   14322:     printf("#model=  1      +     age ");
                   14323:     fprintf(ficres,"#model=  1      +     age ");
                   14324:     fprintf(ficlog,"#model=  1      +     age ");
                   14325:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   14326: </ul>", model);
                   14327: 
                   14328:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   14329:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   14330:     if(nagesqr==1){
                   14331:       printf("  + age*age  ");
                   14332:       fprintf(ficres,"  + age*age  ");
                   14333:       fprintf(ficlog,"  + age*age  ");
                   14334:       fprintf(fichtm, "<th>+ age*age</th>");
                   14335:     }
                   14336:     for(j=1;j <=ncovmodel-2;j++){
                   14337:       if(Typevar[j]==0) {
                   14338:        printf("  +      V%d  ",Tvar[j]);
                   14339:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   14340:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   14341:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   14342:       }else if(Typevar[j]==1) {
                   14343:        printf("  +    V%d*age ",Tvar[j]);
                   14344:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   14345:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   14346:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   14347:       }else if(Typevar[j]==2) {
                   14348:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14349:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14350:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14351:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  14352:       }else if(Typevar[j]==3) { /* TO VERIFY */
                   14353:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14354:        fprintf(ficres,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14355:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14356:        fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  14357:       }
                   14358:     }
                   14359:     printf("\n");
                   14360:     fprintf(ficres,"\n");
                   14361:     fprintf(ficlog,"\n");
                   14362:     fprintf(fichtm, "</tr>");
                   14363:     fprintf(fichtm, "\n");
                   14364:     
                   14365:     
1.126     brouard  14366:     for(i=1,jk=1; i <=nlstate; i++){
                   14367:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  14368:        if (k != i) {
1.319     brouard  14369:          fprintf(fichtm, "<tr>");
1.225     brouard  14370:          printf("%d%d ",i,k);
                   14371:          fprintf(ficlog,"%d%d ",i,k);
                   14372:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  14373:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  14374:          for(j=1; j <=ncovmodel; j++){
                   14375:            printf("%12.7f ",p[jk]);
                   14376:            fprintf(ficlog,"%12.7f ",p[jk]);
                   14377:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  14378:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  14379:            jk++; 
                   14380:          }
                   14381:          printf("\n");
                   14382:          fprintf(ficlog,"\n");
                   14383:          fprintf(ficres,"\n");
1.319     brouard  14384:          fprintf(fichtm, "</tr>\n");
1.225     brouard  14385:        }
1.126     brouard  14386:       }
                   14387:     }
1.319     brouard  14388:     /* fprintf(fichtm,"</tr>\n"); */
                   14389:     fprintf(fichtm,"</table>\n");
                   14390:     fprintf(fichtm, "\n");
                   14391: 
1.203     brouard  14392:     if(mle != 0){
                   14393:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  14394:       ftolhess=ftol; /* Usually correct */
1.203     brouard  14395:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   14396:       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");
                   14397:       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  14398:       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  14399:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   14400:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   14401:       if(nagesqr==1){
                   14402:        printf("  + age*age  ");
                   14403:        fprintf(ficres,"  + age*age  ");
                   14404:        fprintf(ficlog,"  + age*age  ");
                   14405:        fprintf(fichtm, "<th>+ age*age</th>");
                   14406:       }
                   14407:       for(j=1;j <=ncovmodel-2;j++){
                   14408:        if(Typevar[j]==0) {
                   14409:          printf("  +      V%d  ",Tvar[j]);
                   14410:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   14411:        }else if(Typevar[j]==1) {
                   14412:          printf("  +    V%d*age ",Tvar[j]);
                   14413:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   14414:        }else if(Typevar[j]==2) {
                   14415:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  14416:        }else if(Typevar[j]==3) { /* TO VERIFY */
                   14417:          fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  14418:        }
                   14419:       }
                   14420:       fprintf(fichtm, "</tr>\n");
                   14421:  
1.203     brouard  14422:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  14423:        for(k=1; k <=(nlstate+ndeath); k++){
                   14424:          if (k != i) {
1.319     brouard  14425:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  14426:            printf("%d%d ",i,k);
                   14427:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  14428:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  14429:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  14430:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  14431:              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]));
                   14432:              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  14433:              if(fabs(wald) > 1.96){
1.321     brouard  14434:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  14435:              }else{
                   14436:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   14437:              }
1.324     brouard  14438:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  14439:              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  14440:              jk++; 
                   14441:            }
                   14442:            printf("\n");
                   14443:            fprintf(ficlog,"\n");
1.319     brouard  14444:            fprintf(fichtm, "</tr>\n");
1.225     brouard  14445:          }
                   14446:        }
1.193     brouard  14447:       }
1.203     brouard  14448:     } /* end of hesscov and Wald tests */
1.319     brouard  14449:     fprintf(fichtm,"</table>\n");
1.225     brouard  14450:     
1.203     brouard  14451:     /*  */
1.126     brouard  14452:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   14453:     printf("# Scales (for hessian or gradient estimation)\n");
                   14454:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   14455:     for(i=1,jk=1; i <=nlstate; i++){
                   14456:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  14457:        if (j!=i) {
                   14458:          fprintf(ficres,"%1d%1d",i,j);
                   14459:          printf("%1d%1d",i,j);
                   14460:          fprintf(ficlog,"%1d%1d",i,j);
                   14461:          for(k=1; k<=ncovmodel;k++){
                   14462:            printf(" %.5e",delti[jk]);
                   14463:            fprintf(ficlog," %.5e",delti[jk]);
                   14464:            fprintf(ficres," %.5e",delti[jk]);
                   14465:            jk++;
                   14466:          }
                   14467:          printf("\n");
                   14468:          fprintf(ficlog,"\n");
                   14469:          fprintf(ficres,"\n");
                   14470:        }
1.126     brouard  14471:       }
                   14472:     }
                   14473:     
                   14474:     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  14475:     if(mle >= 1) /* Too big for the screen */
1.126     brouard  14476:       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");
                   14477:     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");
                   14478:     /* # 121 Var(a12)\n\ */
                   14479:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   14480:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   14481:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   14482:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   14483:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   14484:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   14485:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   14486:     
                   14487:     
                   14488:     /* Just to have a covariance matrix which will be more understandable
                   14489:        even is we still don't want to manage dictionary of variables
                   14490:     */
                   14491:     for(itimes=1;itimes<=2;itimes++){
                   14492:       jj=0;
                   14493:       for(i=1; i <=nlstate; i++){
1.225     brouard  14494:        for(j=1; j <=nlstate+ndeath; j++){
                   14495:          if(j==i) continue;
                   14496:          for(k=1; k<=ncovmodel;k++){
                   14497:            jj++;
                   14498:            ca[0]= k+'a'-1;ca[1]='\0';
                   14499:            if(itimes==1){
                   14500:              if(mle>=1)
                   14501:                printf("#%1d%1d%d",i,j,k);
                   14502:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   14503:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   14504:            }else{
                   14505:              if(mle>=1)
                   14506:                printf("%1d%1d%d",i,j,k);
                   14507:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   14508:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   14509:            }
                   14510:            ll=0;
                   14511:            for(li=1;li <=nlstate; li++){
                   14512:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   14513:                if(lj==li) continue;
                   14514:                for(lk=1;lk<=ncovmodel;lk++){
                   14515:                  ll++;
                   14516:                  if(ll<=jj){
                   14517:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   14518:                    if(ll<jj){
                   14519:                      if(itimes==1){
                   14520:                        if(mle>=1)
                   14521:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14522:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14523:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14524:                      }else{
                   14525:                        if(mle>=1)
                   14526:                          printf(" %.5e",matcov[jj][ll]); 
                   14527:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   14528:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   14529:                      }
                   14530:                    }else{
                   14531:                      if(itimes==1){
                   14532:                        if(mle>=1)
                   14533:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   14534:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   14535:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   14536:                      }else{
                   14537:                        if(mle>=1)
                   14538:                          printf(" %.7e",matcov[jj][ll]); 
                   14539:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   14540:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   14541:                      }
                   14542:                    }
                   14543:                  }
                   14544:                } /* end lk */
                   14545:              } /* end lj */
                   14546:            } /* end li */
                   14547:            if(mle>=1)
                   14548:              printf("\n");
                   14549:            fprintf(ficlog,"\n");
                   14550:            fprintf(ficres,"\n");
                   14551:            numlinepar++;
                   14552:          } /* end k*/
                   14553:        } /*end j */
1.126     brouard  14554:       } /* end i */
                   14555:     } /* end itimes */
                   14556:     
                   14557:     fflush(ficlog);
                   14558:     fflush(ficres);
1.225     brouard  14559:     while(fgets(line, MAXLINE, ficpar)) {
                   14560:       /* If line starts with a # it is a comment */
                   14561:       if (line[0] == '#') {
                   14562:        numlinepar++;
                   14563:        fputs(line,stdout);
                   14564:        fputs(line,ficparo);
                   14565:        fputs(line,ficlog);
1.299     brouard  14566:        fputs(line,ficres);
1.225     brouard  14567:        continue;
                   14568:       }else
                   14569:        break;
                   14570:     }
                   14571:     
1.209     brouard  14572:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   14573:     /*   ungetc(c,ficpar); */
                   14574:     /*   fgets(line, MAXLINE, ficpar); */
                   14575:     /*   fputs(line,stdout); */
                   14576:     /*   fputs(line,ficparo); */
                   14577:     /* } */
                   14578:     /* ungetc(c,ficpar); */
1.126     brouard  14579:     
                   14580:     estepm=0;
1.209     brouard  14581:     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  14582:       
                   14583:       if (num_filled != 6) {
                   14584:        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);
                   14585:        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);
                   14586:        goto end;
                   14587:       }
                   14588:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   14589:     }
                   14590:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   14591:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   14592:     
1.209     brouard  14593:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  14594:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   14595:     if (fage <= 2) {
                   14596:       bage = ageminpar;
                   14597:       fage = agemaxpar;
                   14598:     }
                   14599:     
                   14600:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  14601:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   14602:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  14603:                
1.186     brouard  14604:     /* Other stuffs, more or less useful */    
1.254     brouard  14605:     while(fgets(line, MAXLINE, ficpar)) {
                   14606:       /* If line starts with a # it is a comment */
                   14607:       if (line[0] == '#') {
                   14608:        numlinepar++;
                   14609:        fputs(line,stdout);
                   14610:        fputs(line,ficparo);
                   14611:        fputs(line,ficlog);
1.299     brouard  14612:        fputs(line,ficres);
1.254     brouard  14613:        continue;
                   14614:       }else
                   14615:        break;
                   14616:     }
                   14617: 
                   14618:     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){
                   14619:       
                   14620:       if (num_filled != 7) {
                   14621:        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);
                   14622:        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);
                   14623:        goto end;
                   14624:       }
                   14625:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   14626:       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);
                   14627:       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);
                   14628:       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  14629:     }
1.254     brouard  14630: 
                   14631:     while(fgets(line, MAXLINE, ficpar)) {
                   14632:       /* If line starts with a # it is a comment */
                   14633:       if (line[0] == '#') {
                   14634:        numlinepar++;
                   14635:        fputs(line,stdout);
                   14636:        fputs(line,ficparo);
                   14637:        fputs(line,ficlog);
1.299     brouard  14638:        fputs(line,ficres);
1.254     brouard  14639:        continue;
                   14640:       }else
                   14641:        break;
1.126     brouard  14642:     }
                   14643:     
                   14644:     
                   14645:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   14646:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   14647:     
1.254     brouard  14648:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   14649:       if (num_filled != 1) {
                   14650:        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);
                   14651:        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);
                   14652:        goto end;
                   14653:       }
                   14654:       printf("pop_based=%d\n",popbased);
                   14655:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   14656:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   14657:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   14658:     }
                   14659:      
1.258     brouard  14660:     /* Results */
1.332     brouard  14661:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
                   14662:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   14663:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  14664:     endishere=0;
1.258     brouard  14665:     nresult=0;
1.308     brouard  14666:     parameterline=0;
1.258     brouard  14667:     do{
                   14668:       if(!fgets(line, MAXLINE, ficpar)){
                   14669:        endishere=1;
1.308     brouard  14670:        parameterline=15;
1.258     brouard  14671:       }else if (line[0] == '#') {
                   14672:        /* If line starts with a # it is a comment */
1.254     brouard  14673:        numlinepar++;
                   14674:        fputs(line,stdout);
                   14675:        fputs(line,ficparo);
                   14676:        fputs(line,ficlog);
1.299     brouard  14677:        fputs(line,ficres);
1.254     brouard  14678:        continue;
1.258     brouard  14679:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   14680:        parameterline=11;
1.296     brouard  14681:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  14682:        parameterline=12;
1.307     brouard  14683:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  14684:        parameterline=13;
1.307     brouard  14685:       }
1.258     brouard  14686:       else{
                   14687:        parameterline=14;
1.254     brouard  14688:       }
1.308     brouard  14689:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  14690:       case 11:
1.296     brouard  14691:        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)){
                   14692:                  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  14693:          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);
                   14694:          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);
                   14695:          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);
                   14696:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  14697:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   14698:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  14699:           prvforecast = 1;
                   14700:        } 
                   14701:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  14702:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   14703:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   14704:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  14705:           prvforecast = 2;
                   14706:        }
                   14707:        else {
                   14708:          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);
                   14709:          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);
                   14710:          goto end;
1.258     brouard  14711:        }
1.254     brouard  14712:        break;
1.258     brouard  14713:       case 12:
1.296     brouard  14714:        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)){
                   14715:           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);
                   14716:          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);
                   14717:          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);
                   14718:          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);
                   14719:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  14720:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   14721:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  14722:           prvbackcast = 1;
                   14723:        } 
                   14724:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  14725:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   14726:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   14727:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  14728:           prvbackcast = 2;
                   14729:        }
                   14730:        else {
                   14731:          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);
                   14732:          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);
                   14733:          goto end;
1.258     brouard  14734:        }
1.230     brouard  14735:        break;
1.258     brouard  14736:       case 13:
1.332     brouard  14737:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  14738:        nresult++; /* Sum of resultlines */
1.342     brouard  14739:        /* printf("Result %d: result:%s\n",nresult, resultlineori); */
1.332     brouard  14740:        /* removefirstspace(&resultlineori); */
                   14741:        
                   14742:        if(strstr(resultlineori,"v") !=0){
                   14743:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   14744:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   14745:          return 1;
                   14746:        }
                   14747:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
1.342     brouard  14748:        /* printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori); */
1.318     brouard  14749:        if(nresult > MAXRESULTLINESPONE-1){
                   14750:          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);
                   14751:          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  14752:          goto end;
                   14753:        }
1.332     brouard  14754:        
1.310     brouard  14755:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  14756:          fprintf(ficparo,"result: %s\n",resultline);
                   14757:          fprintf(ficres,"result: %s\n",resultline);
                   14758:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  14759:        } else
                   14760:          goto end;
1.307     brouard  14761:        break;
                   14762:       case 14:
                   14763:        printf("Error: Unknown command '%s'\n",line);
                   14764:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  14765:        if(line[0] == ' ' || line[0] == '\n'){
                   14766:          printf("It should not be an empty line '%s'\n",line);
                   14767:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   14768:        }         
1.307     brouard  14769:        if(ncovmodel >=2 && nresult==0 ){
                   14770:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   14771:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  14772:        }
1.307     brouard  14773:        /* goto end; */
                   14774:        break;
1.308     brouard  14775:       case 15:
                   14776:        printf("End of resultlines.\n");
                   14777:        fprintf(ficlog,"End of resultlines.\n");
                   14778:        break;
                   14779:       default: /* parameterline =0 */
1.307     brouard  14780:        nresult=1;
                   14781:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  14782:       } /* End switch parameterline */
                   14783:     }while(endishere==0); /* End do */
1.126     brouard  14784:     
1.230     brouard  14785:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  14786:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  14787:     
                   14788:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  14789:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  14790:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14791: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14792: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  14793:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14794: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14795: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  14796:     }else{
1.270     brouard  14797:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  14798:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   14799:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   14800:       if(prvforecast==1){
                   14801:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   14802:         jprojd=jproj1;
                   14803:         mprojd=mproj1;
                   14804:         anprojd=anproj1;
                   14805:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   14806:         jprojf=jproj2;
                   14807:         mprojf=mproj2;
                   14808:         anprojf=anproj2;
                   14809:       } else if(prvforecast == 2){
                   14810:         dateprojd=dateintmean;
                   14811:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   14812:         dateprojf=dateintmean+yrfproj;
                   14813:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   14814:       }
                   14815:       if(prvbackcast==1){
                   14816:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   14817:         jbackd=jback1;
                   14818:         mbackd=mback1;
                   14819:         anbackd=anback1;
                   14820:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   14821:         jbackf=jback2;
                   14822:         mbackf=mback2;
                   14823:         anbackf=anback2;
                   14824:       } else if(prvbackcast == 2){
                   14825:         datebackd=dateintmean;
                   14826:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   14827:         datebackf=dateintmean-yrbproj;
                   14828:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   14829:       }
                   14830:       
1.350     brouard  14831:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);/* HERE valgrind Tvard*/
1.220     brouard  14832:     }
                   14833:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  14834:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   14835:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  14836:                
1.225     brouard  14837:     /*------------ free_vector  -------------*/
                   14838:     /*  chdir(path); */
1.220     brouard  14839:                
1.215     brouard  14840:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   14841:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   14842:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   14843:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  14844:     free_lvector(num,firstobs,lastobs);
                   14845:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  14846:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   14847:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   14848:     fclose(ficparo);
                   14849:     fclose(ficres);
1.220     brouard  14850:                
                   14851:                
1.186     brouard  14852:     /* Other results (useful)*/
1.220     brouard  14853:                
                   14854:                
1.126     brouard  14855:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  14856:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   14857:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  14858:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  14859:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  14860:     fclose(ficrespl);
                   14861: 
                   14862:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  14863:     /*#include "hpijx.h"*/
1.332     brouard  14864:     /** 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?*/
                   14865:     /* calls hpxij with combination k */
1.180     brouard  14866:     hPijx(p, bage, fage);
1.145     brouard  14867:     fclose(ficrespij);
1.227     brouard  14868:     
1.220     brouard  14869:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  14870:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  14871:     k=1;
1.126     brouard  14872:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  14873:     
1.269     brouard  14874:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   14875:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14876:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  14877:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  14878:        for(k=1;k<=ncovcombmax;k++)
                   14879:          probs[i][j][k]=0.;
1.269     brouard  14880:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   14881:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  14882:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  14883:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14884:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  14885:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  14886:          for(k=1;k<=ncovcombmax;k++)
                   14887:            mobaverages[i][j][k]=0.;
1.219     brouard  14888:       mobaverage=mobaverages;
                   14889:       if (mobilav!=0) {
1.235     brouard  14890:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  14891:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  14892:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   14893:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   14894:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   14895:        }
1.269     brouard  14896:       } else if (mobilavproj !=0) {
1.235     brouard  14897:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  14898:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  14899:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   14900:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14901:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14902:        }
1.269     brouard  14903:       }else{
                   14904:        printf("Internal error moving average\n");
                   14905:        fflush(stdout);
                   14906:        exit(1);
1.219     brouard  14907:       }
                   14908:     }/* end if moving average */
1.227     brouard  14909:     
1.126     brouard  14910:     /*---------- Forecasting ------------------*/
1.296     brouard  14911:     if(prevfcast==1){ 
                   14912:       /*   /\*    if(stepm ==1){*\/ */
                   14913:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14914:       /*This done previously after freqsummary.*/
                   14915:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   14916:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   14917:       
                   14918:       /* } else if (prvforecast==2){ */
                   14919:       /*   /\*    if(stepm ==1){*\/ */
                   14920:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14921:       /* } */
                   14922:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   14923:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  14924:     }
1.269     brouard  14925: 
1.296     brouard  14926:     /* Prevbcasting */
                   14927:     if(prevbcast==1){
1.219     brouard  14928:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14929:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14930:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   14931: 
                   14932:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   14933: 
                   14934:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  14935: 
1.219     brouard  14936:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   14937:       fclose(ficresplb);
                   14938: 
1.222     brouard  14939:       hBijx(p, bage, fage, mobaverage);
                   14940:       fclose(ficrespijb);
1.219     brouard  14941: 
1.296     brouard  14942:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   14943:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   14944:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   14945:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   14946:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   14947:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   14948: 
                   14949:       
1.269     brouard  14950:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14951: 
                   14952:       
1.269     brouard  14953:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  14954:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14955:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14956:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  14957:     }    /* end  Prevbcasting */
1.268     brouard  14958:  
1.186     brouard  14959:  
                   14960:     /* ------ Other prevalence ratios------------ */
1.126     brouard  14961: 
1.215     brouard  14962:     free_ivector(wav,1,imx);
                   14963:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   14964:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   14965:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  14966:                
                   14967:                
1.127     brouard  14968:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  14969:                
1.201     brouard  14970:     strcpy(filerese,"E_");
                   14971:     strcat(filerese,fileresu);
1.126     brouard  14972:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   14973:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14974:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14975:     }
1.208     brouard  14976:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   14977:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  14978: 
                   14979:     pstamp(ficreseij);
1.219     brouard  14980:                
1.351     brouard  14981:     /* i1=pow(2,cptcoveff); /\* Number of combination of dummy covariates *\/ */
                   14982:     /* if (cptcovn < 1){i1=1;} */
1.235     brouard  14983:     
1.351     brouard  14984:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   14985:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   14986:       /* if(i1 != 1 && TKresult[nres]!= k) */
                   14987:       /*       continue; */
1.219     brouard  14988:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  14989:       printf("\n#****** ");
1.351     brouard  14990:       for(j=1;j<=cptcovs;j++){
                   14991:       /* for(j=1;j<=cptcoveff;j++) { */
                   14992:        /* fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14993:        fprintf(ficreseij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14994:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14995:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.235     brouard  14996:       }
                   14997:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.337     brouard  14998:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   14999:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  15000:       }
                   15001:       fprintf(ficreseij,"******\n");
1.235     brouard  15002:       printf("******\n");
1.219     brouard  15003:       
                   15004:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15005:       oldm=oldms;savm=savms;
1.330     brouard  15006:       /* 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  15007:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  15008:       
1.219     brouard  15009:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  15010:     }
                   15011:     fclose(ficreseij);
1.208     brouard  15012:     printf("done evsij\n");fflush(stdout);
                   15013:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  15014: 
1.218     brouard  15015:                
1.227     brouard  15016:     /*---------- State-specific expectancies and variances ------------*/
1.336     brouard  15017:     /* Should be moved in a function */                
1.201     brouard  15018:     strcpy(filerest,"T_");
                   15019:     strcat(filerest,fileresu);
1.127     brouard  15020:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   15021:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   15022:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   15023:     }
1.208     brouard  15024:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   15025:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  15026:     strcpy(fileresstde,"STDE_");
                   15027:     strcat(fileresstde,fileresu);
1.126     brouard  15028:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  15029:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   15030:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  15031:     }
1.227     brouard  15032:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   15033:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  15034: 
1.201     brouard  15035:     strcpy(filerescve,"CVE_");
                   15036:     strcat(filerescve,fileresu);
1.126     brouard  15037:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  15038:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   15039:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  15040:     }
1.227     brouard  15041:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   15042:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  15043: 
1.201     brouard  15044:     strcpy(fileresv,"V_");
                   15045:     strcat(fileresv,fileresu);
1.126     brouard  15046:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   15047:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   15048:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   15049:     }
1.227     brouard  15050:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   15051:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  15052: 
1.235     brouard  15053:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   15054:     if (cptcovn < 1){i1=1;}
                   15055:     
1.334     brouard  15056:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   15057:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   15058:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   15059:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   15060:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   15061:       /* */
                   15062:       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  15063:        continue;
1.350     brouard  15064:       printf("\n# model %s \n#****** Result for:", model);  /* HERE model is empty */
1.321     brouard  15065:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   15066:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.334     brouard  15067:       /* It might not be a good idea to mix dummies and quantitative */
                   15068:       /* 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 *\/ */
                   15069:       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 */
                   15070:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   15071:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   15072:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   15073:         * (V5 is quanti) V4 and V3 are dummies
                   15074:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   15075:         *                                                              l=1 l=2
                   15076:         *                                                           k=1  1   1   0   0
                   15077:         *                                                           k=2  2   1   1   0
                   15078:         *                                                           k=3 [1] [2]  0   1
                   15079:         *                                                           k=4  2   2   1   1
                   15080:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   15081:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   15082:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   15083:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   15084:         */
                   15085:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   15086:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   15087: /* We give up with the combinations!! */
1.342     brouard  15088:        /* if(debugILK) */
                   15089:        /*   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  15090: 
                   15091:        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  15092:          /* 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] */
                   15093:          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  */
                   15094:          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  */
                   15095:          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  15096:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   15097:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   15098:          }else{
                   15099:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   15100:          }
                   15101:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15102:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15103:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   15104:          /* For each selected (single) quantitative value */
1.337     brouard  15105:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   15106:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   15107:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
1.334     brouard  15108:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   15109:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   15110:          }else{
                   15111:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   15112:          }
                   15113:        }else{
                   15114:          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 */
                   15115:          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 */
                   15116:          exit(1);
                   15117:        }
1.335     brouard  15118:       } /* End loop for each variable in the resultline */
1.334     brouard  15119:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   15120:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   15121:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   15122:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   15123:       /* }      */
1.208     brouard  15124:       fprintf(ficrest,"******\n");
1.227     brouard  15125:       fprintf(ficlog,"******\n");
                   15126:       printf("******\n");
1.208     brouard  15127:       
                   15128:       fprintf(ficresstdeij,"\n#****** ");
                   15129:       fprintf(ficrescveij,"\n#****** ");
1.337     brouard  15130:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
                   15131:       /* But it won't be sorted and depends on how the resultline is ordered */
1.225     brouard  15132:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  15133:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   15134:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15135:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15136:       }
                   15137:       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  15138:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   15139:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  15140:       }        
1.208     brouard  15141:       fprintf(ficresstdeij,"******\n");
                   15142:       fprintf(ficrescveij,"******\n");
                   15143:       
                   15144:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  15145:       /* pstamp(ficresvij); */
1.225     brouard  15146:       for(j=1;j<=cptcoveff;j++) 
1.335     brouard  15147:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   15148:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  15149:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  15150:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
1.337     brouard  15151:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  15152:       }        
1.208     brouard  15153:       fprintf(ficresvij,"******\n");
                   15154:       
                   15155:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15156:       oldm=oldms;savm=savms;
1.235     brouard  15157:       printf(" cvevsij ");
                   15158:       fprintf(ficlog, " cvevsij ");
                   15159:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  15160:       printf(" end cvevsij \n ");
                   15161:       fprintf(ficlog, " end cvevsij \n ");
                   15162:       
                   15163:       /*
                   15164:        */
                   15165:       /* goto endfree; */
                   15166:       
                   15167:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15168:       pstamp(ficrest);
                   15169:       
1.269     brouard  15170:       epj=vector(1,nlstate+1);
1.208     brouard  15171:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  15172:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   15173:        cptcod= 0; /* To be deleted */
                   15174:        printf("varevsij vpopbased=%d \n",vpopbased);
                   15175:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  15176:        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  15177:        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 ");
                   15178:        if(vpopbased==1)
                   15179:          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);
                   15180:        else
1.288     brouard  15181:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.335     brouard  15182:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  15183:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   15184:        fprintf(ficrest,"\n");
                   15185:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  15186:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   15187:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  15188:        for(age=bage; age <=fage ;age++){
1.235     brouard  15189:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  15190:          if (vpopbased==1) {
                   15191:            if(mobilav ==0){
                   15192:              for(i=1; i<=nlstate;i++)
                   15193:                prlim[i][i]=probs[(int)age][i][k];
                   15194:            }else{ /* mobilav */ 
                   15195:              for(i=1; i<=nlstate;i++)
                   15196:                prlim[i][i]=mobaverage[(int)age][i][k];
                   15197:            }
                   15198:          }
1.219     brouard  15199:          
1.227     brouard  15200:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   15201:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   15202:          /* printf(" age %4.0f ",age); */
                   15203:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   15204:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   15205:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   15206:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   15207:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   15208:            }
                   15209:            epj[nlstate+1] +=epj[j];
                   15210:          }
                   15211:          /* printf(" age %4.0f \n",age); */
1.219     brouard  15212:          
1.227     brouard  15213:          for(i=1, vepp=0.;i <=nlstate;i++)
                   15214:            for(j=1;j <=nlstate;j++)
                   15215:              vepp += vareij[i][j][(int)age];
                   15216:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   15217:          for(j=1;j <=nlstate;j++){
                   15218:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   15219:          }
                   15220:          fprintf(ficrest,"\n");
                   15221:        }
1.208     brouard  15222:       } /* End vpopbased */
1.269     brouard  15223:       free_vector(epj,1,nlstate+1);
1.208     brouard  15224:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   15225:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  15226:       printf("done selection\n");fflush(stdout);
                   15227:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  15228:       
1.335     brouard  15229:     } /* End k selection or end covariate selection for nres */
1.227     brouard  15230: 
                   15231:     printf("done State-specific expectancies\n");fflush(stdout);
                   15232:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   15233: 
1.335     brouard  15234:     /* variance-covariance of forward period prevalence */
1.269     brouard  15235:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  15236: 
1.227     brouard  15237:     
1.290     brouard  15238:     free_vector(weight,firstobs,lastobs);
1.351     brouard  15239:     free_imatrix(Tvardk,0,NCOVMAX,1,2);
1.227     brouard  15240:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  15241:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   15242:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   15243:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   15244:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  15245:     free_ivector(tab,1,NCOVMAX);
                   15246:     fclose(ficresstdeij);
                   15247:     fclose(ficrescveij);
                   15248:     fclose(ficresvij);
                   15249:     fclose(ficrest);
                   15250:     fclose(ficpar);
                   15251:     
                   15252:     
1.126     brouard  15253:     /*---------- End : free ----------------*/
1.219     brouard  15254:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  15255:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   15256:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  15257:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   15258:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  15259:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  15260:   /* endfree:*/
                   15261:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   15262:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   15263:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.341     brouard  15264:   /* if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs); */
                   15265:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);
1.290     brouard  15266:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   15267:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   15268:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  15269:   free_matrix(matcov,1,npar,1,npar);
                   15270:   free_matrix(hess,1,npar,1,npar);
                   15271:   /*free_vector(delti,1,npar);*/
                   15272:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   15273:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  15274:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  15275:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   15276:   
                   15277:   free_ivector(ncodemax,1,NCOVMAX);
                   15278:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   15279:   free_ivector(Dummy,-1,NCOVMAX);
                   15280:   free_ivector(Fixed,-1,NCOVMAX);
1.349     brouard  15281:   free_ivector(DummyV,-1,NCOVMAX);
                   15282:   free_ivector(FixedV,-1,NCOVMAX);
1.227     brouard  15283:   free_ivector(Typevar,-1,NCOVMAX);
                   15284:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  15285:   free_ivector(TvarsQ,1,NCOVMAX);
                   15286:   free_ivector(TvarsQind,1,NCOVMAX);
                   15287:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  15288:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  15289:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  15290:   free_ivector(TvarFD,1,NCOVMAX);
                   15291:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  15292:   free_ivector(TvarF,1,NCOVMAX);
                   15293:   free_ivector(TvarFind,1,NCOVMAX);
                   15294:   free_ivector(TvarV,1,NCOVMAX);
                   15295:   free_ivector(TvarVind,1,NCOVMAX);
                   15296:   free_ivector(TvarA,1,NCOVMAX);
                   15297:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  15298:   free_ivector(TvarFQ,1,NCOVMAX);
                   15299:   free_ivector(TvarFQind,1,NCOVMAX);
                   15300:   free_ivector(TvarVD,1,NCOVMAX);
                   15301:   free_ivector(TvarVDind,1,NCOVMAX);
                   15302:   free_ivector(TvarVQ,1,NCOVMAX);
                   15303:   free_ivector(TvarVQind,1,NCOVMAX);
1.349     brouard  15304:   free_ivector(TvarAVVA,1,NCOVMAX);
                   15305:   free_ivector(TvarAVVAind,1,NCOVMAX);
                   15306:   free_ivector(TvarVVA,1,NCOVMAX);
                   15307:   free_ivector(TvarVVAind,1,NCOVMAX);
1.339     brouard  15308:   free_ivector(TvarVV,1,NCOVMAX);
                   15309:   free_ivector(TvarVVind,1,NCOVMAX);
                   15310:   
1.230     brouard  15311:   free_ivector(Tvarsel,1,NCOVMAX);
                   15312:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  15313:   free_ivector(Tposprod,1,NCOVMAX);
                   15314:   free_ivector(Tprod,1,NCOVMAX);
                   15315:   free_ivector(Tvaraff,1,NCOVMAX);
1.338     brouard  15316:   free_ivector(invalidvarcomb,0,ncovcombmax);
1.227     brouard  15317:   free_ivector(Tage,1,NCOVMAX);
                   15318:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  15319:   free_ivector(TmodelInvind,1,NCOVMAX);
                   15320:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  15321: 
                   15322:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
                   15323: 
1.227     brouard  15324:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   15325:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  15326:   fflush(fichtm);
                   15327:   fflush(ficgp);
                   15328:   
1.227     brouard  15329:   
1.126     brouard  15330:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  15331:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   15332:     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  15333:   }else{
                   15334:     printf("End of Imach\n");
                   15335:     fprintf(ficlog,"End of Imach\n");
                   15336:   }
                   15337:   printf("See log file on %s\n",filelog);
                   15338:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  15339:   /*(void) gettimeofday(&end_time,&tzp);*/
                   15340:   rend_time = time(NULL);  
                   15341:   end_time = *localtime(&rend_time);
                   15342:   /* tml = *localtime(&end_time.tm_sec); */
                   15343:   strcpy(strtend,asctime(&end_time));
1.126     brouard  15344:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   15345:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  15346:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  15347:   
1.157     brouard  15348:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   15349:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   15350:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  15351:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   15352: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   15353:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   15354:   fclose(fichtm);
                   15355:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   15356:   fclose(fichtmcov);
                   15357:   fclose(ficgp);
                   15358:   fclose(ficlog);
                   15359:   /*------ End -----------*/
1.227     brouard  15360:   
1.281     brouard  15361: 
                   15362: /* Executes gnuplot */
1.227     brouard  15363:   
                   15364:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  15365: #ifdef WIN32
1.227     brouard  15366:   if (_chdir(pathcd) != 0)
                   15367:     printf("Can't move to directory %s!\n",path);
                   15368:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  15369: #else
1.227     brouard  15370:     if(chdir(pathcd) != 0)
                   15371:       printf("Can't move to directory %s!\n", path);
                   15372:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  15373: #endif 
1.126     brouard  15374:     printf("Current directory %s!\n",pathcd);
                   15375:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   15376:   sprintf(plotcmd,"gnuplot");
1.157     brouard  15377: #ifdef _WIN32
1.126     brouard  15378:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   15379: #endif
                   15380:   if(!stat(plotcmd,&info)){
1.158     brouard  15381:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  15382:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  15383:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  15384:     }else
                   15385:       strcpy(pplotcmd,plotcmd);
1.157     brouard  15386: #ifdef __unix
1.126     brouard  15387:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   15388:     if(!stat(plotcmd,&info)){
1.158     brouard  15389:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  15390:     }else
                   15391:       strcpy(pplotcmd,plotcmd);
                   15392: #endif
                   15393:   }else
                   15394:     strcpy(pplotcmd,plotcmd);
                   15395:   
                   15396:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  15397:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  15398:   strcpy(pplotcmd,plotcmd);
1.227     brouard  15399:   
1.126     brouard  15400:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  15401:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  15402:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  15403:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  15404:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  15405:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  15406:       strcpy(plotcmd,pplotcmd);
                   15407:     }
1.126     brouard  15408:   }
1.158     brouard  15409:   printf(" Successful, please wait...");
1.126     brouard  15410:   while (z[0] != 'q') {
                   15411:     /* chdir(path); */
1.154     brouard  15412:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  15413:     scanf("%s",z);
                   15414: /*     if (z[0] == 'c') system("./imach"); */
                   15415:     if (z[0] == 'e') {
1.158     brouard  15416: #ifdef __APPLE__
1.152     brouard  15417:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  15418: #elif __linux
                   15419:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  15420: #else
1.152     brouard  15421:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  15422: #endif
                   15423:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   15424:       system(pplotcmd);
1.126     brouard  15425:     }
                   15426:     else if (z[0] == 'g') system(plotcmd);
                   15427:     else if (z[0] == 'q') exit(0);
                   15428:   }
1.227     brouard  15429: end:
1.126     brouard  15430:   while (z[0] != 'q') {
1.195     brouard  15431:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  15432:     scanf("%s",z);
                   15433:   }
1.283     brouard  15434:   printf("End\n");
1.282     brouard  15435:   exit(0);
1.126     brouard  15436: }

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