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

1.341   ! brouard     1: /* $Id: imach.c,v 1.340 2022/09/11 07:53:11 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.341   ! brouard     4:   Revision 1.340  2022/09/11 07:53:11  brouard
        !             5:   Summary: Version imach 0.99r37
        !             6: 
        !             7:   * imach.c (Module): Adding timevarying products of any kinds,
        !             8:   should work before shifting cotvar from ncovcol+nqv columns in
        !             9:   order to have a correspondance between the column of cotvar and
        !            10:   the id of column.
        !            11: 
1.340     brouard    12:   Revision 1.339  2022/09/09 17:55:22  brouard
                     13:   Summary: version 0.99r37
                     14: 
                     15:   * imach.c (Module): Many improvements for fixing products of fixed
                     16:   timevarying as well as fixed * fixed, and test with quantitative
                     17:   covariate.
                     18: 
1.339     brouard    19:   Revision 1.338  2022/09/04 17:40:33  brouard
                     20:   Summary: 0.99r36
                     21: 
                     22:   * imach.c (Module): Now the easy runs i.e. without result or
                     23:   model=1+age only did not work. The defautl combination should be 1
                     24:   and not 0 because everything hasn't been tranformed yet.
                     25: 
1.338     brouard    26:   Revision 1.337  2022/09/02 14:26:02  brouard
                     27:   Summary: version 0.99r35
                     28: 
                     29:   * src/imach.c: Version 0.99r35 because it outputs same results with
                     30:   1+age+V1+V1*age for females and 1+age for females only
                     31:   (education=1 noweight)
                     32: 
1.337     brouard    33:   Revision 1.336  2022/08/31 09:52:36  brouard
                     34:   *** empty log message ***
                     35: 
1.336     brouard    36:   Revision 1.335  2022/08/31 08:23:16  brouard
                     37:   Summary: improvements...
                     38: 
1.335     brouard    39:   Revision 1.334  2022/08/25 09:08:41  brouard
                     40:   Summary: In progress for quantitative
                     41: 
1.334     brouard    42:   Revision 1.333  2022/08/21 09:10:30  brouard
                     43:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     44:   reassigning covariates: my first idea was that people will always
                     45:   use the first covariate V1 into the model but in fact they are
                     46:   producing data with many covariates and can use an equation model
                     47:   with some of the covariate; it means that in a model V2+V3 instead
                     48:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                     49:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                     50:   the equation model is restricted to two variables only (V2, V3)
                     51:   and the combination for V2 should be codtabm(k,1) instead of
                     52:   (codtabm(k,2), and the code should be
                     53:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                     54:   made. All of these should be simplified once a day like we did in
                     55:   hpxij() for example by using precov[nres] which is computed in
                     56:   decoderesult for each nres of each resultline. Loop should be done
                     57:   on the equation model globally by distinguishing only product with
                     58:   age (which are changing with age) and no more on type of
                     59:   covariates, single dummies, single covariates.
                     60: 
1.333     brouard    61:   Revision 1.332  2022/08/21 09:06:25  brouard
                     62:   Summary: Version 0.99r33
                     63: 
                     64:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     65:   reassigning covariates: my first idea was that people will always
                     66:   use the first covariate V1 into the model but in fact they are
                     67:   producing data with many covariates and can use an equation model
                     68:   with some of the covariate; it means that in a model V2+V3 instead
                     69:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                     70:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                     71:   the equation model is restricted to two variables only (V2, V3)
                     72:   and the combination for V2 should be codtabm(k,1) instead of
                     73:   (codtabm(k,2), and the code should be
                     74:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                     75:   made. All of these should be simplified once a day like we did in
                     76:   hpxij() for example by using precov[nres] which is computed in
                     77:   decoderesult for each nres of each resultline. Loop should be done
                     78:   on the equation model globally by distinguishing only product with
                     79:   age (which are changing with age) and no more on type of
                     80:   covariates, single dummies, single covariates.
                     81: 
1.332     brouard    82:   Revision 1.331  2022/08/07 05:40:09  brouard
                     83:   *** empty log message ***
                     84: 
1.331     brouard    85:   Revision 1.330  2022/08/06 07:18:25  brouard
                     86:   Summary: last 0.99r31
                     87: 
                     88:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                     89: 
1.330     brouard    90:   Revision 1.329  2022/08/03 17:29:54  brouard
                     91:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                     92: 
1.329     brouard    93:   Revision 1.328  2022/07/27 17:40:48  brouard
                     94:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                     95: 
1.328     brouard    96:   Revision 1.327  2022/07/27 14:47:35  brouard
                     97:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                     98: 
1.327     brouard    99:   Revision 1.326  2022/07/26 17:33:55  brouard
                    100:   Summary: some test with nres=1
                    101: 
1.326     brouard   102:   Revision 1.325  2022/07/25 14:27:23  brouard
                    103:   Summary: r30
                    104: 
                    105:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                    106:   coredumped, revealed by Feiuno, thank you.
                    107: 
1.325     brouard   108:   Revision 1.324  2022/07/23 17:44:26  brouard
                    109:   *** empty log message ***
                    110: 
1.324     brouard   111:   Revision 1.323  2022/07/22 12:30:08  brouard
                    112:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    113: 
1.323     brouard   114:   Revision 1.322  2022/07/22 12:27:48  brouard
                    115:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    116: 
1.322     brouard   117:   Revision 1.321  2022/07/22 12:04:24  brouard
                    118:   Summary: r28
                    119: 
                    120:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    121: 
1.321     brouard   122:   Revision 1.320  2022/06/02 05:10:11  brouard
                    123:   *** empty log message ***
                    124: 
1.320     brouard   125:   Revision 1.319  2022/06/02 04:45:11  brouard
                    126:   * imach.c (Module): Adding the Wald tests from the log to the main
                    127:   htm for better display of the maximum likelihood estimators.
                    128: 
1.319     brouard   129:   Revision 1.318  2022/05/24 08:10:59  brouard
                    130:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                    131:   of confidencce intervals with product in the equation modelC
                    132: 
1.318     brouard   133:   Revision 1.317  2022/05/15 15:06:23  brouard
                    134:   * imach.c (Module):  Some minor improvements
                    135: 
1.317     brouard   136:   Revision 1.316  2022/05/11 15:11:31  brouard
                    137:   Summary: r27
                    138: 
1.316     brouard   139:   Revision 1.315  2022/05/11 15:06:32  brouard
                    140:   *** empty log message ***
                    141: 
1.315     brouard   142:   Revision 1.314  2022/04/13 17:43:09  brouard
                    143:   * imach.c (Module): Adding link to text data files
                    144: 
1.314     brouard   145:   Revision 1.313  2022/04/11 15:57:42  brouard
                    146:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    147: 
1.313     brouard   148:   Revision 1.312  2022/04/05 21:24:39  brouard
                    149:   *** empty log message ***
                    150: 
1.312     brouard   151:   Revision 1.311  2022/04/05 21:03:51  brouard
                    152:   Summary: Fixed quantitative covariates
                    153: 
                    154:          Fixed covariates (dummy or quantitative)
                    155:        with missing values have never been allowed but are ERRORS and
                    156:        program quits. Standard deviations of fixed covariates were
                    157:        wrongly computed. Mean and standard deviations of time varying
                    158:        covariates are still not computed.
                    159: 
1.311     brouard   160:   Revision 1.310  2022/03/17 08:45:53  brouard
                    161:   Summary: 99r25
                    162: 
                    163:   Improving detection of errors: result lines should be compatible with
                    164:   the model.
                    165: 
1.310     brouard   166:   Revision 1.309  2021/05/20 12:39:14  brouard
                    167:   Summary: Version 0.99r24
                    168: 
1.309     brouard   169:   Revision 1.308  2021/03/31 13:11:57  brouard
                    170:   Summary: Version 0.99r23
                    171: 
                    172: 
                    173:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    174: 
1.308     brouard   175:   Revision 1.307  2021/03/08 18:11:32  brouard
                    176:   Summary: 0.99r22 fixed bug on result:
                    177: 
1.307     brouard   178:   Revision 1.306  2021/02/20 15:44:02  brouard
                    179:   Summary: Version 0.99r21
                    180: 
                    181:   * imach.c (Module): Fix bug on quitting after result lines!
                    182:   (Module): Version 0.99r21
                    183: 
1.306     brouard   184:   Revision 1.305  2021/02/20 15:28:30  brouard
                    185:   * imach.c (Module): Fix bug on quitting after result lines!
                    186: 
1.305     brouard   187:   Revision 1.304  2021/02/12 11:34:20  brouard
                    188:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    189: 
1.304     brouard   190:   Revision 1.303  2021/02/11 19:50:15  brouard
                    191:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    192: 
1.303     brouard   193:   Revision 1.302  2020/02/22 21:00:05  brouard
                    194:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    195:   and life table from the data without any state)
                    196: 
1.302     brouard   197:   Revision 1.301  2019/06/04 13:51:20  brouard
                    198:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    199: 
1.301     brouard   200:   Revision 1.300  2019/05/22 19:09:45  brouard
                    201:   Summary: version 0.99r19 of May 2019
                    202: 
1.300     brouard   203:   Revision 1.299  2019/05/22 18:37:08  brouard
                    204:   Summary: Cleaned 0.99r19
                    205: 
1.299     brouard   206:   Revision 1.298  2019/05/22 18:19:56  brouard
                    207:   *** empty log message ***
                    208: 
1.298     brouard   209:   Revision 1.297  2019/05/22 17:56:10  brouard
                    210:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    211: 
1.297     brouard   212:   Revision 1.296  2019/05/20 13:03:18  brouard
                    213:   Summary: Projection syntax simplified
                    214: 
                    215: 
                    216:   We can now start projections, forward or backward, from the mean date
                    217:   of inteviews up to or down to a number of years of projection:
                    218:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    219:   or
                    220:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    221:   or
                    222:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    223:   or
                    224:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    225: 
1.296     brouard   226:   Revision 1.295  2019/05/18 09:52:50  brouard
                    227:   Summary: doxygen tex bug
                    228: 
1.295     brouard   229:   Revision 1.294  2019/05/16 14:54:33  brouard
                    230:   Summary: There was some wrong lines added
                    231: 
1.294     brouard   232:   Revision 1.293  2019/05/09 15:17:34  brouard
                    233:   *** empty log message ***
                    234: 
1.293     brouard   235:   Revision 1.292  2019/05/09 14:17:20  brouard
                    236:   Summary: Some updates
                    237: 
1.292     brouard   238:   Revision 1.291  2019/05/09 13:44:18  brouard
                    239:   Summary: Before ncovmax
                    240: 
1.291     brouard   241:   Revision 1.290  2019/05/09 13:39:37  brouard
                    242:   Summary: 0.99r18 unlimited number of individuals
                    243: 
                    244:   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.
                    245: 
1.290     brouard   246:   Revision 1.289  2018/12/13 09:16:26  brouard
                    247:   Summary: Bug for young ages (<-30) will be in r17
                    248: 
1.289     brouard   249:   Revision 1.288  2018/05/02 20:58:27  brouard
                    250:   Summary: Some bugs fixed
                    251: 
1.288     brouard   252:   Revision 1.287  2018/05/01 17:57:25  brouard
                    253:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    254: 
1.287     brouard   255:   Revision 1.286  2018/04/27 14:27:04  brouard
                    256:   Summary: some minor bugs
                    257: 
1.286     brouard   258:   Revision 1.285  2018/04/21 21:02:16  brouard
                    259:   Summary: Some bugs fixed, valgrind tested
                    260: 
1.285     brouard   261:   Revision 1.284  2018/04/20 05:22:13  brouard
                    262:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    263: 
1.284     brouard   264:   Revision 1.283  2018/04/19 14:49:16  brouard
                    265:   Summary: Some minor bugs fixed
                    266: 
1.283     brouard   267:   Revision 1.282  2018/02/27 22:50:02  brouard
                    268:   *** empty log message ***
                    269: 
1.282     brouard   270:   Revision 1.281  2018/02/27 19:25:23  brouard
                    271:   Summary: Adding second argument for quitting
                    272: 
1.281     brouard   273:   Revision 1.280  2018/02/21 07:58:13  brouard
                    274:   Summary: 0.99r15
                    275: 
                    276:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    277: 
1.280     brouard   278:   Revision 1.279  2017/07/20 13:35:01  brouard
                    279:   Summary: temporary working
                    280: 
1.279     brouard   281:   Revision 1.278  2017/07/19 14:09:02  brouard
                    282:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    283: 
1.278     brouard   284:   Revision 1.277  2017/07/17 08:53:49  brouard
                    285:   Summary: BOM files can be read now
                    286: 
1.277     brouard   287:   Revision 1.276  2017/06/30 15:48:31  brouard
                    288:   Summary: Graphs improvements
                    289: 
1.276     brouard   290:   Revision 1.275  2017/06/30 13:39:33  brouard
                    291:   Summary: Saito's color
                    292: 
1.275     brouard   293:   Revision 1.274  2017/06/29 09:47:08  brouard
                    294:   Summary: Version 0.99r14
                    295: 
1.274     brouard   296:   Revision 1.273  2017/06/27 11:06:02  brouard
                    297:   Summary: More documentation on projections
                    298: 
1.273     brouard   299:   Revision 1.272  2017/06/27 10:22:40  brouard
                    300:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    301: 
1.272     brouard   302:   Revision 1.271  2017/06/27 10:17:50  brouard
                    303:   Summary: Some bug with rint
                    304: 
1.271     brouard   305:   Revision 1.270  2017/05/24 05:45:29  brouard
                    306:   *** empty log message ***
                    307: 
1.270     brouard   308:   Revision 1.269  2017/05/23 08:39:25  brouard
                    309:   Summary: Code into subroutine, cleanings
                    310: 
1.269     brouard   311:   Revision 1.268  2017/05/18 20:09:32  brouard
                    312:   Summary: backprojection and confidence intervals of backprevalence
                    313: 
1.268     brouard   314:   Revision 1.267  2017/05/13 10:25:05  brouard
                    315:   Summary: temporary save for backprojection
                    316: 
1.267     brouard   317:   Revision 1.266  2017/05/13 07:26:12  brouard
                    318:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    319: 
1.266     brouard   320:   Revision 1.265  2017/04/26 16:22:11  brouard
                    321:   Summary: imach 0.99r13 Some bugs fixed
                    322: 
1.265     brouard   323:   Revision 1.264  2017/04/26 06:01:29  brouard
                    324:   Summary: Labels in graphs
                    325: 
1.264     brouard   326:   Revision 1.263  2017/04/24 15:23:15  brouard
                    327:   Summary: to save
                    328: 
1.263     brouard   329:   Revision 1.262  2017/04/18 16:48:12  brouard
                    330:   *** empty log message ***
                    331: 
1.262     brouard   332:   Revision 1.261  2017/04/05 10:14:09  brouard
                    333:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    334: 
1.261     brouard   335:   Revision 1.260  2017/04/04 17:46:59  brouard
                    336:   Summary: Gnuplot indexations fixed (humm)
                    337: 
1.260     brouard   338:   Revision 1.259  2017/04/04 13:01:16  brouard
                    339:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    340: 
1.259     brouard   341:   Revision 1.258  2017/04/03 10:17:47  brouard
                    342:   Summary: Version 0.99r12
                    343: 
                    344:   Some cleanings, conformed with updated documentation.
                    345: 
1.258     brouard   346:   Revision 1.257  2017/03/29 16:53:30  brouard
                    347:   Summary: Temp
                    348: 
1.257     brouard   349:   Revision 1.256  2017/03/27 05:50:23  brouard
                    350:   Summary: Temporary
                    351: 
1.256     brouard   352:   Revision 1.255  2017/03/08 16:02:28  brouard
                    353:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    354: 
1.255     brouard   355:   Revision 1.254  2017/03/08 07:13:00  brouard
                    356:   Summary: Fixing data parameter line
                    357: 
1.254     brouard   358:   Revision 1.253  2016/12/15 11:59:41  brouard
                    359:   Summary: 0.99 in progress
                    360: 
1.253     brouard   361:   Revision 1.252  2016/09/15 21:15:37  brouard
                    362:   *** empty log message ***
                    363: 
1.252     brouard   364:   Revision 1.251  2016/09/15 15:01:13  brouard
                    365:   Summary: not working
                    366: 
1.251     brouard   367:   Revision 1.250  2016/09/08 16:07:27  brouard
                    368:   Summary: continue
                    369: 
1.250     brouard   370:   Revision 1.249  2016/09/07 17:14:18  brouard
                    371:   Summary: Starting values from frequencies
                    372: 
1.249     brouard   373:   Revision 1.248  2016/09/07 14:10:18  brouard
                    374:   *** empty log message ***
                    375: 
1.248     brouard   376:   Revision 1.247  2016/09/02 11:11:21  brouard
                    377:   *** empty log message ***
                    378: 
1.247     brouard   379:   Revision 1.246  2016/09/02 08:49:22  brouard
                    380:   *** empty log message ***
                    381: 
1.246     brouard   382:   Revision 1.245  2016/09/02 07:25:01  brouard
                    383:   *** empty log message ***
                    384: 
1.245     brouard   385:   Revision 1.244  2016/09/02 07:17:34  brouard
                    386:   *** empty log message ***
                    387: 
1.244     brouard   388:   Revision 1.243  2016/09/02 06:45:35  brouard
                    389:   *** empty log message ***
                    390: 
1.243     brouard   391:   Revision 1.242  2016/08/30 15:01:20  brouard
                    392:   Summary: Fixing a lots
                    393: 
1.242     brouard   394:   Revision 1.241  2016/08/29 17:17:25  brouard
                    395:   Summary: gnuplot problem in Back projection to fix
                    396: 
1.241     brouard   397:   Revision 1.240  2016/08/29 07:53:18  brouard
                    398:   Summary: Better
                    399: 
1.240     brouard   400:   Revision 1.239  2016/08/26 15:51:03  brouard
                    401:   Summary: Improvement in Powell output in order to copy and paste
                    402: 
                    403:   Author:
                    404: 
1.239     brouard   405:   Revision 1.238  2016/08/26 14:23:35  brouard
                    406:   Summary: Starting tests of 0.99
                    407: 
1.238     brouard   408:   Revision 1.237  2016/08/26 09:20:19  brouard
                    409:   Summary: to valgrind
                    410: 
1.237     brouard   411:   Revision 1.236  2016/08/25 10:50:18  brouard
                    412:   *** empty log message ***
                    413: 
1.236     brouard   414:   Revision 1.235  2016/08/25 06:59:23  brouard
                    415:   *** empty log message ***
                    416: 
1.235     brouard   417:   Revision 1.234  2016/08/23 16:51:20  brouard
                    418:   *** empty log message ***
                    419: 
1.234     brouard   420:   Revision 1.233  2016/08/23 07:40:50  brouard
                    421:   Summary: not working
                    422: 
1.233     brouard   423:   Revision 1.232  2016/08/22 14:20:21  brouard
                    424:   Summary: not working
                    425: 
1.232     brouard   426:   Revision 1.231  2016/08/22 07:17:15  brouard
                    427:   Summary: not working
                    428: 
1.231     brouard   429:   Revision 1.230  2016/08/22 06:55:53  brouard
                    430:   Summary: Not working
                    431: 
1.230     brouard   432:   Revision 1.229  2016/07/23 09:45:53  brouard
                    433:   Summary: Completing for func too
                    434: 
1.229     brouard   435:   Revision 1.228  2016/07/22 17:45:30  brouard
                    436:   Summary: Fixing some arrays, still debugging
                    437: 
1.227     brouard   438:   Revision 1.226  2016/07/12 18:42:34  brouard
                    439:   Summary: temp
                    440: 
1.226     brouard   441:   Revision 1.225  2016/07/12 08:40:03  brouard
                    442:   Summary: saving but not running
                    443: 
1.225     brouard   444:   Revision 1.224  2016/07/01 13:16:01  brouard
                    445:   Summary: Fixes
                    446: 
1.224     brouard   447:   Revision 1.223  2016/02/19 09:23:35  brouard
                    448:   Summary: temporary
                    449: 
1.223     brouard   450:   Revision 1.222  2016/02/17 08:14:50  brouard
                    451:   Summary: Probably last 0.98 stable version 0.98r6
                    452: 
1.222     brouard   453:   Revision 1.221  2016/02/15 23:35:36  brouard
                    454:   Summary: minor bug
                    455: 
1.220     brouard   456:   Revision 1.219  2016/02/15 00:48:12  brouard
                    457:   *** empty log message ***
                    458: 
1.219     brouard   459:   Revision 1.218  2016/02/12 11:29:23  brouard
                    460:   Summary: 0.99 Back projections
                    461: 
1.218     brouard   462:   Revision 1.217  2015/12/23 17:18:31  brouard
                    463:   Summary: Experimental backcast
                    464: 
1.217     brouard   465:   Revision 1.216  2015/12/18 17:32:11  brouard
                    466:   Summary: 0.98r4 Warning and status=-2
                    467: 
                    468:   Version 0.98r4 is now:
                    469:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    470:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    471:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    472: 
1.216     brouard   473:   Revision 1.215  2015/12/16 08:52:24  brouard
                    474:   Summary: 0.98r4 working
                    475: 
1.215     brouard   476:   Revision 1.214  2015/12/16 06:57:54  brouard
                    477:   Summary: temporary not working
                    478: 
1.214     brouard   479:   Revision 1.213  2015/12/11 18:22:17  brouard
                    480:   Summary: 0.98r4
                    481: 
1.213     brouard   482:   Revision 1.212  2015/11/21 12:47:24  brouard
                    483:   Summary: minor typo
                    484: 
1.212     brouard   485:   Revision 1.211  2015/11/21 12:41:11  brouard
                    486:   Summary: 0.98r3 with some graph of projected cross-sectional
                    487: 
                    488:   Author: Nicolas Brouard
                    489: 
1.211     brouard   490:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   491:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   492:   Summary: Adding ftolpl parameter
                    493:   Author: N Brouard
                    494: 
                    495:   We had difficulties to get smoothed confidence intervals. It was due
                    496:   to the period prevalence which wasn't computed accurately. The inner
                    497:   parameter ftolpl is now an outer parameter of the .imach parameter
                    498:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    499:   computation are long.
                    500: 
1.209     brouard   501:   Revision 1.208  2015/11/17 14:31:57  brouard
                    502:   Summary: temporary
                    503: 
1.208     brouard   504:   Revision 1.207  2015/10/27 17:36:57  brouard
                    505:   *** empty log message ***
                    506: 
1.207     brouard   507:   Revision 1.206  2015/10/24 07:14:11  brouard
                    508:   *** empty log message ***
                    509: 
1.206     brouard   510:   Revision 1.205  2015/10/23 15:50:53  brouard
                    511:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    512: 
1.205     brouard   513:   Revision 1.204  2015/10/01 16:20:26  brouard
                    514:   Summary: Some new graphs of contribution to likelihood
                    515: 
1.204     brouard   516:   Revision 1.203  2015/09/30 17:45:14  brouard
                    517:   Summary: looking at better estimation of the hessian
                    518: 
                    519:   Also a better criteria for convergence to the period prevalence And
                    520:   therefore adding the number of years needed to converge. (The
                    521:   prevalence in any alive state shold sum to one
                    522: 
1.203     brouard   523:   Revision 1.202  2015/09/22 19:45:16  brouard
                    524:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    525: 
1.202     brouard   526:   Revision 1.201  2015/09/15 17:34:58  brouard
                    527:   Summary: 0.98r0
                    528: 
                    529:   - Some new graphs like suvival functions
                    530:   - Some bugs fixed like model=1+age+V2.
                    531: 
1.201     brouard   532:   Revision 1.200  2015/09/09 16:53:55  brouard
                    533:   Summary: Big bug thanks to Flavia
                    534: 
                    535:   Even model=1+age+V2. did not work anymore
                    536: 
1.200     brouard   537:   Revision 1.199  2015/09/07 14:09:23  brouard
                    538:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    539: 
1.199     brouard   540:   Revision 1.198  2015/09/03 07:14:39  brouard
                    541:   Summary: 0.98q5 Flavia
                    542: 
1.198     brouard   543:   Revision 1.197  2015/09/01 18:24:39  brouard
                    544:   *** empty log message ***
                    545: 
1.197     brouard   546:   Revision 1.196  2015/08/18 23:17:52  brouard
                    547:   Summary: 0.98q5
                    548: 
1.196     brouard   549:   Revision 1.195  2015/08/18 16:28:39  brouard
                    550:   Summary: Adding a hack for testing purpose
                    551: 
                    552:   After reading the title, ftol and model lines, if the comment line has
                    553:   a q, starting with #q, the answer at the end of the run is quit. It
                    554:   permits to run test files in batch with ctest. The former workaround was
                    555:   $ echo q | imach foo.imach
                    556: 
1.195     brouard   557:   Revision 1.194  2015/08/18 13:32:00  brouard
                    558:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    559: 
1.194     brouard   560:   Revision 1.193  2015/08/04 07:17:42  brouard
                    561:   Summary: 0.98q4
                    562: 
1.193     brouard   563:   Revision 1.192  2015/07/16 16:49:02  brouard
                    564:   Summary: Fixing some outputs
                    565: 
1.192     brouard   566:   Revision 1.191  2015/07/14 10:00:33  brouard
                    567:   Summary: Some fixes
                    568: 
1.191     brouard   569:   Revision 1.190  2015/05/05 08:51:13  brouard
                    570:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    571: 
                    572:   Fix 1+age+.
                    573: 
1.190     brouard   574:   Revision 1.189  2015/04/30 14:45:16  brouard
                    575:   Summary: 0.98q2
                    576: 
1.189     brouard   577:   Revision 1.188  2015/04/30 08:27:53  brouard
                    578:   *** empty log message ***
                    579: 
1.188     brouard   580:   Revision 1.187  2015/04/29 09:11:15  brouard
                    581:   *** empty log message ***
                    582: 
1.187     brouard   583:   Revision 1.186  2015/04/23 12:01:52  brouard
                    584:   Summary: V1*age is working now, version 0.98q1
                    585: 
                    586:   Some codes had been disabled in order to simplify and Vn*age was
                    587:   working in the optimization phase, ie, giving correct MLE parameters,
                    588:   but, as usual, outputs were not correct and program core dumped.
                    589: 
1.186     brouard   590:   Revision 1.185  2015/03/11 13:26:42  brouard
                    591:   Summary: Inclusion of compile and links command line for Intel Compiler
                    592: 
1.185     brouard   593:   Revision 1.184  2015/03/11 11:52:39  brouard
                    594:   Summary: Back from Windows 8. Intel Compiler
                    595: 
1.184     brouard   596:   Revision 1.183  2015/03/10 20:34:32  brouard
                    597:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    598: 
                    599:   We use directest instead of original Powell test; probably no
                    600:   incidence on the results, but better justifications;
                    601:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    602:   wrong results.
                    603: 
1.183     brouard   604:   Revision 1.182  2015/02/12 08:19:57  brouard
                    605:   Summary: Trying to keep directest which seems simpler and more general
                    606:   Author: Nicolas Brouard
                    607: 
1.182     brouard   608:   Revision 1.181  2015/02/11 23:22:24  brouard
                    609:   Summary: Comments on Powell added
                    610: 
                    611:   Author:
                    612: 
1.181     brouard   613:   Revision 1.180  2015/02/11 17:33:45  brouard
                    614:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    615: 
1.180     brouard   616:   Revision 1.179  2015/01/04 09:57:06  brouard
                    617:   Summary: back to OS/X
                    618: 
1.179     brouard   619:   Revision 1.178  2015/01/04 09:35:48  brouard
                    620:   *** empty log message ***
                    621: 
1.178     brouard   622:   Revision 1.177  2015/01/03 18:40:56  brouard
                    623:   Summary: Still testing ilc32 on OSX
                    624: 
1.177     brouard   625:   Revision 1.176  2015/01/03 16:45:04  brouard
                    626:   *** empty log message ***
                    627: 
1.176     brouard   628:   Revision 1.175  2015/01/03 16:33:42  brouard
                    629:   *** empty log message ***
                    630: 
1.175     brouard   631:   Revision 1.174  2015/01/03 16:15:49  brouard
                    632:   Summary: Still in cross-compilation
                    633: 
1.174     brouard   634:   Revision 1.173  2015/01/03 12:06:26  brouard
                    635:   Summary: trying to detect cross-compilation
                    636: 
1.173     brouard   637:   Revision 1.172  2014/12/27 12:07:47  brouard
                    638:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    639: 
1.172     brouard   640:   Revision 1.171  2014/12/23 13:26:59  brouard
                    641:   Summary: Back from Visual C
                    642: 
                    643:   Still problem with utsname.h on Windows
                    644: 
1.171     brouard   645:   Revision 1.170  2014/12/23 11:17:12  brouard
                    646:   Summary: Cleaning some \%% back to %%
                    647: 
                    648:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    649: 
1.170     brouard   650:   Revision 1.169  2014/12/22 23:08:31  brouard
                    651:   Summary: 0.98p
                    652: 
                    653:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    654: 
1.169     brouard   655:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   656:   Summary: update
1.169     brouard   657: 
1.168     brouard   658:   Revision 1.167  2014/12/22 13:50:56  brouard
                    659:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    660: 
                    661:   Testing on Linux 64
                    662: 
1.167     brouard   663:   Revision 1.166  2014/12/22 11:40:47  brouard
                    664:   *** empty log message ***
                    665: 
1.166     brouard   666:   Revision 1.165  2014/12/16 11:20:36  brouard
                    667:   Summary: After compiling on Visual C
                    668: 
                    669:   * imach.c (Module): Merging 1.61 to 1.162
                    670: 
1.165     brouard   671:   Revision 1.164  2014/12/16 10:52:11  brouard
                    672:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    673: 
                    674:   * imach.c (Module): Merging 1.61 to 1.162
                    675: 
1.164     brouard   676:   Revision 1.163  2014/12/16 10:30:11  brouard
                    677:   * imach.c (Module): Merging 1.61 to 1.162
                    678: 
1.163     brouard   679:   Revision 1.162  2014/09/25 11:43:39  brouard
                    680:   Summary: temporary backup 0.99!
                    681: 
1.162     brouard   682:   Revision 1.1  2014/09/16 11:06:58  brouard
                    683:   Summary: With some code (wrong) for nlopt
                    684: 
                    685:   Author:
                    686: 
                    687:   Revision 1.161  2014/09/15 20:41:41  brouard
                    688:   Summary: Problem with macro SQR on Intel compiler
                    689: 
1.161     brouard   690:   Revision 1.160  2014/09/02 09:24:05  brouard
                    691:   *** empty log message ***
                    692: 
1.160     brouard   693:   Revision 1.159  2014/09/01 10:34:10  brouard
                    694:   Summary: WIN32
                    695:   Author: Brouard
                    696: 
1.159     brouard   697:   Revision 1.158  2014/08/27 17:11:51  brouard
                    698:   *** empty log message ***
                    699: 
1.158     brouard   700:   Revision 1.157  2014/08/27 16:26:55  brouard
                    701:   Summary: Preparing windows Visual studio version
                    702:   Author: Brouard
                    703: 
                    704:   In order to compile on Visual studio, time.h is now correct and time_t
                    705:   and tm struct should be used. difftime should be used but sometimes I
                    706:   just make the differences in raw time format (time(&now).
                    707:   Trying to suppress #ifdef LINUX
                    708:   Add xdg-open for __linux in order to open default browser.
                    709: 
1.157     brouard   710:   Revision 1.156  2014/08/25 20:10:10  brouard
                    711:   *** empty log message ***
                    712: 
1.156     brouard   713:   Revision 1.155  2014/08/25 18:32:34  brouard
                    714:   Summary: New compile, minor changes
                    715:   Author: Brouard
                    716: 
1.155     brouard   717:   Revision 1.154  2014/06/20 17:32:08  brouard
                    718:   Summary: Outputs now all graphs of convergence to period prevalence
                    719: 
1.154     brouard   720:   Revision 1.153  2014/06/20 16:45:46  brouard
                    721:   Summary: If 3 live state, convergence to period prevalence on same graph
                    722:   Author: Brouard
                    723: 
1.153     brouard   724:   Revision 1.152  2014/06/18 17:54:09  brouard
                    725:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    726: 
1.152     brouard   727:   Revision 1.151  2014/06/18 16:43:30  brouard
                    728:   *** empty log message ***
                    729: 
1.151     brouard   730:   Revision 1.150  2014/06/18 16:42:35  brouard
                    731:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    732:   Author: brouard
                    733: 
1.150     brouard   734:   Revision 1.149  2014/06/18 15:51:14  brouard
                    735:   Summary: Some fixes in parameter files errors
                    736:   Author: Nicolas Brouard
                    737: 
1.149     brouard   738:   Revision 1.148  2014/06/17 17:38:48  brouard
                    739:   Summary: Nothing new
                    740:   Author: Brouard
                    741: 
                    742:   Just a new packaging for OS/X version 0.98nS
                    743: 
1.148     brouard   744:   Revision 1.147  2014/06/16 10:33:11  brouard
                    745:   *** empty log message ***
                    746: 
1.147     brouard   747:   Revision 1.146  2014/06/16 10:20:28  brouard
                    748:   Summary: Merge
                    749:   Author: Brouard
                    750: 
                    751:   Merge, before building revised version.
                    752: 
1.146     brouard   753:   Revision 1.145  2014/06/10 21:23:15  brouard
                    754:   Summary: Debugging with valgrind
                    755:   Author: Nicolas Brouard
                    756: 
                    757:   Lot of changes in order to output the results with some covariates
                    758:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    759:   improve the code.
                    760:   No more memory valgrind error but a lot has to be done in order to
                    761:   continue the work of splitting the code into subroutines.
                    762:   Also, decodemodel has been improved. Tricode is still not
                    763:   optimal. nbcode should be improved. Documentation has been added in
                    764:   the source code.
                    765: 
1.144     brouard   766:   Revision 1.143  2014/01/26 09:45:38  brouard
                    767:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    768: 
                    769:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    770:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    771: 
1.143     brouard   772:   Revision 1.142  2014/01/26 03:57:36  brouard
                    773:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    774: 
                    775:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    776: 
1.142     brouard   777:   Revision 1.141  2014/01/26 02:42:01  brouard
                    778:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    779: 
1.141     brouard   780:   Revision 1.140  2011/09/02 10:37:54  brouard
                    781:   Summary: times.h is ok with mingw32 now.
                    782: 
1.140     brouard   783:   Revision 1.139  2010/06/14 07:50:17  brouard
                    784:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    785:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    786: 
1.139     brouard   787:   Revision 1.138  2010/04/30 18:19:40  brouard
                    788:   *** empty log message ***
                    789: 
1.138     brouard   790:   Revision 1.137  2010/04/29 18:11:38  brouard
                    791:   (Module): Checking covariates for more complex models
                    792:   than V1+V2. A lot of change to be done. Unstable.
                    793: 
1.137     brouard   794:   Revision 1.136  2010/04/26 20:30:53  brouard
                    795:   (Module): merging some libgsl code. Fixing computation
                    796:   of likelione (using inter/intrapolation if mle = 0) in order to
                    797:   get same likelihood as if mle=1.
                    798:   Some cleaning of code and comments added.
                    799: 
1.136     brouard   800:   Revision 1.135  2009/10/29 15:33:14  brouard
                    801:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    802: 
1.135     brouard   803:   Revision 1.134  2009/10/29 13:18:53  brouard
                    804:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    805: 
1.134     brouard   806:   Revision 1.133  2009/07/06 10:21:25  brouard
                    807:   just nforces
                    808: 
1.133     brouard   809:   Revision 1.132  2009/07/06 08:22:05  brouard
                    810:   Many tings
                    811: 
1.132     brouard   812:   Revision 1.131  2009/06/20 16:22:47  brouard
                    813:   Some dimensions resccaled
                    814: 
1.131     brouard   815:   Revision 1.130  2009/05/26 06:44:34  brouard
                    816:   (Module): Max Covariate is now set to 20 instead of 8. A
                    817:   lot of cleaning with variables initialized to 0. Trying to make
                    818:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    819: 
1.130     brouard   820:   Revision 1.129  2007/08/31 13:49:27  lievre
                    821:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    822: 
1.129     lievre    823:   Revision 1.128  2006/06/30 13:02:05  brouard
                    824:   (Module): Clarifications on computing e.j
                    825: 
1.128     brouard   826:   Revision 1.127  2006/04/28 18:11:50  brouard
                    827:   (Module): Yes the sum of survivors was wrong since
                    828:   imach-114 because nhstepm was no more computed in the age
                    829:   loop. Now we define nhstepma in the age loop.
                    830:   (Module): In order to speed up (in case of numerous covariates) we
                    831:   compute health expectancies (without variances) in a first step
                    832:   and then all the health expectancies with variances or standard
                    833:   deviation (needs data from the Hessian matrices) which slows the
                    834:   computation.
                    835:   In the future we should be able to stop the program is only health
                    836:   expectancies and graph are needed without standard deviations.
                    837: 
1.127     brouard   838:   Revision 1.126  2006/04/28 17:23:28  brouard
                    839:   (Module): Yes the sum of survivors was wrong since
                    840:   imach-114 because nhstepm was no more computed in the age
                    841:   loop. Now we define nhstepma in the age loop.
                    842:   Version 0.98h
                    843: 
1.126     brouard   844:   Revision 1.125  2006/04/04 15:20:31  lievre
                    845:   Errors in calculation of health expectancies. Age was not initialized.
                    846:   Forecasting file added.
                    847: 
                    848:   Revision 1.124  2006/03/22 17:13:53  lievre
                    849:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    850:   The log-likelihood is printed in the log file
                    851: 
                    852:   Revision 1.123  2006/03/20 10:52:43  brouard
                    853:   * imach.c (Module): <title> changed, corresponds to .htm file
                    854:   name. <head> headers where missing.
                    855: 
                    856:   * imach.c (Module): Weights can have a decimal point as for
                    857:   English (a comma might work with a correct LC_NUMERIC environment,
                    858:   otherwise the weight is truncated).
                    859:   Modification of warning when the covariates values are not 0 or
                    860:   1.
                    861:   Version 0.98g
                    862: 
                    863:   Revision 1.122  2006/03/20 09:45:41  brouard
                    864:   (Module): Weights can have a decimal point as for
                    865:   English (a comma might work with a correct LC_NUMERIC environment,
                    866:   otherwise the weight is truncated).
                    867:   Modification of warning when the covariates values are not 0 or
                    868:   1.
                    869:   Version 0.98g
                    870: 
                    871:   Revision 1.121  2006/03/16 17:45:01  lievre
                    872:   * imach.c (Module): Comments concerning covariates added
                    873: 
                    874:   * imach.c (Module): refinements in the computation of lli if
                    875:   status=-2 in order to have more reliable computation if stepm is
                    876:   not 1 month. Version 0.98f
                    877: 
                    878:   Revision 1.120  2006/03/16 15:10:38  lievre
                    879:   (Module): refinements in the computation of lli if
                    880:   status=-2 in order to have more reliable computation if stepm is
                    881:   not 1 month. Version 0.98f
                    882: 
                    883:   Revision 1.119  2006/03/15 17:42:26  brouard
                    884:   (Module): Bug if status = -2, the loglikelihood was
                    885:   computed as likelihood omitting the logarithm. Version O.98e
                    886: 
                    887:   Revision 1.118  2006/03/14 18:20:07  brouard
                    888:   (Module): varevsij Comments added explaining the second
                    889:   table of variances if popbased=1 .
                    890:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    891:   (Module): Function pstamp added
                    892:   (Module): Version 0.98d
                    893: 
                    894:   Revision 1.117  2006/03/14 17:16:22  brouard
                    895:   (Module): varevsij Comments added explaining the second
                    896:   table of variances if popbased=1 .
                    897:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    898:   (Module): Function pstamp added
                    899:   (Module): Version 0.98d
                    900: 
                    901:   Revision 1.116  2006/03/06 10:29:27  brouard
                    902:   (Module): Variance-covariance wrong links and
                    903:   varian-covariance of ej. is needed (Saito).
                    904: 
                    905:   Revision 1.115  2006/02/27 12:17:45  brouard
                    906:   (Module): One freematrix added in mlikeli! 0.98c
                    907: 
                    908:   Revision 1.114  2006/02/26 12:57:58  brouard
                    909:   (Module): Some improvements in processing parameter
                    910:   filename with strsep.
                    911: 
                    912:   Revision 1.113  2006/02/24 14:20:24  brouard
                    913:   (Module): Memory leaks checks with valgrind and:
                    914:   datafile was not closed, some imatrix were not freed and on matrix
                    915:   allocation too.
                    916: 
                    917:   Revision 1.112  2006/01/30 09:55:26  brouard
                    918:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    919: 
                    920:   Revision 1.111  2006/01/25 20:38:18  brouard
                    921:   (Module): Lots of cleaning and bugs added (Gompertz)
                    922:   (Module): Comments can be added in data file. Missing date values
                    923:   can be a simple dot '.'.
                    924: 
                    925:   Revision 1.110  2006/01/25 00:51:50  brouard
                    926:   (Module): Lots of cleaning and bugs added (Gompertz)
                    927: 
                    928:   Revision 1.109  2006/01/24 19:37:15  brouard
                    929:   (Module): Comments (lines starting with a #) are allowed in data.
                    930: 
                    931:   Revision 1.108  2006/01/19 18:05:42  lievre
                    932:   Gnuplot problem appeared...
                    933:   To be fixed
                    934: 
                    935:   Revision 1.107  2006/01/19 16:20:37  brouard
                    936:   Test existence of gnuplot in imach path
                    937: 
                    938:   Revision 1.106  2006/01/19 13:24:36  brouard
                    939:   Some cleaning and links added in html output
                    940: 
                    941:   Revision 1.105  2006/01/05 20:23:19  lievre
                    942:   *** empty log message ***
                    943: 
                    944:   Revision 1.104  2005/09/30 16:11:43  lievre
                    945:   (Module): sump fixed, loop imx fixed, and simplifications.
                    946:   (Module): If the status is missing at the last wave but we know
                    947:   that the person is alive, then we can code his/her status as -2
                    948:   (instead of missing=-1 in earlier versions) and his/her
                    949:   contributions to the likelihood is 1 - Prob of dying from last
                    950:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    951:   the healthy state at last known wave). Version is 0.98
                    952: 
                    953:   Revision 1.103  2005/09/30 15:54:49  lievre
                    954:   (Module): sump fixed, loop imx fixed, and simplifications.
                    955: 
                    956:   Revision 1.102  2004/09/15 17:31:30  brouard
                    957:   Add the possibility to read data file including tab characters.
                    958: 
                    959:   Revision 1.101  2004/09/15 10:38:38  brouard
                    960:   Fix on curr_time
                    961: 
                    962:   Revision 1.100  2004/07/12 18:29:06  brouard
                    963:   Add version for Mac OS X. Just define UNIX in Makefile
                    964: 
                    965:   Revision 1.99  2004/06/05 08:57:40  brouard
                    966:   *** empty log message ***
                    967: 
                    968:   Revision 1.98  2004/05/16 15:05:56  brouard
                    969:   New version 0.97 . First attempt to estimate force of mortality
                    970:   directly from the data i.e. without the need of knowing the health
                    971:   state at each age, but using a Gompertz model: log u =a + b*age .
                    972:   This is the basic analysis of mortality and should be done before any
                    973:   other analysis, in order to test if the mortality estimated from the
                    974:   cross-longitudinal survey is different from the mortality estimated
                    975:   from other sources like vital statistic data.
                    976: 
                    977:   The same imach parameter file can be used but the option for mle should be -3.
                    978: 
1.324     brouard   979:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   980:   former routines in order to include the new code within the former code.
                    981: 
                    982:   The output is very simple: only an estimate of the intercept and of
                    983:   the slope with 95% confident intervals.
                    984: 
                    985:   Current limitations:
                    986:   A) Even if you enter covariates, i.e. with the
                    987:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    988:   B) There is no computation of Life Expectancy nor Life Table.
                    989: 
                    990:   Revision 1.97  2004/02/20 13:25:42  lievre
                    991:   Version 0.96d. Population forecasting command line is (temporarily)
                    992:   suppressed.
                    993: 
                    994:   Revision 1.96  2003/07/15 15:38:55  brouard
                    995:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    996:   rewritten within the same printf. Workaround: many printfs.
                    997: 
                    998:   Revision 1.95  2003/07/08 07:54:34  brouard
                    999:   * imach.c (Repository):
                   1000:   (Repository): Using imachwizard code to output a more meaningful covariance
                   1001:   matrix (cov(a12,c31) instead of numbers.
                   1002: 
                   1003:   Revision 1.94  2003/06/27 13:00:02  brouard
                   1004:   Just cleaning
                   1005: 
                   1006:   Revision 1.93  2003/06/25 16:33:55  brouard
                   1007:   (Module): On windows (cygwin) function asctime_r doesn't
                   1008:   exist so I changed back to asctime which exists.
                   1009:   (Module): Version 0.96b
                   1010: 
                   1011:   Revision 1.92  2003/06/25 16:30:45  brouard
                   1012:   (Module): On windows (cygwin) function asctime_r doesn't
                   1013:   exist so I changed back to asctime which exists.
                   1014: 
                   1015:   Revision 1.91  2003/06/25 15:30:29  brouard
                   1016:   * imach.c (Repository): Duplicated warning errors corrected.
                   1017:   (Repository): Elapsed time after each iteration is now output. It
                   1018:   helps to forecast when convergence will be reached. Elapsed time
                   1019:   is stamped in powell.  We created a new html file for the graphs
                   1020:   concerning matrix of covariance. It has extension -cov.htm.
                   1021: 
                   1022:   Revision 1.90  2003/06/24 12:34:15  brouard
                   1023:   (Module): Some bugs corrected for windows. Also, when
                   1024:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1025:   of the covariance matrix to be input.
                   1026: 
                   1027:   Revision 1.89  2003/06/24 12:30:52  brouard
                   1028:   (Module): Some bugs corrected for windows. Also, when
                   1029:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1030:   of the covariance matrix to be input.
                   1031: 
                   1032:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1033:   * 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.
                   1034: 
                   1035:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1036:   Version 0.96
                   1037: 
                   1038:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1039:   (Module): Change position of html and gnuplot routines and added
                   1040:   routine fileappend.
                   1041: 
                   1042:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1043:   * imach.c (Repository): Check when date of death was earlier that
                   1044:   current date of interview. It may happen when the death was just
                   1045:   prior to the death. In this case, dh was negative and likelihood
                   1046:   was wrong (infinity). We still send an "Error" but patch by
                   1047:   assuming that the date of death was just one stepm after the
                   1048:   interview.
                   1049:   (Repository): Because some people have very long ID (first column)
                   1050:   we changed int to long in num[] and we added a new lvector for
                   1051:   memory allocation. But we also truncated to 8 characters (left
                   1052:   truncation)
                   1053:   (Repository): No more line truncation errors.
                   1054: 
                   1055:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1056:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1057:   place. It differs from routine "prevalence" which may be called
                   1058:   many times. Probs is memory consuming and must be used with
                   1059:   parcimony.
                   1060:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1061: 
                   1062:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1063:   *** empty log message ***
                   1064: 
                   1065:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1066:   Add log in  imach.c and  fullversion number is now printed.
                   1067: 
                   1068: */
                   1069: /*
                   1070:    Interpolated Markov Chain
                   1071: 
                   1072:   Short summary of the programme:
                   1073:   
1.227     brouard  1074:   This program computes Healthy Life Expectancies or State-specific
                   1075:   (if states aren't health statuses) Expectancies from
                   1076:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1077: 
                   1078:   -1- a first survey ("cross") where individuals from different ages
                   1079:   are interviewed on their health status or degree of disability (in
                   1080:   the case of a health survey which is our main interest)
                   1081: 
                   1082:   -2- at least a second wave of interviews ("longitudinal") which
                   1083:   measure each change (if any) in individual health status.  Health
                   1084:   expectancies are computed from the time spent in each health state
                   1085:   according to a model. More health states you consider, more time is
                   1086:   necessary to reach the Maximum Likelihood of the parameters involved
                   1087:   in the model.  The simplest model is the multinomial logistic model
                   1088:   where pij is the probability to be observed in state j at the second
                   1089:   wave conditional to be observed in state i at the first
                   1090:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1091:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1092:   have a more complex model than "constant and age", you should modify
                   1093:   the program where the markup *Covariates have to be included here
                   1094:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1095:   convergence.
                   1096: 
                   1097:   The advantage of this computer programme, compared to a simple
                   1098:   multinomial logistic model, is clear when the delay between waves is not
                   1099:   identical for each individual. Also, if a individual missed an
                   1100:   intermediate interview, the information is lost, but taken into
                   1101:   account using an interpolation or extrapolation.  
                   1102: 
                   1103:   hPijx is the probability to be observed in state i at age x+h
                   1104:   conditional to the observed state i at age x. The delay 'h' can be
                   1105:   split into an exact number (nh*stepm) of unobserved intermediate
                   1106:   states. This elementary transition (by month, quarter,
                   1107:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1108:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1109:   and the contribution of each individual to the likelihood is simply
                   1110:   hPijx.
                   1111: 
                   1112:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1113:   of the life expectancies. It also computes the period (stable) prevalence.
                   1114: 
                   1115: Back prevalence and projections:
1.227     brouard  1116: 
                   1117:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1118:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1119:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1120:    mobilavproj)
                   1121: 
                   1122:     Computes the back prevalence limit for any combination of
                   1123:     covariate values k at any age between ageminpar and agemaxpar and
                   1124:     returns it in **bprlim. In the loops,
                   1125: 
                   1126:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1127:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1128: 
                   1129:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1130:    Computes for any combination of covariates k and any age between bage and fage 
                   1131:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1132:                        oldm=oldms;savm=savms;
1.227     brouard  1133: 
1.267     brouard  1134:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1135:      Computes the transition matrix starting at age 'age' over
                   1136:      'nhstepm*hstepm*stepm' months (i.e. until
                   1137:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1138:      nhstepm*hstepm matrices. 
                   1139: 
                   1140:      Returns p3mat[i][j][h] after calling
                   1141:      p3mat[i][j][h]=matprod2(newm,
                   1142:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1143:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1144:      oldm);
1.226     brouard  1145: 
                   1146: Important routines
                   1147: 
                   1148: - func (or funcone), computes logit (pij) distinguishing
                   1149:   o fixed variables (single or product dummies or quantitative);
                   1150:   o varying variables by:
                   1151:    (1) wave (single, product dummies, quantitative), 
                   1152:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1153:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1154:        % varying dummy (not done) or quantitative (not done);
                   1155: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1156:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1157: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1158:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1159:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1160: 
1.226     brouard  1161: 
                   1162:   
1.324     brouard  1163:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1164:            Institut national d'études démographiques, Paris.
1.126     brouard  1165:   This software have been partly granted by Euro-REVES, a concerted action
                   1166:   from the European Union.
                   1167:   It is copyrighted identically to a GNU software product, ie programme and
                   1168:   software can be distributed freely for non commercial use. Latest version
                   1169:   can be accessed at http://euroreves.ined.fr/imach .
                   1170: 
                   1171:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1172:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1173:   
                   1174:   **********************************************************************/
                   1175: /*
                   1176:   main
                   1177:   read parameterfile
                   1178:   read datafile
                   1179:   concatwav
                   1180:   freqsummary
                   1181:   if (mle >= 1)
                   1182:     mlikeli
                   1183:   print results files
                   1184:   if mle==1 
                   1185:      computes hessian
                   1186:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1187:       begin-prev-date,...
                   1188:   open gnuplot file
                   1189:   open html file
1.145     brouard  1190:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1191:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1192:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1193:     freexexit2 possible for memory heap.
                   1194: 
                   1195:   h Pij x                         | pij_nom  ficrestpij
                   1196:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1197:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1198:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1199: 
                   1200:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1201:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1202:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1203:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1204:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1205: 
1.126     brouard  1206:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1207:   health expectancies
                   1208:   Variance-covariance of DFLE
                   1209:   prevalence()
                   1210:    movingaverage()
                   1211:   varevsij() 
                   1212:   if popbased==1 varevsij(,popbased)
                   1213:   total life expectancies
                   1214:   Variance of period (stable) prevalence
                   1215:  end
                   1216: */
                   1217: 
1.187     brouard  1218: /* #define DEBUG */
                   1219: /* #define DEBUGBRENT */
1.203     brouard  1220: /* #define DEBUGLINMIN */
                   1221: /* #define DEBUGHESS */
                   1222: #define DEBUGHESSIJ
1.224     brouard  1223: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1224: #define POWELL /* Instead of NLOPT */
1.224     brouard  1225: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1226: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1227: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1228: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.126     brouard  1229: 
                   1230: #include <math.h>
                   1231: #include <stdio.h>
                   1232: #include <stdlib.h>
                   1233: #include <string.h>
1.226     brouard  1234: #include <ctype.h>
1.159     brouard  1235: 
                   1236: #ifdef _WIN32
                   1237: #include <io.h>
1.172     brouard  1238: #include <windows.h>
                   1239: #include <tchar.h>
1.159     brouard  1240: #else
1.126     brouard  1241: #include <unistd.h>
1.159     brouard  1242: #endif
1.126     brouard  1243: 
                   1244: #include <limits.h>
                   1245: #include <sys/types.h>
1.171     brouard  1246: 
                   1247: #if defined(__GNUC__)
                   1248: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1249: #endif
                   1250: 
1.126     brouard  1251: #include <sys/stat.h>
                   1252: #include <errno.h>
1.159     brouard  1253: /* extern int errno; */
1.126     brouard  1254: 
1.157     brouard  1255: /* #ifdef LINUX */
                   1256: /* #include <time.h> */
                   1257: /* #include "timeval.h" */
                   1258: /* #else */
                   1259: /* #include <sys/time.h> */
                   1260: /* #endif */
                   1261: 
1.126     brouard  1262: #include <time.h>
                   1263: 
1.136     brouard  1264: #ifdef GSL
                   1265: #include <gsl/gsl_errno.h>
                   1266: #include <gsl/gsl_multimin.h>
                   1267: #endif
                   1268: 
1.167     brouard  1269: 
1.162     brouard  1270: #ifdef NLOPT
                   1271: #include <nlopt.h>
                   1272: typedef struct {
                   1273:   double (* function)(double [] );
                   1274: } myfunc_data ;
                   1275: #endif
                   1276: 
1.126     brouard  1277: /* #include <libintl.h> */
                   1278: /* #define _(String) gettext (String) */
                   1279: 
1.251     brouard  1280: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1281: 
                   1282: #define GNUPLOTPROGRAM "gnuplot"
                   1283: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1284: #define FILENAMELENGTH 256
1.126     brouard  1285: 
                   1286: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1287: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1288: 
1.144     brouard  1289: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1290: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1291: 
                   1292: #define NINTERVMAX 8
1.144     brouard  1293: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1294: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1295: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1296: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1297: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1298: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1299: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1300: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1301: /* #define AGESUP 130 */
1.288     brouard  1302: /* #define AGESUP 150 */
                   1303: #define AGESUP 200
1.268     brouard  1304: #define AGEINF 0
1.218     brouard  1305: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1306: #define AGEBASE 40
1.194     brouard  1307: #define AGEOVERFLOW 1.e20
1.164     brouard  1308: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1309: #ifdef _WIN32
                   1310: #define DIRSEPARATOR '\\'
                   1311: #define CHARSEPARATOR "\\"
                   1312: #define ODIRSEPARATOR '/'
                   1313: #else
1.126     brouard  1314: #define DIRSEPARATOR '/'
                   1315: #define CHARSEPARATOR "/"
                   1316: #define ODIRSEPARATOR '\\'
                   1317: #endif
                   1318: 
1.341   ! brouard  1319: /* $Id: imach.c,v 1.340 2022/09/11 07:53:11 brouard Exp $ */
1.126     brouard  1320: /* $State: Exp $ */
1.196     brouard  1321: #include "version.h"
                   1322: char version[]=__IMACH_VERSION__;
1.337     brouard  1323: char copyright[]="September 2022,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.341   ! brouard  1324: char fullversion[]="$Revision: 1.340 $ $Date: 2022/09/11 07:53:11 $"; 
1.126     brouard  1325: char strstart[80];
                   1326: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1327: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard  1328: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1329: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1330: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
1.335     brouard  1331: 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  1332: 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  1333: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1334: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1335: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1336: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335     brouard  1337: 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  1338: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1339: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.339     brouard  1340: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
1.232     brouard  1341: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1342: int nsd=0; /**< Total number of single dummy variables (output) */
                   1343: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1344: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1345: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1346: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1347: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1348: int cptcov=0; /* Working variable */
1.334     brouard  1349: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1350: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1351: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1352: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1353: int nlstate=2; /* Number of live states */
                   1354: int ndeath=1; /* Number of dead states */
1.130     brouard  1355: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.339     brouard  1356: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
                   1357: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
1.126     brouard  1358: int popbased=0;
                   1359: 
                   1360: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1361: int maxwav=0; /* Maxim number of waves */
                   1362: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1363: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1364: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1365:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1366: int mle=1, weightopt=0;
1.126     brouard  1367: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1368: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1369: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1370:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1371: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1372: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1373: 
1.130     brouard  1374: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1375: double **matprod2(); /* test */
1.126     brouard  1376: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1377: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1378: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1379: 
1.136     brouard  1380: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1381: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1382: FILE *ficlog, *ficrespow;
1.130     brouard  1383: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1384: double fretone; /* Only one call to likelihood */
1.130     brouard  1385: long ipmx=0; /* Number of contributions */
1.126     brouard  1386: double sw; /* Sum of weights */
                   1387: char filerespow[FILENAMELENGTH];
                   1388: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1389: FILE *ficresilk;
                   1390: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1391: FILE *ficresprobmorprev;
                   1392: FILE *fichtm, *fichtmcov; /* Html File */
                   1393: FILE *ficreseij;
                   1394: char filerese[FILENAMELENGTH];
                   1395: FILE *ficresstdeij;
                   1396: char fileresstde[FILENAMELENGTH];
                   1397: FILE *ficrescveij;
                   1398: char filerescve[FILENAMELENGTH];
                   1399: FILE  *ficresvij;
                   1400: char fileresv[FILENAMELENGTH];
1.269     brouard  1401: 
1.126     brouard  1402: char title[MAXLINE];
1.234     brouard  1403: char model[MAXLINE]; /**< The model line */
1.217     brouard  1404: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1405: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1406: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1407: char command[FILENAMELENGTH];
                   1408: int  outcmd=0;
                   1409: 
1.217     brouard  1410: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1411: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1412: char filelog[FILENAMELENGTH]; /* Log file */
                   1413: char filerest[FILENAMELENGTH];
                   1414: char fileregp[FILENAMELENGTH];
                   1415: char popfile[FILENAMELENGTH];
                   1416: 
                   1417: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1418: 
1.157     brouard  1419: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1420: /* struct timezone tzp; */
                   1421: /* extern int gettimeofday(); */
                   1422: struct tm tml, *gmtime(), *localtime();
                   1423: 
                   1424: extern time_t time();
                   1425: 
                   1426: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1427: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1428: struct tm tm;
                   1429: 
1.126     brouard  1430: char strcurr[80], strfor[80];
                   1431: 
                   1432: char *endptr;
                   1433: long lval;
                   1434: double dval;
                   1435: 
                   1436: #define NR_END 1
                   1437: #define FREE_ARG char*
                   1438: #define FTOL 1.0e-10
                   1439: 
                   1440: #define NRANSI 
1.240     brouard  1441: #define ITMAX 200
                   1442: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1443: 
                   1444: #define TOL 2.0e-4 
                   1445: 
                   1446: #define CGOLD 0.3819660 
                   1447: #define ZEPS 1.0e-10 
                   1448: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1449: 
                   1450: #define GOLD 1.618034 
                   1451: #define GLIMIT 100.0 
                   1452: #define TINY 1.0e-20 
                   1453: 
                   1454: static double maxarg1,maxarg2;
                   1455: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1456: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1457:   
                   1458: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1459: #define rint(a) floor(a+0.5)
1.166     brouard  1460: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1461: #define mytinydouble 1.0e-16
1.166     brouard  1462: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1463: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1464: /* static double dsqrarg; */
                   1465: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1466: static double sqrarg;
                   1467: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1468: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1469: int agegomp= AGEGOMP;
                   1470: 
                   1471: int imx; 
                   1472: int stepm=1;
                   1473: /* Stepm, step in month: minimum step interpolation*/
                   1474: 
                   1475: int estepm;
                   1476: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1477: 
                   1478: int m,nb;
                   1479: long *num;
1.197     brouard  1480: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1481: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1482:                   covariate for which somebody answered excluding 
                   1483:                   undefined. Usually 2: 0 and 1. */
                   1484: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1485:                             covariate for which somebody answered including 
                   1486:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1487: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1488: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1489: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1490: 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  1491: double *ageexmed,*agecens;
                   1492: double dateintmean=0;
1.296     brouard  1493:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1494:   double anprojf, mprojf, jprojf;
1.126     brouard  1495: 
1.296     brouard  1496:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1497:   double anbackf, mbackf, jbackf;
                   1498:   double jintmean,mintmean,aintmean;  
1.126     brouard  1499: double *weight;
                   1500: int **s; /* Status */
1.141     brouard  1501: double *agedc;
1.145     brouard  1502: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1503:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1504:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1505: double **coqvar; /* Fixed quantitative covariate nqv */
1.341   ! brouard  1506: double ***cotvar; /* Time varying covariate start at ncovcol + nqv + (1 to ntv) */
1.225     brouard  1507: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1508: double  idx; 
                   1509: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1510: /* Some documentation */
                   1511:       /*   Design original data
                   1512:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1513:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1514:        *                                                             ntv=3     nqtv=1
1.330     brouard  1515:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1516:        * For time varying covariate, quanti or dummies
                   1517:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
1.341   ! brouard  1518:        *       cotvar[wav][ncovcol+nqv+ iv(1 to nqtv)][i]= [(1 to nqtv)][i]=(V12) quanti
1.319     brouard  1519:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1520:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1521:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1522:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1523:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1524:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1525:        */
                   1526: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1527: /* 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
                   1528:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1529:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1530: */
1.319     brouard  1531: /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1532: /*    k        1  2   3   4     5    6    7     8    9 */
                   1533: /*Typevar[k]=  0  0   0   2     1    0    2     1    0 *//*0 for simple covariate (dummy, quantitative,*/
                   1534:                                                          /* fixed or varying), 1 for age product, 2 for*/
                   1535:                                                          /* product */
                   1536: /*Dummy[k]=    1  0   0   1     3    1    1     2    0 *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1537:                                                          /*(single or product without age), 2 dummy*/
                   1538:                                                          /* with age product, 3 quant with age product*/
                   1539: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
                   1540: /*    nsd         1   2                              3 */ /* Counting single dummies covar fixed or tv */
1.330     brouard  1541: /*TnsdVar[Tvar]   1   2                              3 */ 
1.337     brouard  1542: /*Tvaraff[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
1.319     brouard  1543: /*TvarsD[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
1.338     brouard  1544: /*TvarsDind[nsd]  2   3                              9 */ /* position K of single dummy cova */
1.319     brouard  1545: /*    nsq      1                     2                 */ /* Counting single quantit tv */
                   1546: /* TvarsQ[k]   5                     2                 */ /* Number of single quantitative cova */
                   1547: /* TvarsQind   1                     6                 */ /* position K of single quantitative cova */
                   1548: /* Tprod[i]=k             1               2            */ /* Position in model of the ith prod without age */
                   1549: /* cptcovage                    1               2      */ /* Counting cov*age in the model equation */
                   1550: /* Tage[cptcovage]=k            5               8      */ /* Position in the model of ith cov*age */
                   1551: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2              */ /* Position in model of the ith prod without age */
1.330     brouard  1552: /* 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  1553: /* 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  1554: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1555: /* Type                    */
                   1556: /* V         1  2  3  4  5 */
                   1557: /*           F  F  V  V  V */
                   1558: /*           D  Q  D  D  Q */
                   1559: /*                         */
                   1560: int *TvarsD;
1.330     brouard  1561: int *TnsdVar;
1.234     brouard  1562: int *TvarsDind;
                   1563: int *TvarsQ;
                   1564: int *TvarsQind;
                   1565: 
1.318     brouard  1566: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1567: int nresult=0;
1.258     brouard  1568: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1569: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1570: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1571: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1572: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1573: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1574: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1575: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1576: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1577: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1578: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1579: 
                   1580: /* 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
                   1581:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1582:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1583: */
1.234     brouard  1584: /* 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  1585: 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 */
                   1586: 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 */
                   1587: 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 */
                   1588: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1589: 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 */
                   1590: 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  1591: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1592: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1593: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1594: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1595: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1596: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1597: 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 */
                   1598: 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  1599: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1600: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1601:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   1602:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   1603:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   1604:       /* TvarVV={3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */            
                   1605:       /* TvarVVind={2,5,5}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */         
1.230     brouard  1606: int *Tvarsel; /**< Selected covariates for output */
                   1607: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1608: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1609: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1610: 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  1611: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1612: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1613: int *Tage;
1.227     brouard  1614: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1615: 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  1616: 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*/ 
                   1617: 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  1618: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1619: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1620: int **Tvard;
1.330     brouard  1621: int **Tvardk;
1.227     brouard  1622: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1623: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1624: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1625:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1626:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1627: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1628: double *lsurv, *lpop, *tpop;
                   1629: 
1.231     brouard  1630: #define FD 1; /* Fixed dummy covariate */
                   1631: #define FQ 2; /* Fixed quantitative covariate */
                   1632: #define FP 3; /* Fixed product covariate */
                   1633: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1634: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1635: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1636: #define VD 10; /* Varying dummy covariate */
                   1637: #define VQ 11; /* Varying quantitative covariate */
                   1638: #define VP 12; /* Varying product covariate */
                   1639: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1640: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1641: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1642: #define APFD 16; /* Age product * fixed dummy covariate */
                   1643: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1644: #define APVD 18; /* Age product * varying dummy covariate */
                   1645: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1646: 
                   1647: #define FTYPE 1; /* Fixed covariate */
                   1648: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1649: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1650: 
                   1651: struct kmodel{
                   1652:        int maintype; /* main type */
                   1653:        int subtype; /* subtype */
                   1654: };
                   1655: struct kmodel modell[NCOVMAX];
                   1656: 
1.143     brouard  1657: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1658: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1659: 
                   1660: /**************** split *************************/
                   1661: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1662: {
                   1663:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1664:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1665:   */ 
                   1666:   char *ss;                            /* pointer */
1.186     brouard  1667:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1668: 
                   1669:   l1 = strlen(path );                  /* length of path */
                   1670:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1671:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1672:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1673:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1674:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1675:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1676:     /* get current working directory */
                   1677:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1678: #ifdef WIN32
                   1679:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1680: #else
                   1681:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1682: #endif
1.126     brouard  1683:       return( GLOCK_ERROR_GETCWD );
                   1684:     }
                   1685:     /* got dirc from getcwd*/
                   1686:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1687:   } else {                             /* strip directory from path */
1.126     brouard  1688:     ss++;                              /* after this, the filename */
                   1689:     l2 = strlen( ss );                 /* length of filename */
                   1690:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1691:     strcpy( name, ss );                /* save file name */
                   1692:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1693:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1694:     printf(" DIRC2 = %s \n",dirc);
                   1695:   }
                   1696:   /* We add a separator at the end of dirc if not exists */
                   1697:   l1 = strlen( dirc );                 /* length of directory */
                   1698:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1699:     dirc[l1] =  DIRSEPARATOR;
                   1700:     dirc[l1+1] = 0; 
                   1701:     printf(" DIRC3 = %s \n",dirc);
                   1702:   }
                   1703:   ss = strrchr( name, '.' );           /* find last / */
                   1704:   if (ss >0){
                   1705:     ss++;
                   1706:     strcpy(ext,ss);                    /* save extension */
                   1707:     l1= strlen( name);
                   1708:     l2= strlen(ss)+1;
                   1709:     strncpy( finame, name, l1-l2);
                   1710:     finame[l1-l2]= 0;
                   1711:   }
                   1712: 
                   1713:   return( 0 );                         /* we're done */
                   1714: }
                   1715: 
                   1716: 
                   1717: /******************************************/
                   1718: 
                   1719: void replace_back_to_slash(char *s, char*t)
                   1720: {
                   1721:   int i;
                   1722:   int lg=0;
                   1723:   i=0;
                   1724:   lg=strlen(t);
                   1725:   for(i=0; i<= lg; i++) {
                   1726:     (s[i] = t[i]);
                   1727:     if (t[i]== '\\') s[i]='/';
                   1728:   }
                   1729: }
                   1730: 
1.132     brouard  1731: char *trimbb(char *out, char *in)
1.137     brouard  1732: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1733:   char *s;
                   1734:   s=out;
                   1735:   while (*in != '\0'){
1.137     brouard  1736:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1737:       in++;
                   1738:     }
                   1739:     *out++ = *in++;
                   1740:   }
                   1741:   *out='\0';
                   1742:   return s;
                   1743: }
                   1744: 
1.187     brouard  1745: /* char *substrchaine(char *out, char *in, char *chain) */
                   1746: /* { */
                   1747: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1748: /*   char *s, *t; */
                   1749: /*   t=in;s=out; */
                   1750: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1751: /*     *out++ = *in++; */
                   1752: /*   } */
                   1753: 
                   1754: /*   /\* *in matches *chain *\/ */
                   1755: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1756: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1757: /*   } */
                   1758: /*   in--; chain--; */
                   1759: /*   while ( (*in != '\0')){ */
                   1760: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1761: /*     *out++ = *in++; */
                   1762: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1763: /*   } */
                   1764: /*   *out='\0'; */
                   1765: /*   out=s; */
                   1766: /*   return out; */
                   1767: /* } */
                   1768: char *substrchaine(char *out, char *in, char *chain)
                   1769: {
                   1770:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1771:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1772: 
                   1773:   char *strloc;
                   1774: 
                   1775:   strcpy (out, in); 
                   1776:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1777:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1778:   if(strloc != NULL){ 
                   1779:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1780:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1781:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1782:   }
                   1783:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1784:   return out;
                   1785: }
                   1786: 
                   1787: 
1.145     brouard  1788: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1789: {
1.187     brouard  1790:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1791:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1792:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1793:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1794:   */
1.160     brouard  1795:   char *s, *t;
1.145     brouard  1796:   t=in;s=in;
                   1797:   while ((*in != occ) && (*in != '\0')){
                   1798:     *alocc++ = *in++;
                   1799:   }
                   1800:   if( *in == occ){
                   1801:     *(alocc)='\0';
                   1802:     s=++in;
                   1803:   }
                   1804:  
                   1805:   if (s == t) {/* occ not found */
                   1806:     *(alocc-(in-s))='\0';
                   1807:     in=s;
                   1808:   }
                   1809:   while ( *in != '\0'){
                   1810:     *blocc++ = *in++;
                   1811:   }
                   1812: 
                   1813:   *blocc='\0';
                   1814:   return t;
                   1815: }
1.137     brouard  1816: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1817: {
1.187     brouard  1818:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1819:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1820:      gives blocc="abcdef2ghi" and alocc="j".
                   1821:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1822:   */
                   1823:   char *s, *t;
                   1824:   t=in;s=in;
                   1825:   while (*in != '\0'){
                   1826:     while( *in == occ){
                   1827:       *blocc++ = *in++;
                   1828:       s=in;
                   1829:     }
                   1830:     *blocc++ = *in++;
                   1831:   }
                   1832:   if (s == t) /* occ not found */
                   1833:     *(blocc-(in-s))='\0';
                   1834:   else
                   1835:     *(blocc-(in-s)-1)='\0';
                   1836:   in=s;
                   1837:   while ( *in != '\0'){
                   1838:     *alocc++ = *in++;
                   1839:   }
                   1840: 
                   1841:   *alocc='\0';
                   1842:   return s;
                   1843: }
                   1844: 
1.126     brouard  1845: int nbocc(char *s, char occ)
                   1846: {
                   1847:   int i,j=0;
                   1848:   int lg=20;
                   1849:   i=0;
                   1850:   lg=strlen(s);
                   1851:   for(i=0; i<= lg; i++) {
1.234     brouard  1852:     if  (s[i] == occ ) j++;
1.126     brouard  1853:   }
                   1854:   return j;
                   1855: }
                   1856: 
1.137     brouard  1857: /* void cutv(char *u,char *v, char*t, char occ) */
                   1858: /* { */
                   1859: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1860: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1861: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1862: /*   int i,lg,j,p=0; */
                   1863: /*   i=0; */
                   1864: /*   lg=strlen(t); */
                   1865: /*   for(j=0; j<=lg-1; j++) { */
                   1866: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1867: /*   } */
1.126     brouard  1868: 
1.137     brouard  1869: /*   for(j=0; j<p; j++) { */
                   1870: /*     (u[j] = t[j]); */
                   1871: /*   } */
                   1872: /*      u[p]='\0'; */
1.126     brouard  1873: 
1.137     brouard  1874: /*    for(j=0; j<= lg; j++) { */
                   1875: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1876: /*   } */
                   1877: /* } */
1.126     brouard  1878: 
1.160     brouard  1879: #ifdef _WIN32
                   1880: char * strsep(char **pp, const char *delim)
                   1881: {
                   1882:   char *p, *q;
                   1883:          
                   1884:   if ((p = *pp) == NULL)
                   1885:     return 0;
                   1886:   if ((q = strpbrk (p, delim)) != NULL)
                   1887:   {
                   1888:     *pp = q + 1;
                   1889:     *q = '\0';
                   1890:   }
                   1891:   else
                   1892:     *pp = 0;
                   1893:   return p;
                   1894: }
                   1895: #endif
                   1896: 
1.126     brouard  1897: /********************** nrerror ********************/
                   1898: 
                   1899: void nrerror(char error_text[])
                   1900: {
                   1901:   fprintf(stderr,"ERREUR ...\n");
                   1902:   fprintf(stderr,"%s\n",error_text);
                   1903:   exit(EXIT_FAILURE);
                   1904: }
                   1905: /*********************** vector *******************/
                   1906: double *vector(int nl, int nh)
                   1907: {
                   1908:   double *v;
                   1909:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1910:   if (!v) nrerror("allocation failure in vector");
                   1911:   return v-nl+NR_END;
                   1912: }
                   1913: 
                   1914: /************************ free vector ******************/
                   1915: void free_vector(double*v, int nl, int nh)
                   1916: {
                   1917:   free((FREE_ARG)(v+nl-NR_END));
                   1918: }
                   1919: 
                   1920: /************************ivector *******************************/
                   1921: int *ivector(long nl,long nh)
                   1922: {
                   1923:   int *v;
                   1924:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1925:   if (!v) nrerror("allocation failure in ivector");
                   1926:   return v-nl+NR_END;
                   1927: }
                   1928: 
                   1929: /******************free ivector **************************/
                   1930: void free_ivector(int *v, long nl, long nh)
                   1931: {
                   1932:   free((FREE_ARG)(v+nl-NR_END));
                   1933: }
                   1934: 
                   1935: /************************lvector *******************************/
                   1936: long *lvector(long nl,long nh)
                   1937: {
                   1938:   long *v;
                   1939:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1940:   if (!v) nrerror("allocation failure in ivector");
                   1941:   return v-nl+NR_END;
                   1942: }
                   1943: 
                   1944: /******************free lvector **************************/
                   1945: void free_lvector(long *v, long nl, long nh)
                   1946: {
                   1947:   free((FREE_ARG)(v+nl-NR_END));
                   1948: }
                   1949: 
                   1950: /******************* imatrix *******************************/
                   1951: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1952:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1953: { 
                   1954:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1955:   int **m; 
                   1956:   
                   1957:   /* allocate pointers to rows */ 
                   1958:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1959:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1960:   m += NR_END; 
                   1961:   m -= nrl; 
                   1962:   
                   1963:   
                   1964:   /* allocate rows and set pointers to them */ 
                   1965:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1966:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1967:   m[nrl] += NR_END; 
                   1968:   m[nrl] -= ncl; 
                   1969:   
                   1970:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1971:   
                   1972:   /* return pointer to array of pointers to rows */ 
                   1973:   return m; 
                   1974: } 
                   1975: 
                   1976: /****************** free_imatrix *************************/
                   1977: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1978:       int **m;
                   1979:       long nch,ncl,nrh,nrl; 
                   1980:      /* free an int matrix allocated by imatrix() */ 
                   1981: { 
                   1982:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1983:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1984: } 
                   1985: 
                   1986: /******************* matrix *******************************/
                   1987: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1988: {
                   1989:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1990:   double **m;
                   1991: 
                   1992:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1993:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1994:   m += NR_END;
                   1995:   m -= nrl;
                   1996: 
                   1997:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1998:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1999:   m[nrl] += NR_END;
                   2000:   m[nrl] -= ncl;
                   2001: 
                   2002:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2003:   return m;
1.145     brouard  2004:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   2005: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   2006: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  2007:    */
                   2008: }
                   2009: 
                   2010: /*************************free matrix ************************/
                   2011: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   2012: {
                   2013:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2014:   free((FREE_ARG)(m+nrl-NR_END));
                   2015: }
                   2016: 
                   2017: /******************* ma3x *******************************/
                   2018: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   2019: {
                   2020:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   2021:   double ***m;
                   2022: 
                   2023:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2024:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2025:   m += NR_END;
                   2026:   m -= nrl;
                   2027: 
                   2028:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2029:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2030:   m[nrl] += NR_END;
                   2031:   m[nrl] -= ncl;
                   2032: 
                   2033:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2034: 
                   2035:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   2036:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2037:   m[nrl][ncl] += NR_END;
                   2038:   m[nrl][ncl] -= nll;
                   2039:   for (j=ncl+1; j<=nch; j++) 
                   2040:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2041:   
                   2042:   for (i=nrl+1; i<=nrh; i++) {
                   2043:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2044:     for (j=ncl+1; j<=nch; j++) 
                   2045:       m[i][j]=m[i][j-1]+nlay;
                   2046:   }
                   2047:   return m; 
                   2048:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2049:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2050:   */
                   2051: }
                   2052: 
                   2053: /*************************free ma3x ************************/
                   2054: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2055: {
                   2056:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2057:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2058:   free((FREE_ARG)(m+nrl-NR_END));
                   2059: }
                   2060: 
                   2061: /*************** function subdirf ***********/
                   2062: char *subdirf(char fileres[])
                   2063: {
                   2064:   /* Caution optionfilefiname is hidden */
                   2065:   strcpy(tmpout,optionfilefiname);
                   2066:   strcat(tmpout,"/"); /* Add to the right */
                   2067:   strcat(tmpout,fileres);
                   2068:   return tmpout;
                   2069: }
                   2070: 
                   2071: /*************** function subdirf2 ***********/
                   2072: char *subdirf2(char fileres[], char *preop)
                   2073: {
1.314     brouard  2074:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2075:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2076:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2077:   /* Caution optionfilefiname is hidden */
                   2078:   strcpy(tmpout,optionfilefiname);
                   2079:   strcat(tmpout,"/");
                   2080:   strcat(tmpout,preop);
                   2081:   strcat(tmpout,fileres);
                   2082:   return tmpout;
                   2083: }
                   2084: 
                   2085: /*************** function subdirf3 ***********/
                   2086: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2087: {
                   2088:   
                   2089:   /* Caution optionfilefiname is hidden */
                   2090:   strcpy(tmpout,optionfilefiname);
                   2091:   strcat(tmpout,"/");
                   2092:   strcat(tmpout,preop);
                   2093:   strcat(tmpout,preop2);
                   2094:   strcat(tmpout,fileres);
                   2095:   return tmpout;
                   2096: }
1.213     brouard  2097:  
                   2098: /*************** function subdirfext ***********/
                   2099: char *subdirfext(char fileres[], char *preop, char *postop)
                   2100: {
                   2101:   
                   2102:   strcpy(tmpout,preop);
                   2103:   strcat(tmpout,fileres);
                   2104:   strcat(tmpout,postop);
                   2105:   return tmpout;
                   2106: }
1.126     brouard  2107: 
1.213     brouard  2108: /*************** function subdirfext3 ***********/
                   2109: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2110: {
                   2111:   
                   2112:   /* Caution optionfilefiname is hidden */
                   2113:   strcpy(tmpout,optionfilefiname);
                   2114:   strcat(tmpout,"/");
                   2115:   strcat(tmpout,preop);
                   2116:   strcat(tmpout,fileres);
                   2117:   strcat(tmpout,postop);
                   2118:   return tmpout;
                   2119: }
                   2120:  
1.162     brouard  2121: char *asc_diff_time(long time_sec, char ascdiff[])
                   2122: {
                   2123:   long sec_left, days, hours, minutes;
                   2124:   days = (time_sec) / (60*60*24);
                   2125:   sec_left = (time_sec) % (60*60*24);
                   2126:   hours = (sec_left) / (60*60) ;
                   2127:   sec_left = (sec_left) %(60*60);
                   2128:   minutes = (sec_left) /60;
                   2129:   sec_left = (sec_left) % (60);
                   2130:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2131:   return ascdiff;
                   2132: }
                   2133: 
1.126     brouard  2134: /***************** f1dim *************************/
                   2135: extern int ncom; 
                   2136: extern double *pcom,*xicom;
                   2137: extern double (*nrfunc)(double []); 
                   2138:  
                   2139: double f1dim(double x) 
                   2140: { 
                   2141:   int j; 
                   2142:   double f;
                   2143:   double *xt; 
                   2144:  
                   2145:   xt=vector(1,ncom); 
                   2146:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2147:   f=(*nrfunc)(xt); 
                   2148:   free_vector(xt,1,ncom); 
                   2149:   return f; 
                   2150: } 
                   2151: 
                   2152: /*****************brent *************************/
                   2153: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2154: {
                   2155:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2156:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2157:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2158:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2159:    * returned function value. 
                   2160:   */
1.126     brouard  2161:   int iter; 
                   2162:   double a,b,d,etemp;
1.159     brouard  2163:   double fu=0,fv,fw,fx;
1.164     brouard  2164:   double ftemp=0.;
1.126     brouard  2165:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2166:   double e=0.0; 
                   2167:  
                   2168:   a=(ax < cx ? ax : cx); 
                   2169:   b=(ax > cx ? ax : cx); 
                   2170:   x=w=v=bx; 
                   2171:   fw=fv=fx=(*f)(x); 
                   2172:   for (iter=1;iter<=ITMAX;iter++) { 
                   2173:     xm=0.5*(a+b); 
                   2174:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2175:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2176:     printf(".");fflush(stdout);
                   2177:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2178: #ifdef DEBUGBRENT
1.126     brouard  2179:     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);
                   2180:     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);
                   2181:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2182: #endif
                   2183:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2184:       *xmin=x; 
                   2185:       return fx; 
                   2186:     } 
                   2187:     ftemp=fu;
                   2188:     if (fabs(e) > tol1) { 
                   2189:       r=(x-w)*(fx-fv); 
                   2190:       q=(x-v)*(fx-fw); 
                   2191:       p=(x-v)*q-(x-w)*r; 
                   2192:       q=2.0*(q-r); 
                   2193:       if (q > 0.0) p = -p; 
                   2194:       q=fabs(q); 
                   2195:       etemp=e; 
                   2196:       e=d; 
                   2197:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2198:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2199:       else { 
1.224     brouard  2200:                                d=p/q; 
                   2201:                                u=x+d; 
                   2202:                                if (u-a < tol2 || b-u < tol2) 
                   2203:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2204:       } 
                   2205:     } else { 
                   2206:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2207:     } 
                   2208:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2209:     fu=(*f)(u); 
                   2210:     if (fu <= fx) { 
                   2211:       if (u >= x) a=x; else b=x; 
                   2212:       SHFT(v,w,x,u) 
1.183     brouard  2213:       SHFT(fv,fw,fx,fu) 
                   2214:     } else { 
                   2215:       if (u < x) a=u; else b=u; 
                   2216:       if (fu <= fw || w == x) { 
1.224     brouard  2217:                                v=w; 
                   2218:                                w=u; 
                   2219:                                fv=fw; 
                   2220:                                fw=fu; 
1.183     brouard  2221:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2222:                                v=u; 
                   2223:                                fv=fu; 
1.183     brouard  2224:       } 
                   2225:     } 
1.126     brouard  2226:   } 
                   2227:   nrerror("Too many iterations in brent"); 
                   2228:   *xmin=x; 
                   2229:   return fx; 
                   2230: } 
                   2231: 
                   2232: /****************** mnbrak ***********************/
                   2233: 
                   2234: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2235:            double (*func)(double)) 
1.183     brouard  2236: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2237: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2238: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2239: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2240:    */
1.126     brouard  2241:   double ulim,u,r,q, dum;
                   2242:   double fu; 
1.187     brouard  2243: 
                   2244:   double scale=10.;
                   2245:   int iterscale=0;
                   2246: 
                   2247:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2248:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2249: 
                   2250: 
                   2251:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2252:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2253:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2254:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2255:   /* } */
                   2256: 
1.126     brouard  2257:   if (*fb > *fa) { 
                   2258:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2259:     SHFT(dum,*fb,*fa,dum) 
                   2260:   } 
1.126     brouard  2261:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2262:   *fc=(*func)(*cx); 
1.183     brouard  2263: #ifdef DEBUG
1.224     brouard  2264:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2265:   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  2266: #endif
1.224     brouard  2267:   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  2268:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2269:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2270:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2271:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2272:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2273:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2274:       fu=(*func)(u); 
1.163     brouard  2275: #ifdef DEBUG
                   2276:       /* f(x)=A(x-u)**2+f(u) */
                   2277:       double A, fparabu; 
                   2278:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2279:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2280:       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);
                   2281:       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  2282:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2283:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2284:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2285:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2286: #endif 
1.184     brouard  2287: #ifdef MNBRAKORIGINAL
1.183     brouard  2288: #else
1.191     brouard  2289: /*       if (fu > *fc) { */
                   2290: /* #ifdef DEBUG */
                   2291: /*       printf("mnbrak4  fu > fc \n"); */
                   2292: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2293: /* #endif */
                   2294: /*     /\* 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 *\\/  *\/ */
                   2295: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2296: /*     dum=u; /\* Shifting c and u *\/ */
                   2297: /*     u = *cx; */
                   2298: /*     *cx = dum; */
                   2299: /*     dum = fu; */
                   2300: /*     fu = *fc; */
                   2301: /*     *fc =dum; */
                   2302: /*       } else { /\* end *\/ */
                   2303: /* #ifdef DEBUG */
                   2304: /*       printf("mnbrak3  fu < fc \n"); */
                   2305: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2306: /* #endif */
                   2307: /*     dum=u; /\* Shifting c and u *\/ */
                   2308: /*     u = *cx; */
                   2309: /*     *cx = dum; */
                   2310: /*     dum = fu; */
                   2311: /*     fu = *fc; */
                   2312: /*     *fc =dum; */
                   2313: /*       } */
1.224     brouard  2314: #ifdef DEBUGMNBRAK
                   2315:                 double A, fparabu; 
                   2316:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2317:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2318:      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);
                   2319:      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  2320: #endif
1.191     brouard  2321:       dum=u; /* Shifting c and u */
                   2322:       u = *cx;
                   2323:       *cx = dum;
                   2324:       dum = fu;
                   2325:       fu = *fc;
                   2326:       *fc =dum;
1.183     brouard  2327: #endif
1.162     brouard  2328:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2329: #ifdef DEBUG
1.224     brouard  2330:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2331:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2332: #endif
1.126     brouard  2333:       fu=(*func)(u); 
                   2334:       if (fu < *fc) { 
1.183     brouard  2335: #ifdef DEBUG
1.224     brouard  2336:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2337:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2338: #endif
                   2339:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2340:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2341: #ifdef DEBUG
                   2342:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2343: #endif
                   2344:       } 
1.162     brouard  2345:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2346: #ifdef DEBUG
1.224     brouard  2347:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2348:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2349: #endif
1.126     brouard  2350:       u=ulim; 
                   2351:       fu=(*func)(u); 
1.183     brouard  2352:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2353: #ifdef DEBUG
1.224     brouard  2354:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2355:       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  2356: #endif
1.126     brouard  2357:       u=(*cx)+GOLD*(*cx-*bx); 
                   2358:       fu=(*func)(u); 
1.224     brouard  2359: #ifdef DEBUG
                   2360:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2361:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2362: #endif
1.183     brouard  2363:     } /* end tests */
1.126     brouard  2364:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2365:     SHFT(*fa,*fb,*fc,fu) 
                   2366: #ifdef DEBUG
1.224     brouard  2367:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2368:       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  2369: #endif
                   2370:   } /* 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  2371: } 
                   2372: 
                   2373: /*************** linmin ************************/
1.162     brouard  2374: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2375: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2376: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2377: the value of func at the returned location p . This is actually all accomplished by calling the
                   2378: routines mnbrak and brent .*/
1.126     brouard  2379: int ncom; 
                   2380: double *pcom,*xicom;
                   2381: double (*nrfunc)(double []); 
                   2382:  
1.224     brouard  2383: #ifdef LINMINORIGINAL
1.126     brouard  2384: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2385: #else
                   2386: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2387: #endif
1.126     brouard  2388: { 
                   2389:   double brent(double ax, double bx, double cx, 
                   2390:               double (*f)(double), double tol, double *xmin); 
                   2391:   double f1dim(double x); 
                   2392:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2393:              double *fc, double (*func)(double)); 
                   2394:   int j; 
                   2395:   double xx,xmin,bx,ax; 
                   2396:   double fx,fb,fa;
1.187     brouard  2397: 
1.203     brouard  2398: #ifdef LINMINORIGINAL
                   2399: #else
                   2400:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2401: #endif
                   2402:   
1.126     brouard  2403:   ncom=n; 
                   2404:   pcom=vector(1,n); 
                   2405:   xicom=vector(1,n); 
                   2406:   nrfunc=func; 
                   2407:   for (j=1;j<=n;j++) { 
                   2408:     pcom[j]=p[j]; 
1.202     brouard  2409:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2410:   } 
1.187     brouard  2411: 
1.203     brouard  2412: #ifdef LINMINORIGINAL
                   2413:   xx=1.;
                   2414: #else
                   2415:   axs=0.0;
                   2416:   xxs=1.;
                   2417:   do{
                   2418:     xx= xxs;
                   2419: #endif
1.187     brouard  2420:     ax=0.;
                   2421:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2422:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2423:     /* 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))   */
                   2424:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2425:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2426:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2427:     /* 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  2428: #ifdef LINMINORIGINAL
                   2429: #else
                   2430:     if (fx != fx){
1.224     brouard  2431:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2432:                        printf("|");
                   2433:                        fprintf(ficlog,"|");
1.203     brouard  2434: #ifdef DEBUGLINMIN
1.224     brouard  2435:                        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  2436: #endif
                   2437:     }
1.224     brouard  2438:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2439: #endif
                   2440:   
1.191     brouard  2441: #ifdef DEBUGLINMIN
                   2442:   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  2443:   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  2444: #endif
1.224     brouard  2445: #ifdef LINMINORIGINAL
                   2446: #else
1.317     brouard  2447:   if(fb == fx){ /* Flat function in the direction */
                   2448:     xmin=xx;
1.224     brouard  2449:     *flat=1;
1.317     brouard  2450:   }else{
1.224     brouard  2451:     *flat=0;
                   2452: #endif
                   2453:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2454:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2455:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2456:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2457:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2458:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2459: #ifdef DEBUG
1.224     brouard  2460:   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);
                   2461:   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);
                   2462: #endif
                   2463: #ifdef LINMINORIGINAL
                   2464: #else
                   2465:                        }
1.126     brouard  2466: #endif
1.191     brouard  2467: #ifdef DEBUGLINMIN
                   2468:   printf("linmin end ");
1.202     brouard  2469:   fprintf(ficlog,"linmin end ");
1.191     brouard  2470: #endif
1.126     brouard  2471:   for (j=1;j<=n;j++) { 
1.203     brouard  2472: #ifdef LINMINORIGINAL
                   2473:     xi[j] *= xmin; 
                   2474: #else
                   2475: #ifdef DEBUGLINMIN
                   2476:     if(xxs <1.0)
                   2477:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2478: #endif
                   2479:     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) */
                   2480: #ifdef DEBUGLINMIN
                   2481:     if(xxs <1.0)
                   2482:       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 );
                   2483: #endif
                   2484: #endif
1.187     brouard  2485:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2486:   } 
1.191     brouard  2487: #ifdef DEBUGLINMIN
1.203     brouard  2488:   printf("\n");
1.191     brouard  2489:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2490:   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  2491:   for (j=1;j<=n;j++) { 
1.202     brouard  2492:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2493:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2494:     if(j % ncovmodel == 0){
1.191     brouard  2495:       printf("\n");
1.202     brouard  2496:       fprintf(ficlog,"\n");
                   2497:     }
1.191     brouard  2498:   }
1.203     brouard  2499: #else
1.191     brouard  2500: #endif
1.126     brouard  2501:   free_vector(xicom,1,n); 
                   2502:   free_vector(pcom,1,n); 
                   2503: } 
                   2504: 
                   2505: 
                   2506: /*************** powell ************************/
1.162     brouard  2507: /*
1.317     brouard  2508: Minimization of a function func of n variables. Input consists in an initial starting point
                   2509: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2510: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2511: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2512: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2513: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2514:  */
1.224     brouard  2515: #ifdef LINMINORIGINAL
                   2516: #else
                   2517:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2518:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2519: #endif
1.126     brouard  2520: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2521:            double (*func)(double [])) 
                   2522: { 
1.224     brouard  2523: #ifdef LINMINORIGINAL
                   2524:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2525:              double (*func)(double [])); 
1.224     brouard  2526: #else 
1.241     brouard  2527:  void linmin(double p[], double xi[], int n, double *fret,
                   2528:             double (*func)(double []),int *flat); 
1.224     brouard  2529: #endif
1.239     brouard  2530:  int i,ibig,j,jk,k; 
1.126     brouard  2531:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2532:   double directest;
1.126     brouard  2533:   double fp,fptt;
                   2534:   double *xits;
                   2535:   int niterf, itmp;
                   2536: 
                   2537:   pt=vector(1,n); 
                   2538:   ptt=vector(1,n); 
                   2539:   xit=vector(1,n); 
                   2540:   xits=vector(1,n); 
                   2541:   *fret=(*func)(p); 
                   2542:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.338     brouard  2543:   rcurr_time = time(NULL);
                   2544:   fp=(*fret); /* Initialisation */
1.126     brouard  2545:   for (*iter=1;;++(*iter)) { 
                   2546:     ibig=0; 
                   2547:     del=0.0; 
1.157     brouard  2548:     rlast_time=rcurr_time;
                   2549:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2550:     rcurr_time = time(NULL);  
                   2551:     curr_time = *localtime(&rcurr_time);
1.337     brouard  2552:     /* 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); */
                   2553:     /* 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); */
                   2554:     printf("\nPowell iter=%d -2*LL=%.12f gain=%.3lg %ld sec. %ld sec.",*iter,*fret,fp-*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2555:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f gain=%.3lg %ld sec. %ld sec.",*iter,*fret,fp-*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1.157     brouard  2556: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.324     brouard  2557:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2558:     for (i=1;i<=n;i++) {
1.126     brouard  2559:       fprintf(ficrespow," %.12lf", p[i]);
                   2560:     }
1.239     brouard  2561:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2562:     printf("\n#model=  1      +     age ");
                   2563:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2564:     if(nagesqr==1){
1.241     brouard  2565:        printf("  + age*age  ");
                   2566:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2567:     }
                   2568:     for(j=1;j <=ncovmodel-2;j++){
                   2569:       if(Typevar[j]==0) {
                   2570:        printf("  +      V%d  ",Tvar[j]);
                   2571:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2572:       }else if(Typevar[j]==1) {
                   2573:        printf("  +    V%d*age ",Tvar[j]);
                   2574:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2575:       }else if(Typevar[j]==2) {
                   2576:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2577:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2578:       }
                   2579:     }
1.126     brouard  2580:     printf("\n");
1.239     brouard  2581: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2582: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2583:     fprintf(ficlog,"\n");
1.239     brouard  2584:     for(i=1,jk=1; i <=nlstate; i++){
                   2585:       for(k=1; k <=(nlstate+ndeath); k++){
                   2586:        if (k != i) {
                   2587:          printf("%d%d ",i,k);
                   2588:          fprintf(ficlog,"%d%d ",i,k);
                   2589:          for(j=1; j <=ncovmodel; j++){
                   2590:            printf("%12.7f ",p[jk]);
                   2591:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2592:            jk++; 
                   2593:          }
                   2594:          printf("\n");
                   2595:          fprintf(ficlog,"\n");
                   2596:        }
                   2597:       }
                   2598:     }
1.241     brouard  2599:     if(*iter <=3 && *iter >1){
1.157     brouard  2600:       tml = *localtime(&rcurr_time);
                   2601:       strcpy(strcurr,asctime(&tml));
                   2602:       rforecast_time=rcurr_time; 
1.126     brouard  2603:       itmp = strlen(strcurr);
                   2604:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2605:        strcurr[itmp-1]='\0';
1.162     brouard  2606:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2607:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2608:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2609:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2610:        forecast_time = *localtime(&rforecast_time);
                   2611:        strcpy(strfor,asctime(&forecast_time));
                   2612:        itmp = strlen(strfor);
                   2613:        if(strfor[itmp-1]=='\n')
                   2614:          strfor[itmp-1]='\0';
                   2615:        printf("   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
                   2616:        fprintf(ficlog,"   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
1.126     brouard  2617:       }
                   2618:     }
1.187     brouard  2619:     for (i=1;i<=n;i++) { /* For each direction i */
                   2620:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2621:       fptt=(*fret); 
                   2622: #ifdef DEBUG
1.203     brouard  2623:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2624:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2625: #endif
1.203     brouard  2626:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2627:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2628: #ifdef LINMINORIGINAL
1.188     brouard  2629:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2630: #else
                   2631:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2632:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2633: #endif
                   2634:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2635:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2636:                                /* because that direction will be replaced unless the gain del is small */
                   2637:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2638:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2639:                                /* with the new direction. */
                   2640:                                del=fabs(fptt-(*fret)); 
                   2641:                                ibig=i; 
1.126     brouard  2642:       } 
                   2643: #ifdef DEBUG
                   2644:       printf("%d %.12e",i,(*fret));
                   2645:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2646:       for (j=1;j<=n;j++) {
1.224     brouard  2647:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2648:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2649:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2650:       }
                   2651:       for(j=1;j<=n;j++) {
1.225     brouard  2652:                                printf(" p(%d)=%.12e",j,p[j]);
                   2653:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2654:       }
                   2655:       printf("\n");
                   2656:       fprintf(ficlog,"\n");
                   2657: #endif
1.187     brouard  2658:     } /* end loop on each direction i */
                   2659:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2660:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2661:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2662:     for(j=1;j<=n;j++) {
                   2663:       if(flatdir[j] >0){
                   2664:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2665:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2666:       }
1.319     brouard  2667:       /* printf("\n"); */
                   2668:       /* fprintf(ficlog,"\n"); */
                   2669:     }
1.243     brouard  2670:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2671:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2672:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2673:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2674:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2675:       /* decreased of more than 3.84  */
                   2676:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2677:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2678:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2679:                        
1.188     brouard  2680:       /* Starting the program with initial values given by a former maximization will simply change */
                   2681:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2682:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2683:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2684: #ifdef DEBUG
                   2685:       int k[2],l;
                   2686:       k[0]=1;
                   2687:       k[1]=-1;
                   2688:       printf("Max: %.12e",(*func)(p));
                   2689:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2690:       for (j=1;j<=n;j++) {
                   2691:        printf(" %.12e",p[j]);
                   2692:        fprintf(ficlog," %.12e",p[j]);
                   2693:       }
                   2694:       printf("\n");
                   2695:       fprintf(ficlog,"\n");
                   2696:       for(l=0;l<=1;l++) {
                   2697:        for (j=1;j<=n;j++) {
                   2698:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2699:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2700:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2701:        }
                   2702:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2703:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2704:       }
                   2705: #endif
                   2706: 
                   2707:       free_vector(xit,1,n); 
                   2708:       free_vector(xits,1,n); 
                   2709:       free_vector(ptt,1,n); 
                   2710:       free_vector(pt,1,n); 
                   2711:       return; 
1.192     brouard  2712:     } /* enough precision */ 
1.240     brouard  2713:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2714:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2715:       ptt[j]=2.0*p[j]-pt[j]; 
                   2716:       xit[j]=p[j]-pt[j]; 
                   2717:       pt[j]=p[j]; 
                   2718:     } 
1.181     brouard  2719:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2720: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2721:                if (*iter <=4) {
1.225     brouard  2722: #else
                   2723: #endif
1.224     brouard  2724: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2725: #else
1.161     brouard  2726:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2727: #endif
1.162     brouard  2728:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2729:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2730:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2731:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2732:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2733:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2734:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2735:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2736:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2737:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2738:       /* mu² and del² are equal when f3=f1 */
                   2739:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2740:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2741:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2742:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2743: #ifdef NRCORIGINAL
                   2744:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2745: #else
                   2746:       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  2747:       t= t- del*SQR(fp-fptt);
1.183     brouard  2748: #endif
1.202     brouard  2749:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2750: #ifdef DEBUG
1.181     brouard  2751:       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);
                   2752:       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  2753:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2754:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2755:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2756:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2757:       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);
                   2758:       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);
                   2759: #endif
1.183     brouard  2760: #ifdef POWELLORIGINAL
                   2761:       if (t < 0.0) { /* Then we use it for new direction */
                   2762: #else
1.182     brouard  2763:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2764:                                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  2765:         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  2766:         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  2767:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2768:       } 
1.181     brouard  2769:       if (directest < 0.0) { /* Then we use it for new direction */
                   2770: #endif
1.191     brouard  2771: #ifdef DEBUGLINMIN
1.234     brouard  2772:        printf("Before linmin in direction P%d-P0\n",n);
                   2773:        for (j=1;j<=n;j++) {
                   2774:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2775:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2776:          if(j % ncovmodel == 0){
                   2777:            printf("\n");
                   2778:            fprintf(ficlog,"\n");
                   2779:          }
                   2780:        }
1.224     brouard  2781: #endif
                   2782: #ifdef LINMINORIGINAL
1.234     brouard  2783:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2784: #else
1.234     brouard  2785:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2786:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2787: #endif
1.234     brouard  2788:        
1.191     brouard  2789: #ifdef DEBUGLINMIN
1.234     brouard  2790:        for (j=1;j<=n;j++) { 
                   2791:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2792:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2793:          if(j % ncovmodel == 0){
                   2794:            printf("\n");
                   2795:            fprintf(ficlog,"\n");
                   2796:          }
                   2797:        }
1.224     brouard  2798: #endif
1.234     brouard  2799:        for (j=1;j<=n;j++) { 
                   2800:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2801:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2802:        }
1.224     brouard  2803: #ifdef LINMINORIGINAL
                   2804: #else
1.234     brouard  2805:        for (j=1, flatd=0;j<=n;j++) {
                   2806:          if(flatdir[j]>0)
                   2807:            flatd++;
                   2808:        }
                   2809:        if(flatd >0){
1.255     brouard  2810:          printf("%d flat directions: ",flatd);
                   2811:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2812:          for (j=1;j<=n;j++) { 
                   2813:            if(flatdir[j]>0){
                   2814:              printf("%d ",j);
                   2815:              fprintf(ficlog,"%d ",j);
                   2816:            }
                   2817:          }
                   2818:          printf("\n");
                   2819:          fprintf(ficlog,"\n");
1.319     brouard  2820: #ifdef FLATSUP
                   2821:           free_vector(xit,1,n); 
                   2822:           free_vector(xits,1,n); 
                   2823:           free_vector(ptt,1,n); 
                   2824:           free_vector(pt,1,n); 
                   2825:           return;
                   2826: #endif
1.234     brouard  2827:        }
1.191     brouard  2828: #endif
1.234     brouard  2829:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2830:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2831:        
1.126     brouard  2832: #ifdef DEBUG
1.234     brouard  2833:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2834:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2835:        for(j=1;j<=n;j++){
                   2836:          printf(" %lf",xit[j]);
                   2837:          fprintf(ficlog," %lf",xit[j]);
                   2838:        }
                   2839:        printf("\n");
                   2840:        fprintf(ficlog,"\n");
1.126     brouard  2841: #endif
1.192     brouard  2842:       } /* end of t or directest negative */
1.224     brouard  2843: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2844: #else
1.234     brouard  2845:       } /* end if (fptt < fp)  */
1.192     brouard  2846: #endif
1.225     brouard  2847: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2848:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2849: #else
1.224     brouard  2850: #endif
1.234     brouard  2851:                } /* loop iteration */ 
1.126     brouard  2852: } 
1.234     brouard  2853:   
1.126     brouard  2854: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2855:   
1.235     brouard  2856:   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  2857:   {
1.338     brouard  2858:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
1.279     brouard  2859:      *   (and selected quantitative values in nres)
                   2860:      *  by left multiplying the unit
                   2861:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2862:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2863:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2864:      * or prevalence in state 1, prevalence in state 2, 0
                   2865:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2866:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2867:      * Output is prlim.
                   2868:      * Initial matrix pimij 
                   2869:      */
1.206     brouard  2870:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2871:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2872:   /*  0,                   0                  , 1} */
                   2873:   /*
                   2874:    * and after some iteration: */
                   2875:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2876:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2877:   /*  0,                   0                  , 1} */
                   2878:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2879:   /* {0.51571254859325999, 0.4842874514067399, */
                   2880:   /*  0.51326036147820708, 0.48673963852179264} */
                   2881:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2882:     
1.332     brouard  2883:     int i, ii,j,k, k1;
1.209     brouard  2884:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2885:   /* double **matprod2(); */ /* test */
1.218     brouard  2886:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2887:   double **newm;
1.209     brouard  2888:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2889:   int ncvloop=0;
1.288     brouard  2890:   int first=0;
1.169     brouard  2891:   
1.209     brouard  2892:   min=vector(1,nlstate);
                   2893:   max=vector(1,nlstate);
                   2894:   meandiff=vector(1,nlstate);
                   2895: 
1.218     brouard  2896:        /* Starting with matrix unity */
1.126     brouard  2897:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2898:     for (j=1;j<=nlstate+ndeath;j++){
                   2899:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2900:     }
1.169     brouard  2901:   
                   2902:   cov[1]=1.;
                   2903:   
                   2904:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2905:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2906:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2907:     ncvloop++;
1.126     brouard  2908:     newm=savm;
                   2909:     /* Covariates have to be included here again */
1.138     brouard  2910:     cov[2]=agefin;
1.319     brouard  2911:      if(nagesqr==1){
                   2912:       cov[3]= agefin*agefin;
                   2913:      }
1.332     brouard  2914:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   2915:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   2916:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   2917:        if(Typevar[k1]==1){ /* A product with age */
                   2918:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   2919:        }else{
                   2920:         cov[2+nagesqr+k1]=precov[nres][k1];
                   2921:        }
                   2922:      }/* End of loop on model equation */
                   2923:      
                   2924: /* Start of old code (replaced by a loop on position in the model equation */
                   2925:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   2926:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   2927:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   2928:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   2929:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   2930:     /*    * k                  1        2      3    4      5      6     7        8 */
                   2931:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   2932:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   2933:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   2934:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   2935:     /*    *nsd=3                              (1)  (2)           (3) */
                   2936:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   2937:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   2938:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   2939:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   2940:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   2941:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   2942:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   2943:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   2944:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   2945:     /*    *TvarsDpType */
                   2946:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   2947:     /*    * nsd=1              (1)           (2) */
                   2948:     /*    *TvarsD[nsd]          3             2 */
                   2949:     /*    *TnsdVar           (3)=1          (2)=2 */
                   2950:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   2951:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   2952:     /*    *\/ */
                   2953:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   2954:     /*   /\* 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)); *\/ */
                   2955:     /* } */
                   2956:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   2957:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   2958:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   2959:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   2960:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   2961:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   2962:     /*   /\* 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]); *\/ */
                   2963:     /* } */
                   2964:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   2965:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   2966:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   2967:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   2968:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   2969:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   2970:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   2971:     /*   } */
                   2972:     /*   /\* 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]); *\/ */
                   2973:     /* } */
                   2974:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   2975:     /*   /\* 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]); *\/ */
                   2976:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   2977:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   2978:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2979:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   2980:     /*         }else{ */
                   2981:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   2982:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   2983:     /*         } */
                   2984:     /*   }else{ */
                   2985:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   2986:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   2987:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   2988:     /*         }else{ */
                   2989:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   2990:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   2991:     /*         } */
                   2992:     /*   } */
                   2993:     /* } /\* End product without age *\/ */
                   2994: /* ENd of old code */
1.138     brouard  2995:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2996:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2997:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2998:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2999:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  3000:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  3001:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  3002:     
1.126     brouard  3003:     savm=oldm;
                   3004:     oldm=newm;
1.209     brouard  3005: 
                   3006:     for(j=1; j<=nlstate; j++){
                   3007:       max[j]=0.;
                   3008:       min[j]=1.;
                   3009:     }
                   3010:     for(i=1;i<=nlstate;i++){
                   3011:       sumnew=0;
                   3012:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   3013:       for(j=1; j<=nlstate; j++){ 
                   3014:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   3015:        max[j]=FMAX(max[j],prlim[i][j]);
                   3016:        min[j]=FMIN(min[j],prlim[i][j]);
                   3017:       }
                   3018:     }
                   3019: 
1.126     brouard  3020:     maxmax=0.;
1.209     brouard  3021:     for(j=1; j<=nlstate; j++){
                   3022:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   3023:       maxmax=FMAX(maxmax,meandiff[j]);
                   3024:       /* 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  3025:     } /* j loop */
1.203     brouard  3026:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  3027:     /* 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  3028:     if(maxmax < ftolpl){
1.209     brouard  3029:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   3030:       free_vector(min,1,nlstate);
                   3031:       free_vector(max,1,nlstate);
                   3032:       free_vector(meandiff,1,nlstate);
1.126     brouard  3033:       return prlim;
                   3034:     }
1.288     brouard  3035:   } /* agefin loop */
1.208     brouard  3036:     /* After some age loop it doesn't converge */
1.288     brouard  3037:   if(!first){
                   3038:     first=1;
                   3039:     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  3040:     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);
                   3041:   }else if (first >=1 && first <10){
                   3042:     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);
                   3043:     first++;
                   3044:   }else if (first ==10){
                   3045:     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);
                   3046:     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");
                   3047:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   3048:     first++;
1.288     brouard  3049:   }
                   3050: 
1.209     brouard  3051:   /* 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); */
                   3052:   free_vector(min,1,nlstate);
                   3053:   free_vector(max,1,nlstate);
                   3054:   free_vector(meandiff,1,nlstate);
1.208     brouard  3055:   
1.169     brouard  3056:   return prlim; /* should not reach here */
1.126     brouard  3057: }
                   3058: 
1.217     brouard  3059: 
                   3060:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   3061: 
1.218     brouard  3062:  /* 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) */
                   3063:  /* 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  3064:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  3065: {
1.264     brouard  3066:   /* 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  3067:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   3068:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   3069:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   3070:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   3071:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   3072:   /* Initial matrix pimij */
                   3073:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3074:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3075:   /*  0,                   0                  , 1} */
                   3076:   /*
                   3077:    * and after some iteration: */
                   3078:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3079:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3080:   /*  0,                   0                  , 1} */
                   3081:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3082:   /* {0.51571254859325999, 0.4842874514067399, */
                   3083:   /*  0.51326036147820708, 0.48673963852179264} */
                   3084:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3085: 
1.332     brouard  3086:   int i, ii,j,k, k1;
1.247     brouard  3087:   int first=0;
1.217     brouard  3088:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3089:   /* double **matprod2(); */ /* test */
                   3090:   double **out, cov[NCOVMAX+1], **bmij();
                   3091:   double **newm;
1.218     brouard  3092:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   3093:   double        **oldm, **savm;  /* for use */
                   3094: 
1.217     brouard  3095:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3096:   int ncvloop=0;
                   3097:   
                   3098:   min=vector(1,nlstate);
                   3099:   max=vector(1,nlstate);
                   3100:   meandiff=vector(1,nlstate);
                   3101: 
1.266     brouard  3102:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   3103:   oldm=oldms; savm=savms;
                   3104:   
                   3105:   /* Starting with matrix unity */
                   3106:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3107:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  3108:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3109:     }
                   3110:   
                   3111:   cov[1]=1.;
                   3112:   
                   3113:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3114:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  3115:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  3116:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3117:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  3118:     ncvloop++;
1.218     brouard  3119:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   3120:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  3121:     /* Covariates have to be included here again */
                   3122:     cov[2]=agefin;
1.319     brouard  3123:     if(nagesqr==1){
1.217     brouard  3124:       cov[3]= agefin*agefin;;
1.319     brouard  3125:     }
1.332     brouard  3126:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3127:       if(Typevar[k1]==1){ /* A product with age */
                   3128:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  3129:       }else{
1.332     brouard  3130:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  3131:       }
1.332     brouard  3132:     }/* End of loop on model equation */
                   3133: 
                   3134: /* Old code */ 
                   3135: 
                   3136:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   3137:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3138:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   3139:     /*   /\* 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)); *\/ */
                   3140:     /* } */
                   3141:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   3142:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3143:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3144:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   3145:     /* /\* } *\/ */
                   3146:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3147:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3148:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3149:     /*   /\* 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]); *\/ */
                   3150:     /* } */
                   3151:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   3152:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   3153:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   3154:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3155:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3156:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   3157:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3158:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3159:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3160:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3161:     /*   } */
                   3162:     /*   /\* 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]); *\/ */
                   3163:     /* } */
                   3164:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3165:     /*   /\* 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]); *\/ */
                   3166:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3167:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3168:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3169:     /*         }else{ */
                   3170:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3171:     /*         } */
                   3172:     /*   }else{ */
                   3173:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3174:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3175:     /*         }else{ */
                   3176:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3177:     /*         } */
                   3178:     /*   } */
                   3179:     /* } */
1.217     brouard  3180:     
                   3181:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3182:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3183:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3184:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3185:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3186:                /* ij should be linked to the correct index of cov */
                   3187:                /* age and covariate values ij are in 'cov', but we need to pass
                   3188:                 * ij for the observed prevalence at age and status and covariate
                   3189:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3190:                 */
                   3191:     /* 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 *\/ */
                   3192:     /* 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 *\/ */
                   3193:     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  3194:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3195:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3196:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3197:     /*         printf("%d newm= ",i); */
                   3198:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3199:     /*           printf("%f ",newm[i][j]); */
                   3200:     /*         } */
                   3201:     /*         printf("oldm * "); */
                   3202:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3203:     /*           printf("%f ",oldm[i][j]); */
                   3204:     /*         } */
1.268     brouard  3205:     /*         printf(" bmmij "); */
1.266     brouard  3206:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3207:     /*           printf("%f ",pmmij[i][j]); */
                   3208:     /*         } */
                   3209:     /*         printf("\n"); */
                   3210:     /*   } */
                   3211:     /* } */
1.217     brouard  3212:     savm=oldm;
                   3213:     oldm=newm;
1.266     brouard  3214: 
1.217     brouard  3215:     for(j=1; j<=nlstate; j++){
                   3216:       max[j]=0.;
                   3217:       min[j]=1.;
                   3218:     }
                   3219:     for(j=1; j<=nlstate; j++){ 
                   3220:       for(i=1;i<=nlstate;i++){
1.234     brouard  3221:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3222:        bprlim[i][j]= newm[i][j];
                   3223:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3224:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3225:       }
                   3226:     }
1.218     brouard  3227:                
1.217     brouard  3228:     maxmax=0.;
                   3229:     for(i=1; i<=nlstate; i++){
1.318     brouard  3230:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3231:       maxmax=FMAX(maxmax,meandiff[i]);
                   3232:       /* 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  3233:     } /* i loop */
1.217     brouard  3234:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3235:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3236:     if(maxmax < ftolpl){
1.220     brouard  3237:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3238:       free_vector(min,1,nlstate);
                   3239:       free_vector(max,1,nlstate);
                   3240:       free_vector(meandiff,1,nlstate);
                   3241:       return bprlim;
                   3242:     }
1.288     brouard  3243:   } /* agefin loop */
1.217     brouard  3244:     /* After some age loop it doesn't converge */
1.288     brouard  3245:   if(!first){
1.247     brouard  3246:     first=1;
                   3247:     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\
                   3248: 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);
                   3249:   }
                   3250:   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  3251: 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);
                   3252:   /* 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); */
                   3253:   free_vector(min,1,nlstate);
                   3254:   free_vector(max,1,nlstate);
                   3255:   free_vector(meandiff,1,nlstate);
                   3256:   
                   3257:   return bprlim; /* should not reach here */
                   3258: }
                   3259: 
1.126     brouard  3260: /*************** transition probabilities ***************/ 
                   3261: 
                   3262: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3263: {
1.138     brouard  3264:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3265:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3266:      model to the ncovmodel covariates (including constant and age).
                   3267:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3268:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3269:      ncth covariate in the global vector x is given by the formula:
                   3270:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3271:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3272:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3273:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3274:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3275:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3276:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3277:   */
                   3278:   double s1, lnpijopii;
1.126     brouard  3279:   /*double t34;*/
1.164     brouard  3280:   int i,j, nc, ii, jj;
1.126     brouard  3281: 
1.223     brouard  3282:   for(i=1; i<= nlstate; i++){
                   3283:     for(j=1; j<i;j++){
                   3284:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3285:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3286:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3287:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3288:       }
                   3289:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3290:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3291:     }
                   3292:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3293:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3294:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3295:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3296:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3297:       }
                   3298:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3299:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3300:     }
                   3301:   }
1.218     brouard  3302:   
1.223     brouard  3303:   for(i=1; i<= nlstate; i++){
                   3304:     s1=0;
                   3305:     for(j=1; j<i; j++){
1.339     brouard  3306:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3307:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3308:     }
                   3309:     for(j=i+1; j<=nlstate+ndeath; j++){
1.339     brouard  3310:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3311:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3312:     }
                   3313:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3314:     ps[i][i]=1./(s1+1.);
                   3315:     /* Computing other pijs */
                   3316:     for(j=1; j<i; j++)
1.325     brouard  3317:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3318:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3319:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3320:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3321:   } /* end i */
1.218     brouard  3322:   
1.223     brouard  3323:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3324:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3325:       ps[ii][jj]=0;
                   3326:       ps[ii][ii]=1;
                   3327:     }
                   3328:   }
1.294     brouard  3329: 
                   3330: 
1.223     brouard  3331:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3332:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3333:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3334:   /*   } */
                   3335:   /*   printf("\n "); */
                   3336:   /* } */
                   3337:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3338:   /*
                   3339:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3340:                goto end;*/
1.266     brouard  3341:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3342: }
                   3343: 
1.218     brouard  3344: /*************** backward transition probabilities ***************/ 
                   3345: 
                   3346:  /* 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 ) */
                   3347: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3348:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3349: {
1.302     brouard  3350:   /* 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  3351:    * 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  3352:    */
1.218     brouard  3353:   int i, ii, j,k;
1.222     brouard  3354:   
                   3355:   double **out, **pmij();
                   3356:   double sumnew=0.;
1.218     brouard  3357:   double agefin;
1.292     brouard  3358:   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  3359:   double **dnewm, **dsavm, **doldm;
                   3360:   double **bbmij;
                   3361:   
1.218     brouard  3362:   doldm=ddoldms; /* global pointers */
1.222     brouard  3363:   dnewm=ddnewms;
                   3364:   dsavm=ddsavms;
1.318     brouard  3365: 
                   3366:   /* Debug */
                   3367:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3368:   agefin=cov[2];
1.268     brouard  3369:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3370:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3371:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3372:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3373: 
                   3374:   /* P_x */
1.325     brouard  3375:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3376:   /* outputs pmmij which is a stochastic matrix in row */
                   3377: 
                   3378:   /* Diag(w_x) */
1.292     brouard  3379:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3380:   sumnew=0.;
1.269     brouard  3381:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3382:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3383:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3384:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3385:   }
                   3386:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3387:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3388:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3389:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3390:     }
                   3391:   }else{
                   3392:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3393:       for (j=1;j<=nlstate+ndeath;j++)
                   3394:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3395:     }
                   3396:     /* if(sumnew <0.9){ */
                   3397:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3398:     /* } */
                   3399:   }
                   3400:   k3=0.0;  /* We put the last diagonal to 0 */
                   3401:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3402:       doldm[ii][ii]= k3;
                   3403:   }
                   3404:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3405:   
1.292     brouard  3406:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3407:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3408: 
1.292     brouard  3409:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3410:   /* 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  3411:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3412:     sumnew=0.;
1.222     brouard  3413:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3414:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3415:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3416:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3417:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3418:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3419:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3420:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3421:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3422:        /* }else */
1.268     brouard  3423:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3424:     } /*End ii */
                   3425:   } /* 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 */
                   3426: 
1.292     brouard  3427:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3428:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3429:   /* end bmij */
1.266     brouard  3430:   return ps; /*pointer is unchanged */
1.218     brouard  3431: }
1.217     brouard  3432: /*************** transition probabilities ***************/ 
                   3433: 
1.218     brouard  3434: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3435: {
                   3436:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3437:      computes the probability to be observed in state j being in state i by appying the
                   3438:      model to the ncovmodel covariates (including constant and age).
                   3439:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3440:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3441:      ncth covariate in the global vector x is given by the formula:
                   3442:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3443:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3444:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3445:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3446:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3447:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3448:   */
                   3449:   double s1, lnpijopii;
                   3450:   /*double t34;*/
                   3451:   int i,j, nc, ii, jj;
                   3452: 
1.234     brouard  3453:   for(i=1; i<= nlstate; i++){
                   3454:     for(j=1; j<i;j++){
                   3455:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3456:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3457:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3458:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3459:       }
                   3460:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3461:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3462:     }
                   3463:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3464:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3465:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3466:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3467:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3468:       }
                   3469:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3470:     }
                   3471:   }
                   3472:   
                   3473:   for(i=1; i<= nlstate; i++){
                   3474:     s1=0;
                   3475:     for(j=1; j<i; j++){
                   3476:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3477:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3478:     }
                   3479:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3480:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3481:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3482:     }
                   3483:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3484:     ps[i][i]=1./(s1+1.);
                   3485:     /* Computing other pijs */
                   3486:     for(j=1; j<i; j++)
                   3487:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3488:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3489:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3490:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3491:   } /* end i */
                   3492:   
                   3493:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3494:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3495:       ps[ii][jj]=0;
                   3496:       ps[ii][ii]=1;
                   3497:     }
                   3498:   }
1.296     brouard  3499:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3500:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3501:     s1=0.;
                   3502:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3503:       s1+=ps[ii][jj];
                   3504:     }
                   3505:     for(ii=1; ii<= nlstate; ii++){
                   3506:       ps[ii][jj]=ps[ii][jj]/s1;
                   3507:     }
                   3508:   }
                   3509:   /* Transposition */
                   3510:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3511:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3512:       s1=ps[ii][jj];
                   3513:       ps[ii][jj]=ps[jj][ii];
                   3514:       ps[jj][ii]=s1;
                   3515:     }
                   3516:   }
                   3517:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3518:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3519:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3520:   /*   } */
                   3521:   /*   printf("\n "); */
                   3522:   /* } */
                   3523:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3524:   /*
                   3525:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3526:     goto end;*/
                   3527:   return ps;
1.217     brouard  3528: }
                   3529: 
                   3530: 
1.126     brouard  3531: /**************** Product of 2 matrices ******************/
                   3532: 
1.145     brouard  3533: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3534: {
                   3535:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3536:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3537:   /* in, b, out are matrice of pointers which should have been initialized 
                   3538:      before: only the contents of out is modified. The function returns
                   3539:      a pointer to pointers identical to out */
1.145     brouard  3540:   int i, j, k;
1.126     brouard  3541:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3542:     for(k=ncolol; k<=ncoloh; k++){
                   3543:       out[i][k]=0.;
                   3544:       for(j=ncl; j<=nch; j++)
                   3545:        out[i][k] +=in[i][j]*b[j][k];
                   3546:     }
1.126     brouard  3547:   return out;
                   3548: }
                   3549: 
                   3550: 
                   3551: /************* Higher Matrix Product ***************/
                   3552: 
1.235     brouard  3553: 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  3554: {
1.336     brouard  3555:   /* Already optimized with precov.
                   3556:      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  3557:      'nhstepm*hstepm*stepm' months (i.e. until
                   3558:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3559:      nhstepm*hstepm matrices. 
                   3560:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3561:      (typically every 2 years instead of every month which is too big 
                   3562:      for the memory).
                   3563:      Model is determined by parameters x and covariates have to be 
                   3564:      included manually here. 
                   3565: 
                   3566:      */
                   3567: 
1.330     brouard  3568:   int i, j, d, h, k, k1;
1.131     brouard  3569:   double **out, cov[NCOVMAX+1];
1.126     brouard  3570:   double **newm;
1.187     brouard  3571:   double agexact;
1.214     brouard  3572:   double agebegin, ageend;
1.126     brouard  3573: 
                   3574:   /* Hstepm could be zero and should return the unit matrix */
                   3575:   for (i=1;i<=nlstate+ndeath;i++)
                   3576:     for (j=1;j<=nlstate+ndeath;j++){
                   3577:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3578:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3579:     }
                   3580:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3581:   for(h=1; h <=nhstepm; h++){
                   3582:     for(d=1; d <=hstepm; d++){
                   3583:       newm=savm;
                   3584:       /* Covariates have to be included here again */
                   3585:       cov[1]=1.;
1.214     brouard  3586:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3587:       cov[2]=agexact;
1.319     brouard  3588:       if(nagesqr==1){
1.227     brouard  3589:        cov[3]= agexact*agexact;
1.319     brouard  3590:       }
1.330     brouard  3591:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3592:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3593:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.332     brouard  3594:        if(Typevar[k1]==1){ /* A product with age */
                   3595:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3596:        }else{
                   3597:          cov[2+nagesqr+k1]=precov[nres][k1];
                   3598:        }
                   3599:       }/* End of loop on model equation */
                   3600:        /* Old code */ 
                   3601: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   3602: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   3603: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   3604: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   3605: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   3606: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3607: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3608: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   3609: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   3610: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   3611: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   3612: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   3613: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   3614: /*       /\* 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]])); *\/ */
                   3615: /*       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); */
                   3616: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3617: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   3618: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   3619: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   3620: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   3621: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   3622: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3623: /*       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]]); */
                   3624: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3625: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   3626: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   3627: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   3628: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   3629: /*       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]); */
                   3630: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3631: 
                   3632: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   3633: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   3634: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   3635: /*       /\* *\/ */
1.330     brouard  3636: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3637: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3638: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  3639: /* /\*cptcovage=2                   1               2      *\/ */
                   3640: /* /\*Tage[k]=                      5               8      *\/  */
                   3641: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   3642: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   3643: /*       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]]); */
                   3644: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3645: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   3646: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   3647: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   3648: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   3649: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   3650: /*       /\*   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); *\/ */
                   3651: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   3652: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   3653: /*       /\* } *\/ */
                   3654: /*       /\* 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]); *\/ */
                   3655: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   3656: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   3657: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   3658: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   3659: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   3660: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   3661: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   3662: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   3663: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  3664:          
1.332     brouard  3665: /*       /\* 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])]); *\/ */
                   3666: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3667: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   3668: /*       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]]); */
                   3669: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3670: 
                   3671: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   3672: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   3673: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3674: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   3675: /*           /\* 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]])]; *\/ */
                   3676: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   3677: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   3678: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   3679: /*       /\*   } *\/ */
                   3680: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   3681: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   3682: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   3683: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3684: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   3685: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   3686: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3687: /*       /\*   } *\/ */
                   3688: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   3689: /*     }/\*end of products *\/ */
                   3690:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  3691:       /* for (k=1; k<=cptcovn;k++)  */
                   3692:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3693:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3694:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3695:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3696:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3697:       
                   3698:       
1.126     brouard  3699:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3700:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3701:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3702:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3703:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3704:       /* if((int)age == 70){ */
                   3705:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3706:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3707:       /*         printf("%d pmmij ",i); */
                   3708:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3709:       /*           printf("%f ",pmmij[i][j]); */
                   3710:       /*         } */
                   3711:       /*         printf(" oldm "); */
                   3712:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3713:       /*           printf("%f ",oldm[i][j]); */
                   3714:       /*         } */
                   3715:       /*         printf("\n"); */
                   3716:       /*       } */
                   3717:       /* } */
1.126     brouard  3718:       savm=oldm;
                   3719:       oldm=newm;
                   3720:     }
                   3721:     for(i=1; i<=nlstate+ndeath; i++)
                   3722:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3723:        po[i][j][h]=newm[i][j];
                   3724:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3725:       }
1.128     brouard  3726:     /*printf("h=%d ",h);*/
1.126     brouard  3727:   } /* end h */
1.267     brouard  3728:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3729:   return po;
                   3730: }
                   3731: 
1.217     brouard  3732: /************* Higher Back Matrix Product ***************/
1.218     brouard  3733: /* 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  3734: 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  3735: {
1.332     brouard  3736:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   3737:      computes the transition matrix starting at age 'age' over
1.217     brouard  3738:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3739:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3740:      nhstepm*hstepm matrices.
                   3741:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3742:      (typically every 2 years instead of every month which is too big
1.217     brouard  3743:      for the memory).
1.218     brouard  3744:      Model is determined by parameters x and covariates have to be
1.266     brouard  3745:      included manually here. Then we use a call to bmij(x and cov)
                   3746:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3747:   */
1.217     brouard  3748: 
1.332     brouard  3749:   int i, j, d, h, k, k1;
1.266     brouard  3750:   double **out, cov[NCOVMAX+1], **bmij();
                   3751:   double **newm, ***newmm;
1.217     brouard  3752:   double agexact;
                   3753:   double agebegin, ageend;
1.222     brouard  3754:   double **oldm, **savm;
1.217     brouard  3755: 
1.266     brouard  3756:   newmm=po; /* To be saved */
                   3757:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3758:   /* Hstepm could be zero and should return the unit matrix */
                   3759:   for (i=1;i<=nlstate+ndeath;i++)
                   3760:     for (j=1;j<=nlstate+ndeath;j++){
                   3761:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3762:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3763:     }
                   3764:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3765:   for(h=1; h <=nhstepm; h++){
                   3766:     for(d=1; d <=hstepm; d++){
                   3767:       newm=savm;
                   3768:       /* Covariates have to be included here again */
                   3769:       cov[1]=1.;
1.271     brouard  3770:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3771:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3772:         /* Debug */
                   3773:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3774:       cov[2]=agexact;
1.332     brouard  3775:       if(nagesqr==1){
1.222     brouard  3776:        cov[3]= agexact*agexact;
1.332     brouard  3777:       }
                   3778:       /** New code */
                   3779:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3780:        if(Typevar[k1]==1){ /* A product with age */
                   3781:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  3782:        }else{
1.332     brouard  3783:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  3784:        }
1.332     brouard  3785:       }/* End of loop on model equation */
                   3786:       /** End of new code */
                   3787:   /** This was old code */
                   3788:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   3789:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3790:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3791:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   3792:       /*   /\* 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)); *\/ */
                   3793:       /* } */
                   3794:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3795:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3796:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3797:       /*       /\* 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]); *\/ */
                   3798:       /* } */
                   3799:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   3800:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   3801:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3802:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3803:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3804:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   3805:       /*       } */
                   3806:       /*       /\* 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]); *\/ */
                   3807:       /* } */
                   3808:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   3809:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3810:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   3811:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3812:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   3813:       /*         }else{ */
                   3814:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3815:       /*         } */
                   3816:       /*       }else{ */
                   3817:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3818:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3819:       /*         }else{ */
                   3820:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3821:       /*         } */
                   3822:       /*       } */
                   3823:       /* }                      */
                   3824:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   3825:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   3826: /** End of old code */
                   3827:       
1.218     brouard  3828:       /* Careful transposed matrix */
1.266     brouard  3829:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3830:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3831:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3832:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3833:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3834:       /* if((int)age == 70){ */
                   3835:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3836:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3837:       /*         printf("%d pmmij ",i); */
                   3838:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3839:       /*           printf("%f ",pmmij[i][j]); */
                   3840:       /*         } */
                   3841:       /*         printf(" oldm "); */
                   3842:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3843:       /*           printf("%f ",oldm[i][j]); */
                   3844:       /*         } */
                   3845:       /*         printf("\n"); */
                   3846:       /*       } */
                   3847:       /* } */
                   3848:       savm=oldm;
                   3849:       oldm=newm;
                   3850:     }
                   3851:     for(i=1; i<=nlstate+ndeath; i++)
                   3852:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3853:        po[i][j][h]=newm[i][j];
1.268     brouard  3854:        /* if(h==nhstepm) */
                   3855:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3856:       }
1.268     brouard  3857:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3858:   } /* end h */
1.268     brouard  3859:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3860:   return po;
                   3861: }
                   3862: 
                   3863: 
1.162     brouard  3864: #ifdef NLOPT
                   3865:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3866:   double fret;
                   3867:   double *xt;
                   3868:   int j;
                   3869:   myfunc_data *d2 = (myfunc_data *) pd;
                   3870: /* xt = (p1-1); */
                   3871:   xt=vector(1,n); 
                   3872:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3873: 
                   3874:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3875:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3876:   printf("Function = %.12lf ",fret);
                   3877:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3878:   printf("\n");
                   3879:  free_vector(xt,1,n);
                   3880:   return fret;
                   3881: }
                   3882: #endif
1.126     brouard  3883: 
                   3884: /*************** log-likelihood *************/
                   3885: double func( double *x)
                   3886: {
1.336     brouard  3887:   int i, ii, j, k, mi, d, kk, kf=0;
1.226     brouard  3888:   int ioffset=0;
1.339     brouard  3889:   int ipos=0,iposold=0,ncovv=0;
                   3890: 
1.340     brouard  3891:   double cotvarv, cotvarvold;
1.226     brouard  3892:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3893:   double **out;
                   3894:   double lli; /* Individual log likelihood */
                   3895:   int s1, s2;
1.228     brouard  3896:   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  3897: 
1.226     brouard  3898:   double bbh, survp;
                   3899:   double agexact;
1.336     brouard  3900:   double agebegin, ageend;
1.226     brouard  3901:   /*extern weight */
                   3902:   /* We are differentiating ll according to initial status */
                   3903:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3904:   /*for(i=1;i<imx;i++) 
                   3905:     printf(" %d\n",s[4][i]);
                   3906:   */
1.162     brouard  3907: 
1.226     brouard  3908:   ++countcallfunc;
1.162     brouard  3909: 
1.226     brouard  3910:   cov[1]=1.;
1.126     brouard  3911: 
1.226     brouard  3912:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3913:   ioffset=0;
1.226     brouard  3914:   if(mle==1){
                   3915:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3916:       /* Computes the values of the ncovmodel covariates of the model
                   3917:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3918:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3919:         to be observed in j being in i according to the model.
                   3920:       */
1.243     brouard  3921:       ioffset=2+nagesqr ;
1.233     brouard  3922:    /* Fixed */
1.336     brouard  3923:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummu or quant or prod */
1.319     brouard  3924:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   3925:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   3926:        /*  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  3927:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.336     brouard  3928:        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  3929:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  3930:       }
1.226     brouard  3931:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  3932:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  3933:         has been calculated etc */
                   3934:       /* For an individual i, wav[i] gives the number of effective waves */
                   3935:       /* We compute the contribution to Likelihood of each effective transition
                   3936:         mw[mi][i] is real wave of the mi th effectve wave */
                   3937:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3938:         s2=s[mw[mi+1][i]][i];
1.341   ! brouard  3939:         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  3940:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3941:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3942:       */
1.336     brouard  3943:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   3944:       /* Wave varying (but not age varying) */
1.339     brouard  3945:        /* 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*\/ */
                   3946:        /*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
                   3947:        /*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   3948:        /* } */
1.340     brouard  3949:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
                   3950:          itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   3951:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   3952:          if(TvarFind[itv]==0){ /* Not a fixed covariate */
1.341   ! brouard  3953:            cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* cotvar[wav][ncovcol+nqv+iv][i] */
1.340     brouard  3954:          }else{ /* fixed covariate */
                   3955:            cotvarv=covar[Tvar[TvarFind[itv]]][i];
                   3956:          }
1.339     brouard  3957:          if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  3958:            cotvarvold=cotvarv;
                   3959:          }else{ /* A second product */
                   3960:            cotvarv=cotvarv*cotvarvold;
1.339     brouard  3961:          }
                   3962:          iposold=ipos;
1.340     brouard  3963:          cov[ioffset+ipos]=cotvarv;
1.234     brouard  3964:        }
1.339     brouard  3965:        /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
                   3966:        /*   iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3967:        /*   cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   3968:        /*   k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   3969:        /*   cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   3970:        /*   printf(" i=%d,mi=%d,itv=%d,TmodelInvind[itv]=%d,cotvar[mw[mi][i]][TmodelInvind[itv]][i]=%f\n", i, mi, itv, TmodelInvind[itv],cotvar[mw[mi][i]][TmodelInvind[itv]][i]); */
                   3971:        /* } */
                   3972:        /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
                   3973:        /*   iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3974:        /*   /\* 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]); *\/ */
                   3975:        /*   cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
                   3976:        /* } */
                   3977:        /* for products of time varying to be done */
1.234     brouard  3978:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3979:          for (j=1;j<=nlstate+ndeath;j++){
                   3980:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3981:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3982:          }
1.336     brouard  3983: 
                   3984:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3985:        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  3986:        for(d=0; d<dh[mi][i]; d++){
                   3987:          newm=savm;
                   3988:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3989:          cov[2]=agexact;
                   3990:          if(nagesqr==1)
                   3991:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3992:          for (kk=1; kk<=cptcovage;kk++) {
1.318     brouard  3993:            if(!FixedV[Tvar[Tage[kk]]])
                   3994:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   3995:            else
1.341   ! brouard  3996:              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.234     brouard  3997:          }
                   3998:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3999:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4000:          savm=oldm;
                   4001:          oldm=newm;
                   4002:        } /* end mult */
                   4003:        
                   4004:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4005:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4006:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4007:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4008:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4009:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4010:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4011:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  4012:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4013:                                 * -stepm/2 to stepm/2 .
                   4014:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4015:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4016:                                 */
1.234     brouard  4017:        s1=s[mw[mi][i]][i];
                   4018:        s2=s[mw[mi+1][i]][i];
                   4019:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4020:        /* bias bh is positive if real duration
                   4021:         * is higher than the multiple of stepm and negative otherwise.
                   4022:         */
                   4023:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   4024:        if( s2 > nlstate){ 
                   4025:          /* i.e. if s2 is a death state and if the date of death is known 
                   4026:             then the contribution to the likelihood is the probability to 
                   4027:             die between last step unit time and current  step unit time, 
                   4028:             which is also equal to probability to die before dh 
                   4029:             minus probability to die before dh-stepm . 
                   4030:             In version up to 0.92 likelihood was computed
                   4031:             as if date of death was unknown. Death was treated as any other
                   4032:             health state: the date of the interview describes the actual state
                   4033:             and not the date of a change in health state. The former idea was
                   4034:             to consider that at each interview the state was recorded
                   4035:             (healthy, disable or death) and IMaCh was corrected; but when we
                   4036:             introduced the exact date of death then we should have modified
                   4037:             the contribution of an exact death to the likelihood. This new
                   4038:             contribution is smaller and very dependent of the step unit
                   4039:             stepm. It is no more the probability to die between last interview
                   4040:             and month of death but the probability to survive from last
                   4041:             interview up to one month before death multiplied by the
                   4042:             probability to die within a month. Thanks to Chris
                   4043:             Jackson for correcting this bug.  Former versions increased
                   4044:             mortality artificially. The bad side is that we add another loop
                   4045:             which slows down the processing. The difference can be up to 10%
                   4046:             lower mortality.
                   4047:          */
                   4048:          /* If, at the beginning of the maximization mostly, the
                   4049:             cumulative probability or probability to be dead is
                   4050:             constant (ie = 1) over time d, the difference is equal to
                   4051:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   4052:             s1 at precedent wave, to be dead a month before current
                   4053:             wave is equal to probability, being at state s1 at
                   4054:             precedent wave, to be dead at mont of the current
                   4055:             wave. Then the observed probability (that this person died)
                   4056:             is null according to current estimated parameter. In fact,
                   4057:             it should be very low but not zero otherwise the log go to
                   4058:             infinity.
                   4059:          */
1.183     brouard  4060: /* #ifdef INFINITYORIGINAL */
                   4061: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4062: /* #else */
                   4063: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   4064: /*         lli=log(mytinydouble); */
                   4065: /*       else */
                   4066: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4067: /* #endif */
1.226     brouard  4068:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4069:          
1.226     brouard  4070:        } else if  ( s2==-1 ) { /* alive */
                   4071:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4072:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4073:          /*survp += out[s1][j]; */
                   4074:          lli= log(survp);
                   4075:        }
1.336     brouard  4076:        /* else if  (s2==-4) {  */
                   4077:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
                   4078:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4079:        /*   lli= log(survp);  */
                   4080:        /* }  */
                   4081:        /* else if  (s2==-5) {  */
                   4082:        /*   for (j=1,survp=0. ; j<=2; j++)   */
                   4083:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4084:        /*   lli= log(survp);  */
                   4085:        /* }  */
1.226     brouard  4086:        else{
                   4087:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4088:          /*  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 */
                   4089:        } 
                   4090:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   4091:        /*if(lli ==000.0)*/
1.340     brouard  4092:        /* 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  4093:        ipmx +=1;
                   4094:        sw += weight[i];
                   4095:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4096:        /* if (lli < log(mytinydouble)){ */
                   4097:        /*   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); */
                   4098:        /*   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]); */
                   4099:        /* } */
                   4100:       } /* end of wave */
                   4101:     } /* end of individual */
                   4102:   }  else if(mle==2){
                   4103:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  4104:       ioffset=2+nagesqr ;
                   4105:       for (k=1; k<=ncovf;k++)
                   4106:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  4107:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  4108:        for(k=1; k <= ncovv ; k++){
1.341   ! brouard  4109:          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  4110:        }
1.226     brouard  4111:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4112:          for (j=1;j<=nlstate+ndeath;j++){
                   4113:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4114:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4115:          }
                   4116:        for(d=0; d<=dh[mi][i]; d++){
                   4117:          newm=savm;
                   4118:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4119:          cov[2]=agexact;
                   4120:          if(nagesqr==1)
                   4121:            cov[3]= agexact*agexact;
                   4122:          for (kk=1; kk<=cptcovage;kk++) {
                   4123:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4124:          }
                   4125:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4126:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4127:          savm=oldm;
                   4128:          oldm=newm;
                   4129:        } /* end mult */
                   4130:       
                   4131:        s1=s[mw[mi][i]][i];
                   4132:        s2=s[mw[mi+1][i]][i];
                   4133:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4134:        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 */
                   4135:        ipmx +=1;
                   4136:        sw += weight[i];
                   4137:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4138:       } /* end of wave */
                   4139:     } /* end of individual */
                   4140:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   4141:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4142:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4143:       for(mi=1; mi<= wav[i]-1; mi++){
                   4144:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4145:          for (j=1;j<=nlstate+ndeath;j++){
                   4146:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4147:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4148:          }
                   4149:        for(d=0; d<dh[mi][i]; d++){
                   4150:          newm=savm;
                   4151:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4152:          cov[2]=agexact;
                   4153:          if(nagesqr==1)
                   4154:            cov[3]= agexact*agexact;
                   4155:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4156:            if(!FixedV[Tvar[Tage[kk]]])
                   4157:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4158:            else
1.341   ! brouard  4159:              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  4160:          }
                   4161:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4162:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4163:          savm=oldm;
                   4164:          oldm=newm;
                   4165:        } /* end mult */
                   4166:       
                   4167:        s1=s[mw[mi][i]][i];
                   4168:        s2=s[mw[mi+1][i]][i];
                   4169:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4170:        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 */
                   4171:        ipmx +=1;
                   4172:        sw += weight[i];
                   4173:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4174:       } /* end of wave */
                   4175:     } /* end of individual */
                   4176:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   4177:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4178:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4179:       for(mi=1; mi<= wav[i]-1; mi++){
                   4180:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4181:          for (j=1;j<=nlstate+ndeath;j++){
                   4182:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4183:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4184:          }
                   4185:        for(d=0; d<dh[mi][i]; d++){
                   4186:          newm=savm;
                   4187:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4188:          cov[2]=agexact;
                   4189:          if(nagesqr==1)
                   4190:            cov[3]= agexact*agexact;
                   4191:          for (kk=1; kk<=cptcovage;kk++) {
                   4192:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4193:          }
1.126     brouard  4194:        
1.226     brouard  4195:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4196:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4197:          savm=oldm;
                   4198:          oldm=newm;
                   4199:        } /* end mult */
                   4200:       
                   4201:        s1=s[mw[mi][i]][i];
                   4202:        s2=s[mw[mi+1][i]][i];
                   4203:        if( s2 > nlstate){ 
                   4204:          lli=log(out[s1][s2] - savm[s1][s2]);
                   4205:        } else if  ( s2==-1 ) { /* alive */
                   4206:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4207:            survp += out[s1][j];
                   4208:          lli= log(survp);
                   4209:        }else{
                   4210:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4211:        }
                   4212:        ipmx +=1;
                   4213:        sw += weight[i];
                   4214:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.340     brouard  4215:        /* 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]); */
1.226     brouard  4216:       } /* end of wave */
                   4217:     } /* end of individual */
                   4218:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4219:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4220:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4221:       for(mi=1; mi<= wav[i]-1; mi++){
                   4222:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4223:          for (j=1;j<=nlstate+ndeath;j++){
                   4224:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4225:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4226:          }
                   4227:        for(d=0; d<dh[mi][i]; d++){
                   4228:          newm=savm;
                   4229:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4230:          cov[2]=agexact;
                   4231:          if(nagesqr==1)
                   4232:            cov[3]= agexact*agexact;
                   4233:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4234:            if(!FixedV[Tvar[Tage[kk]]])
                   4235:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4236:            else
1.341   ! brouard  4237:              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  4238:          }
1.126     brouard  4239:        
1.226     brouard  4240:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4241:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4242:          savm=oldm;
                   4243:          oldm=newm;
                   4244:        } /* end mult */
                   4245:       
                   4246:        s1=s[mw[mi][i]][i];
                   4247:        s2=s[mw[mi+1][i]][i];
                   4248:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4249:        ipmx +=1;
                   4250:        sw += weight[i];
                   4251:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4252:        /*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]);*/
                   4253:       } /* end of wave */
                   4254:     } /* end of individual */
                   4255:   } /* End of if */
                   4256:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4257:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4258:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4259:   return -l;
1.126     brouard  4260: }
                   4261: 
                   4262: /*************** log-likelihood *************/
                   4263: double funcone( double *x)
                   4264: {
1.228     brouard  4265:   /* Same as func but slower because of a lot of printf and if */
1.335     brouard  4266:   int i, ii, j, k, mi, d, kk, kf=0;
1.228     brouard  4267:   int ioffset=0;
1.339     brouard  4268:   int ipos=0,iposold=0,ncovv=0;
                   4269: 
1.340     brouard  4270:   double cotvarv, cotvarvold;
1.131     brouard  4271:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  4272:   double **out;
                   4273:   double lli; /* Individual log likelihood */
                   4274:   double llt;
                   4275:   int s1, s2;
1.228     brouard  4276:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4277: 
1.126     brouard  4278:   double bbh, survp;
1.187     brouard  4279:   double agexact;
1.214     brouard  4280:   double agebegin, ageend;
1.126     brouard  4281:   /*extern weight */
                   4282:   /* We are differentiating ll according to initial status */
                   4283:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4284:   /*for(i=1;i<imx;i++) 
                   4285:     printf(" %d\n",s[4][i]);
                   4286:   */
                   4287:   cov[1]=1.;
                   4288: 
                   4289:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4290:   ioffset=0;
                   4291:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.336     brouard  4292:     /* Computes the values of the ncovmodel covariates of the model
                   4293:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4294:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4295:        to be observed in j being in i according to the model.
                   4296:     */
1.243     brouard  4297:     /* ioffset=2+nagesqr+cptcovage; */
                   4298:     ioffset=2+nagesqr;
1.232     brouard  4299:     /* Fixed */
1.224     brouard  4300:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4301:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.335     brouard  4302:     for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
1.339     brouard  4303:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
                   4304:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
                   4305:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
1.335     brouard  4306:       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  4307: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4308: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4309: /*    cov[2+6]=covar[2][i]; V2  */
                   4310: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4311: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4312: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4313: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4314: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4315: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4316:     }
1.336     brouard  4317:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   4318:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   4319:         has been calculated etc */
                   4320:       /* For an individual i, wav[i] gives the number of effective waves */
                   4321:       /* We compute the contribution to Likelihood of each effective transition
                   4322:         mw[mi][i] is real wave of the mi th effectve wave */
                   4323:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4324:         s2=s[mw[mi+1][i]][i];
1.341   ! brouard  4325:         And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][ncovcol+nqv+iv][i]
1.336     brouard  4326:       */
                   4327:     /* This part may be useless now because everythin should be in covar */
1.232     brouard  4328:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4329:     /*   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?)*\/ */
                   4330:     /* } */
1.231     brouard  4331:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4332:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4333:     /* } */
1.225     brouard  4334:     
1.233     brouard  4335: 
                   4336:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.339     brouard  4337:       /* 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 */
                   4338:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
                   4339:       /*       /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
                   4340:       /*       cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4341:       /* } */
                   4342:       
                   4343:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   4344:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   4345:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   4346:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
                   4347:       /* We need the position of the time varying or product in the model */
                   4348:       /* 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 */            
                   4349:       /* TvarVV gives the variable name */
1.340     brouard  4350:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   4351:       *      k=         1   2     3     4         5        6        7       8        9
                   4352:       *  varying            1     2                                 3       4        5
                   4353:       *  ncovv              1     2                                3 4     5 6      7 8
                   4354:       *  TvarVV            V3     5                                1 3     3 5      1 5
                   4355:       * TvarVVind           2     3                                7 7     8 8      9 9
                   4356:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
                   4357:       * cotvar starts at ntv=2 (because of V3 V4)
                   4358:       */
                   4359:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
                   4360:        itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4361:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4362:        if(TvarFind[itv]==0){ /* Not a fixed covariate */
1.341   ! brouard  4363:          cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.340     brouard  4364:        }else{ /* fixed covariate */
                   4365:          cotvarv=covar[Tvar[TvarFind[itv]]][i];
                   4366:        }
1.339     brouard  4367:        if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  4368:          cotvarvold=cotvarv;
                   4369:        }else{ /* A second product */
                   4370:          cotvarv=cotvarv*cotvarvold;
1.339     brouard  4371:        }
                   4372:        iposold=ipos;
1.340     brouard  4373:        cov[ioffset+ipos]=cotvarv;
1.339     brouard  4374:        /* For products */
                   4375:       }
                   4376:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
                   4377:       /*       iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
                   4378:       /*       /\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
                   4379:       /*       /\*           1  2   3      4      5                         *\/ */
                   4380:       /*       /\*itv           1                                           *\/ */
                   4381:       /*       /\* TvarVInd[1]= 2                                           *\/ */
                   4382:       /*       /\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
                   4383:       /*       /\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
                   4384:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
                   4385:       /*       /\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
                   4386:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
                   4387:       /*       cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
                   4388:       /*       /\* 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]); *\/ */
                   4389:       /* } */
1.232     brouard  4390:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4391:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4392:       /*       /\* 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]); *\/ */
                   4393:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4394:       /* } */
1.126     brouard  4395:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4396:        for (j=1;j<=nlstate+ndeath;j++){
                   4397:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4398:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4399:        }
1.214     brouard  4400:       
                   4401:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4402:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4403:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4404:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4405:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4406:          and mw[mi+1][i]. dh depends on stepm.*/
                   4407:        newm=savm;
1.247     brouard  4408:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4409:        cov[2]=agexact;
                   4410:        if(nagesqr==1)
                   4411:          cov[3]= agexact*agexact;
                   4412:        for (kk=1; kk<=cptcovage;kk++) {
                   4413:          if(!FixedV[Tvar[Tage[kk]]])
                   4414:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4415:          else
1.341   ! brouard  4416:            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.242     brouard  4417:        }
                   4418:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4419:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4420:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4421:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4422:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4423:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4424:        savm=oldm;
                   4425:        oldm=newm;
1.126     brouard  4426:       } /* end mult */
1.336     brouard  4427:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4428:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4429:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4430:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4431:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4432:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4433:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4434:         * probability in order to take into account the bias as a fraction of the way
                   4435:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4436:                                 * -stepm/2 to stepm/2 .
                   4437:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4438:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4439:                                 */
1.126     brouard  4440:       s1=s[mw[mi][i]][i];
                   4441:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4442:       /* if(s2==-1){ */
1.268     brouard  4443:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4444:       /*       /\* exit(1); *\/ */
                   4445:       /* } */
1.126     brouard  4446:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4447:       /* bias is positive if real duration
                   4448:        * is higher than the multiple of stepm and negative otherwise.
                   4449:        */
                   4450:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4451:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4452:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4453:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4454:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4455:        lli= log(survp);
1.126     brouard  4456:       }else if (mle==1){
1.242     brouard  4457:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4458:       } else if(mle==2){
1.242     brouard  4459:        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  4460:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4461:        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  4462:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4463:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4464:       } else{  /* mle=0 back to 1 */
1.242     brouard  4465:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4466:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4467:       } /* End of if */
                   4468:       ipmx +=1;
                   4469:       sw += weight[i];
                   4470:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.340     brouard  4471:       printf("Funcone num[i]=%ld i=%6d V= ", num[i], i);
                   4472:       for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
                   4473:        printf("%g",covar[Tvar[TvarFind[kf]]][i]);
                   4474:       }
                   4475:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
                   4476:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4477:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4478:          printf(" %g",cov[ioffset+ipos]);
                   4479:        }else{
                   4480:          printf("*");
                   4481:        }
                   4482:        iposold=ipos;
                   4483:       }
                   4484:       for (kk=1; kk<=cptcovage;kk++) {
                   4485:        if(!FixedV[Tvar[Tage[kk]]])
                   4486:          printf(" %g*age",covar[Tvar[Tage[kk]]][i]);
                   4487:        else
1.341   ! brouard  4488:          printf(" %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.340     brouard  4489:       }
                   4490:       printf(" s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",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  4491:       if(globpr){
1.246     brouard  4492:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4493:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4494:                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  4495:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.335     brouard  4496:  /*    printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
                   4497:  /* %11.6f %11.6f %11.6f ", \ */
                   4498:  /*            num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   4499:  /*            2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  4500:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4501:          llt +=ll[k]*gipmx/gsw;
                   4502:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335     brouard  4503:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  4504:        }
                   4505:        fprintf(ficresilk," %10.6f\n", -llt);
1.335     brouard  4506:        /* printf(" %10.6f\n", -llt); */
1.126     brouard  4507:       }
1.335     brouard  4508:     } /* end of wave */
                   4509:   } /* end of individual */
                   4510:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  4511: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335     brouard  4512:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4513:   if(globpr==0){ /* First time we count the contributions and weights */
                   4514:     gipmx=ipmx;
                   4515:     gsw=sw;
                   4516:   }
1.232     brouard  4517: return -l;
1.126     brouard  4518: }
                   4519: 
                   4520: 
                   4521: /*************** function likelione ***********/
1.292     brouard  4522: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4523: {
                   4524:   /* This routine should help understanding what is done with 
                   4525:      the selection of individuals/waves and
                   4526:      to check the exact contribution to the likelihood.
                   4527:      Plotting could be done.
                   4528:    */
                   4529:   int k;
                   4530: 
                   4531:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4532:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4533:     strcat(fileresilk,fileresu);
1.126     brouard  4534:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4535:       printf("Problem with resultfile: %s\n", fileresilk);
                   4536:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4537:     }
1.214     brouard  4538:     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");
                   4539:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4540:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4541:     for(k=1; k<=nlstate; k++) 
                   4542:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   4543:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   4544:   }
                   4545: 
1.292     brouard  4546:   *fretone=(*func)(p);
1.126     brouard  4547:   if(*globpri !=0){
                   4548:     fclose(ficresilk);
1.205     brouard  4549:     if (mle ==0)
                   4550:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4551:     else if(mle >=1)
                   4552:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4553:     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  4554:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4555:       
                   4556:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  4557:       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> \
1.208     brouard  4558: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4559:     }
1.207     brouard  4560:     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.204     brouard  4561: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4562:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  4563: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4564:     fflush(fichtm);
1.205     brouard  4565:   }
1.126     brouard  4566:   return;
                   4567: }
                   4568: 
                   4569: 
                   4570: /*********** Maximum Likelihood Estimation ***************/
                   4571: 
                   4572: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4573: {
1.319     brouard  4574:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4575:   double **xi;
                   4576:   double fret;
                   4577:   double fretone; /* Only one call to likelihood */
                   4578:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4579: 
                   4580: #ifdef NLOPT
                   4581:   int creturn;
                   4582:   nlopt_opt opt;
                   4583:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4584:   double *lb;
                   4585:   double minf; /* the minimum objective value, upon return */
                   4586:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4587:   myfunc_data dinst, *d = &dinst;
                   4588: #endif
                   4589: 
                   4590: 
1.126     brouard  4591:   xi=matrix(1,npar,1,npar);
                   4592:   for (i=1;i<=npar;i++)
                   4593:     for (j=1;j<=npar;j++)
                   4594:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4595:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4596:   strcpy(filerespow,"POW_"); 
1.126     brouard  4597:   strcat(filerespow,fileres);
                   4598:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4599:     printf("Problem with resultfile: %s\n", filerespow);
                   4600:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4601:   }
                   4602:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4603:   for (i=1;i<=nlstate;i++)
                   4604:     for(j=1;j<=nlstate+ndeath;j++)
                   4605:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4606:   fprintf(ficrespow,"\n");
1.162     brouard  4607: #ifdef POWELL
1.319     brouard  4608: #ifdef LINMINORIGINAL
                   4609: #else /* LINMINORIGINAL */
                   4610:   
                   4611:   flatdir=ivector(1,npar); 
                   4612:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4613: #endif /*LINMINORIGINAL */
                   4614: 
                   4615: #ifdef FLATSUP
                   4616:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4617:   /* reorganizing p by suppressing flat directions */
                   4618:   for(i=1, jk=1; i <=nlstate; i++){
                   4619:     for(k=1; k <=(nlstate+ndeath); k++){
                   4620:       if (k != i) {
                   4621:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4622:         if(flatdir[jk]==1){
                   4623:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4624:         }
                   4625:         for(j=1; j <=ncovmodel; j++){
                   4626:           printf("%12.7f ",p[jk]);
                   4627:           jk++; 
                   4628:         }
                   4629:         printf("\n");
                   4630:       }
                   4631:     }
                   4632:   }
                   4633: /* skipping */
                   4634:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   4635:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   4636:     for(k=1; k <=(nlstate+ndeath); k++){
                   4637:       if (k != i) {
                   4638:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4639:         if(flatdir[jk]==1){
                   4640:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   4641:           for(j=1; j <=ncovmodel;  jk++,j++){
                   4642:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   4643:             /*q[jjk]=p[jk];*/
                   4644:           }
                   4645:         }else{
                   4646:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   4647:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   4648:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   4649:             /*q[jjk]=p[jk];*/
                   4650:           }
                   4651:         }
                   4652:         printf("\n");
                   4653:       }
                   4654:       fflush(stdout);
                   4655:     }
                   4656:   }
                   4657:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4658: #else  /* FLATSUP */
1.126     brouard  4659:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  4660: #endif  /* FLATSUP */
                   4661: 
                   4662: #ifdef LINMINORIGINAL
                   4663: #else
                   4664:       free_ivector(flatdir,1,npar); 
                   4665: #endif  /* LINMINORIGINAL*/
                   4666: #endif /* POWELL */
1.126     brouard  4667: 
1.162     brouard  4668: #ifdef NLOPT
                   4669: #ifdef NEWUOA
                   4670:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4671: #else
                   4672:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4673: #endif
                   4674:   lb=vector(0,npar-1);
                   4675:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4676:   nlopt_set_lower_bounds(opt, lb);
                   4677:   nlopt_set_initial_step1(opt, 0.1);
                   4678:   
                   4679:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4680:   d->function = func;
                   4681:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4682:   nlopt_set_min_objective(opt, myfunc, d);
                   4683:   nlopt_set_xtol_rel(opt, ftol);
                   4684:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4685:     printf("nlopt failed! %d\n",creturn); 
                   4686:   }
                   4687:   else {
                   4688:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4689:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4690:     iter=1; /* not equal */
                   4691:   }
                   4692:   nlopt_destroy(opt);
                   4693: #endif
1.319     brouard  4694: #ifdef FLATSUP
                   4695:   /* npared = npar -flatd/ncovmodel; */
                   4696:   /* xired= matrix(1,npared,1,npared); */
                   4697:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   4698:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   4699:   /* free_matrix(xire,1,npared,1,npared); */
                   4700: #else  /* FLATSUP */
                   4701: #endif /* FLATSUP */
1.126     brouard  4702:   free_matrix(xi,1,npar,1,npar);
                   4703:   fclose(ficrespow);
1.203     brouard  4704:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4705:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4706:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4707: 
                   4708: }
                   4709: 
                   4710: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4711: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4712: {
                   4713:   double  **a,**y,*x,pd;
1.203     brouard  4714:   /* double **hess; */
1.164     brouard  4715:   int i, j;
1.126     brouard  4716:   int *indx;
                   4717: 
                   4718:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4719:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4720:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4721:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4722:   double gompertz(double p[]);
1.203     brouard  4723:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4724: 
                   4725:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4726:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4727:   for (i=1;i<=npar;i++){
1.203     brouard  4728:     printf("%d-",i);fflush(stdout);
                   4729:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4730:    
                   4731:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4732:     
                   4733:     /*  printf(" %f ",p[i]);
                   4734:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4735:   }
                   4736:   
                   4737:   for (i=1;i<=npar;i++) {
                   4738:     for (j=1;j<=npar;j++)  {
                   4739:       if (j>i) { 
1.203     brouard  4740:        printf(".%d-%d",i,j);fflush(stdout);
                   4741:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4742:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4743:        
                   4744:        hess[j][i]=hess[i][j];    
                   4745:        /*printf(" %lf ",hess[i][j]);*/
                   4746:       }
                   4747:     }
                   4748:   }
                   4749:   printf("\n");
                   4750:   fprintf(ficlog,"\n");
                   4751: 
                   4752:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4753:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4754:   
                   4755:   a=matrix(1,npar,1,npar);
                   4756:   y=matrix(1,npar,1,npar);
                   4757:   x=vector(1,npar);
                   4758:   indx=ivector(1,npar);
                   4759:   for (i=1;i<=npar;i++)
                   4760:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4761:   ludcmp(a,npar,indx,&pd);
                   4762: 
                   4763:   for (j=1;j<=npar;j++) {
                   4764:     for (i=1;i<=npar;i++) x[i]=0;
                   4765:     x[j]=1;
                   4766:     lubksb(a,npar,indx,x);
                   4767:     for (i=1;i<=npar;i++){ 
                   4768:       matcov[i][j]=x[i];
                   4769:     }
                   4770:   }
                   4771: 
                   4772:   printf("\n#Hessian matrix#\n");
                   4773:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4774:   for (i=1;i<=npar;i++) { 
                   4775:     for (j=1;j<=npar;j++) { 
1.203     brouard  4776:       printf("%.6e ",hess[i][j]);
                   4777:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4778:     }
                   4779:     printf("\n");
                   4780:     fprintf(ficlog,"\n");
                   4781:   }
                   4782: 
1.203     brouard  4783:   /* printf("\n#Covariance matrix#\n"); */
                   4784:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4785:   /* for (i=1;i<=npar;i++) {  */
                   4786:   /*   for (j=1;j<=npar;j++) {  */
                   4787:   /*     printf("%.6e ",matcov[i][j]); */
                   4788:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4789:   /*   } */
                   4790:   /*   printf("\n"); */
                   4791:   /*   fprintf(ficlog,"\n"); */
                   4792:   /* } */
                   4793: 
1.126     brouard  4794:   /* Recompute Inverse */
1.203     brouard  4795:   /* for (i=1;i<=npar;i++) */
                   4796:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4797:   /* ludcmp(a,npar,indx,&pd); */
                   4798: 
                   4799:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4800: 
                   4801:   /* for (j=1;j<=npar;j++) { */
                   4802:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4803:   /*   x[j]=1; */
                   4804:   /*   lubksb(a,npar,indx,x); */
                   4805:   /*   for (i=1;i<=npar;i++){  */
                   4806:   /*     y[i][j]=x[i]; */
                   4807:   /*     printf("%.3e ",y[i][j]); */
                   4808:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4809:   /*   } */
                   4810:   /*   printf("\n"); */
                   4811:   /*   fprintf(ficlog,"\n"); */
                   4812:   /* } */
                   4813: 
                   4814:   /* Verifying the inverse matrix */
                   4815: #ifdef DEBUGHESS
                   4816:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4817: 
1.203     brouard  4818:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4819:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4820: 
                   4821:   for (j=1;j<=npar;j++) {
                   4822:     for (i=1;i<=npar;i++){ 
1.203     brouard  4823:       printf("%.2f ",y[i][j]);
                   4824:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4825:     }
                   4826:     printf("\n");
                   4827:     fprintf(ficlog,"\n");
                   4828:   }
1.203     brouard  4829: #endif
1.126     brouard  4830: 
                   4831:   free_matrix(a,1,npar,1,npar);
                   4832:   free_matrix(y,1,npar,1,npar);
                   4833:   free_vector(x,1,npar);
                   4834:   free_ivector(indx,1,npar);
1.203     brouard  4835:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4836: 
                   4837: 
                   4838: }
                   4839: 
                   4840: /*************** hessian matrix ****************/
                   4841: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4842: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4843:   int i;
                   4844:   int l=1, lmax=20;
1.203     brouard  4845:   double k1,k2, res, fx;
1.132     brouard  4846:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4847:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4848:   int k=0,kmax=10;
                   4849:   double l1;
                   4850: 
                   4851:   fx=func(x);
                   4852:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  4853:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  4854:     l1=pow(10,l);
                   4855:     delts=delt;
                   4856:     for(k=1 ; k <kmax; k=k+1){
                   4857:       delt = delta*(l1*k);
                   4858:       p2[theta]=x[theta] +delt;
1.145     brouard  4859:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  4860:       p2[theta]=x[theta]-delt;
                   4861:       k2=func(p2)-fx;
                   4862:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  4863:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  4864:       
1.203     brouard  4865: #ifdef DEBUGHESSII
1.126     brouard  4866:       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);
                   4867:       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);
                   4868: #endif
                   4869:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   4870:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   4871:        k=kmax;
                   4872:       }
                   4873:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4874:        k=kmax; l=lmax*10;
1.126     brouard  4875:       }
                   4876:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4877:        delts=delt;
                   4878:       }
1.203     brouard  4879:     } /* End loop k */
1.126     brouard  4880:   }
                   4881:   delti[theta]=delts;
                   4882:   return res; 
                   4883:   
                   4884: }
                   4885: 
1.203     brouard  4886: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  4887: {
                   4888:   int i;
1.164     brouard  4889:   int l=1, lmax=20;
1.126     brouard  4890:   double k1,k2,k3,k4,res,fx;
1.132     brouard  4891:   double p2[MAXPARM+1];
1.203     brouard  4892:   int k, kmax=1;
                   4893:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  4894: 
                   4895:   int firstime=0;
1.203     brouard  4896:   
1.126     brouard  4897:   fx=func(x);
1.203     brouard  4898:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  4899:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  4900:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4901:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4902:     k1=func(p2)-fx;
                   4903:   
1.203     brouard  4904:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4905:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4906:     k2=func(p2)-fx;
                   4907:   
1.203     brouard  4908:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4909:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4910:     k3=func(p2)-fx;
                   4911:   
1.203     brouard  4912:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4913:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4914:     k4=func(p2)-fx;
1.203     brouard  4915:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4916:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4917:       firstime=1;
1.203     brouard  4918:       kmax=kmax+10;
1.208     brouard  4919:     }
                   4920:     if(kmax >=10 || firstime ==1){
1.246     brouard  4921:       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);
                   4922:       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  4923:       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);
                   4924:       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);
                   4925:     }
                   4926: #ifdef DEBUGHESSIJ
                   4927:     v1=hess[thetai][thetai];
                   4928:     v2=hess[thetaj][thetaj];
                   4929:     cv12=res;
                   4930:     /* Computing eigen value of Hessian matrix */
                   4931:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4932:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4933:     if ((lc2 <0) || (lc1 <0) ){
                   4934:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4935:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4936:       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);
                   4937:       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);
                   4938:     }
1.126     brouard  4939: #endif
                   4940:   }
                   4941:   return res;
                   4942: }
                   4943: 
1.203     brouard  4944:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4945: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4946: /* { */
                   4947: /*   int i; */
                   4948: /*   int l=1, lmax=20; */
                   4949: /*   double k1,k2,k3,k4,res,fx; */
                   4950: /*   double p2[MAXPARM+1]; */
                   4951: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4952: /*   int k=0,kmax=10; */
                   4953: /*   double l1; */
                   4954:   
                   4955: /*   fx=func(x); */
                   4956: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4957: /*     l1=pow(10,l); */
                   4958: /*     delts=delt; */
                   4959: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4960: /*       delt = delti*(l1*k); */
                   4961: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4962: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4963: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4964: /*       k1=func(p2)-fx; */
                   4965:       
                   4966: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4967: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4968: /*       k2=func(p2)-fx; */
                   4969:       
                   4970: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4971: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4972: /*       k3=func(p2)-fx; */
                   4973:       
                   4974: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4975: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4976: /*       k4=func(p2)-fx; */
                   4977: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4978: /* #ifdef DEBUGHESSIJ */
                   4979: /*       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); */
                   4980: /*       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); */
                   4981: /* #endif */
                   4982: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4983: /*     k=kmax; */
                   4984: /*       } */
                   4985: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4986: /*     k=kmax; l=lmax*10; */
                   4987: /*       } */
                   4988: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4989: /*     delts=delt; */
                   4990: /*       } */
                   4991: /*     } /\* End loop k *\/ */
                   4992: /*   } */
                   4993: /*   delti[theta]=delts; */
                   4994: /*   return res;  */
                   4995: /* } */
                   4996: 
                   4997: 
1.126     brouard  4998: /************** Inverse of matrix **************/
                   4999: void ludcmp(double **a, int n, int *indx, double *d) 
                   5000: { 
                   5001:   int i,imax,j,k; 
                   5002:   double big,dum,sum,temp; 
                   5003:   double *vv; 
                   5004:  
                   5005:   vv=vector(1,n); 
                   5006:   *d=1.0; 
                   5007:   for (i=1;i<=n;i++) { 
                   5008:     big=0.0; 
                   5009:     for (j=1;j<=n;j++) 
                   5010:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  5011:     if (big == 0.0){
                   5012:       printf(" Singular Hessian matrix at row %d:\n",i);
                   5013:       for (j=1;j<=n;j++) {
                   5014:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   5015:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   5016:       }
                   5017:       fflush(ficlog);
                   5018:       fclose(ficlog);
                   5019:       nrerror("Singular matrix in routine ludcmp"); 
                   5020:     }
1.126     brouard  5021:     vv[i]=1.0/big; 
                   5022:   } 
                   5023:   for (j=1;j<=n;j++) { 
                   5024:     for (i=1;i<j;i++) { 
                   5025:       sum=a[i][j]; 
                   5026:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   5027:       a[i][j]=sum; 
                   5028:     } 
                   5029:     big=0.0; 
                   5030:     for (i=j;i<=n;i++) { 
                   5031:       sum=a[i][j]; 
                   5032:       for (k=1;k<j;k++) 
                   5033:        sum -= a[i][k]*a[k][j]; 
                   5034:       a[i][j]=sum; 
                   5035:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   5036:        big=dum; 
                   5037:        imax=i; 
                   5038:       } 
                   5039:     } 
                   5040:     if (j != imax) { 
                   5041:       for (k=1;k<=n;k++) { 
                   5042:        dum=a[imax][k]; 
                   5043:        a[imax][k]=a[j][k]; 
                   5044:        a[j][k]=dum; 
                   5045:       } 
                   5046:       *d = -(*d); 
                   5047:       vv[imax]=vv[j]; 
                   5048:     } 
                   5049:     indx[j]=imax; 
                   5050:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   5051:     if (j != n) { 
                   5052:       dum=1.0/(a[j][j]); 
                   5053:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   5054:     } 
                   5055:   } 
                   5056:   free_vector(vv,1,n);  /* Doesn't work */
                   5057: ;
                   5058: } 
                   5059: 
                   5060: void lubksb(double **a, int n, int *indx, double b[]) 
                   5061: { 
                   5062:   int i,ii=0,ip,j; 
                   5063:   double sum; 
                   5064:  
                   5065:   for (i=1;i<=n;i++) { 
                   5066:     ip=indx[i]; 
                   5067:     sum=b[ip]; 
                   5068:     b[ip]=b[i]; 
                   5069:     if (ii) 
                   5070:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   5071:     else if (sum) ii=i; 
                   5072:     b[i]=sum; 
                   5073:   } 
                   5074:   for (i=n;i>=1;i--) { 
                   5075:     sum=b[i]; 
                   5076:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   5077:     b[i]=sum/a[i][i]; 
                   5078:   } 
                   5079: } 
                   5080: 
                   5081: void pstamp(FILE *fichier)
                   5082: {
1.196     brouard  5083:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  5084: }
                   5085: 
1.297     brouard  5086: void date2dmy(double date,double *day, double *month, double *year){
                   5087:   double yp=0., yp1=0., yp2=0.;
                   5088:   
                   5089:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   5090:                        fractional in yp1 */
                   5091:   *year=yp;
                   5092:   yp2=modf((yp1*12),&yp);
                   5093:   *month=yp;
                   5094:   yp1=modf((yp2*30.5),&yp);
                   5095:   *day=yp;
                   5096:   if(*day==0) *day=1;
                   5097:   if(*month==0) *month=1;
                   5098: }
                   5099: 
1.253     brouard  5100: 
                   5101: 
1.126     brouard  5102: /************ Frequencies ********************/
1.251     brouard  5103: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  5104:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   5105:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  5106: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  5107:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  5108:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  5109:   int iind=0, iage=0;
                   5110:   int mi; /* Effective wave */
                   5111:   int first;
                   5112:   double ***freq; /* Frequencies */
1.268     brouard  5113:   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 */
                   5114:   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  5115:   double *meanq, *stdq, *idq;
1.226     brouard  5116:   double **meanqt;
                   5117:   double *pp, **prop, *posprop, *pospropt;
                   5118:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   5119:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   5120:   double agebegin, ageend;
                   5121:     
                   5122:   pp=vector(1,nlstate);
1.251     brouard  5123:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  5124:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   5125:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   5126:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   5127:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  5128:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  5129:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  5130:   meanqt=matrix(1,lastpass,1,nqtveff);
                   5131:   strcpy(fileresp,"P_");
                   5132:   strcat(fileresp,fileresu);
                   5133:   /*strcat(fileresphtm,fileresu);*/
                   5134:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   5135:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   5136:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   5137:     exit(0);
                   5138:   }
1.240     brouard  5139:   
1.226     brouard  5140:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   5141:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   5142:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5143:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5144:     fflush(ficlog);
                   5145:     exit(70); 
                   5146:   }
                   5147:   else{
                   5148:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  5149: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  5150: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5151:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5152:   }
1.319     brouard  5153:   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  5154:   
1.226     brouard  5155:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   5156:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   5157:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5158:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5159:     fflush(ficlog);
                   5160:     exit(70); 
1.240     brouard  5161:   } else{
1.226     brouard  5162:     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  5163: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  5164: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5165:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5166:   }
1.319     brouard  5167:   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  5168:   
1.253     brouard  5169:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   5170:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  5171:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  5172:   j1=0;
1.126     brouard  5173:   
1.227     brouard  5174:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335     brouard  5175:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  5176:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  5177:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  5178:   
                   5179:   
1.226     brouard  5180:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   5181:      reference=low_education V1=0,V2=0
                   5182:      med_educ                V1=1 V2=0, 
                   5183:      high_educ               V1=0 V2=1
1.330     brouard  5184:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  5185:   */
1.249     brouard  5186:   dateintsum=0;
                   5187:   k2cpt=0;
                   5188: 
1.253     brouard  5189:   if(cptcoveff == 0 )
1.265     brouard  5190:     nl=1;  /* Constant and age model only */
1.253     brouard  5191:   else
                   5192:     nl=2;
1.265     brouard  5193: 
                   5194:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   5195:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335     brouard  5196:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  5197:    *     freq[s1][s2][iage] =0.
                   5198:    *     Loop on iind
                   5199:    *       ++freq[s1][s2][iage] weighted
                   5200:    *     end iind
                   5201:    *     if covariate and j!0
                   5202:    *       headers Variable on one line
                   5203:    *     endif cov j!=0
                   5204:    *     header of frequency table by age
                   5205:    *     Loop on age
                   5206:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   5207:    *       pos+=freq[s1][s2][iage] weighted
                   5208:    *       Loop on s1 initial state
                   5209:    *         fprintf(ficresp
                   5210:    *       end s1
                   5211:    *     end age
                   5212:    *     if j!=0 computes starting values
                   5213:    *     end compute starting values
                   5214:    *   end j1
                   5215:    * end nl 
                   5216:    */
1.253     brouard  5217:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   5218:     if(nj==1)
                   5219:       j=0;  /* First pass for the constant */
1.265     brouard  5220:     else{
1.335     brouard  5221:       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  5222:     }
1.251     brouard  5223:     first=1;
1.332     brouard  5224:     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  5225:       posproptt=0.;
1.330     brouard  5226:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  5227:        scanf("%d", i);*/
                   5228:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  5229:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  5230:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  5231:            freq[i][s2][m]=0;
1.251     brouard  5232:       
                   5233:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  5234:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  5235:          prop[i][m]=0;
                   5236:        posprop[i]=0;
                   5237:        pospropt[i]=0;
                   5238:       }
1.283     brouard  5239:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  5240:         idq[z1]=0.;
                   5241:         meanq[z1]=0.;
                   5242:         stdq[z1]=0.;
1.283     brouard  5243:       }
                   5244:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  5245:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  5246:       /*         meanqt[m][z1]=0.; */
                   5247:       /*       } */
                   5248:       /* }       */
1.251     brouard  5249:       /* dateintsum=0; */
                   5250:       /* k2cpt=0; */
                   5251:       
1.265     brouard  5252:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  5253:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   5254:        bool=1;
                   5255:        if(j !=0){
                   5256:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335     brouard  5257:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   5258:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  5259:                /* if(Tvaraff[z1] ==-20){ */
                   5260:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   5261:                /* }else  if(Tvaraff[z1] ==-10){ */
                   5262:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  5263:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335     brouard  5264:                /* 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); */
                   5265:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
1.338     brouard  5266:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  5267:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  5268:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  5269:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  5270:                  /* 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", */
                   5271:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   5272:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  5273:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   5274:                } /* Onlyf fixed */
                   5275:              } /* end z1 */
1.335     brouard  5276:            } /* cptcoveff > 0 */
1.251     brouard  5277:          } /* end any */
                   5278:        }/* end j==0 */
1.265     brouard  5279:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  5280:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  5281:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  5282:            m=mw[mi][iind];
                   5283:            if(j!=0){
                   5284:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335     brouard  5285:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  5286:                  if( Fixed[Tmodelind[z1]]==1){
1.341   ! brouard  5287:                    /* iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /\* Good *\/ */
        !          5288:                    iv= Tvar[Tmodelind[z1]]; /* Good *//* because cotvar starts now at first at ncovcol+nqv+ntv */ 
1.332     brouard  5289:                    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  5290:                                                                                      value is -1, we don't select. It differs from the 
                   5291:                                                                                      constant and age model which counts them. */
                   5292:                      bool=0; /* not selected */
                   5293:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  5294:                    /* i1=Tvaraff[z1]; */
                   5295:                    /* i2=TnsdVar[i1]; */
                   5296:                    /* i3=nbcode[i1][i2]; */
                   5297:                    /* i4=covar[i1][iind]; */
                   5298:                    /* if(i4 != i3){ */
                   5299:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  5300:                      bool=0;
                   5301:                    }
                   5302:                  }
                   5303:                }
                   5304:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   5305:            } /* end j==0 */
                   5306:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  5307:            if(bool==1){ /*Selected */
1.251     brouard  5308:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   5309:                 and mw[mi+1][iind]. dh depends on stepm. */
                   5310:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   5311:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   5312:              if(m >=firstpass && m <=lastpass){
                   5313:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   5314:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   5315:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   5316:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   5317:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   5318:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   5319:                if (m<lastpass) {
                   5320:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   5321:                  /*   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]); */
                   5322:                  if(s[m][iind]==-1)
                   5323:                    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.));
                   5324:                  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  5325:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   5326:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  5327:                      idq[z1]=idq[z1]+weight[iind];
                   5328:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   5329:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   5330:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  5331:                    }
1.284     brouard  5332:                  }
1.251     brouard  5333:                  /* if((int)agev[m][iind] == 55) */
                   5334:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5335:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5336:                  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  5337:                }
1.251     brouard  5338:              } /* end if between passes */  
                   5339:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5340:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5341:                k2cpt++;
                   5342:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  5343:              }
1.251     brouard  5344:            }else{
                   5345:              bool=1;
                   5346:            }/* end bool 2 */
                   5347:          } /* end m */
1.284     brouard  5348:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5349:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5350:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5351:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5352:          /* } */
1.251     brouard  5353:        } /* end bool */
                   5354:       } /* end iind = 1 to imx */
1.319     brouard  5355:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  5356:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5357:       
                   5358:       
                   5359:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335     brouard  5360:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  5361:         pstamp(ficresp);
1.335     brouard  5362:       if  (cptcoveff>0 && j!=0){
1.265     brouard  5363:         pstamp(ficresp);
1.251     brouard  5364:        printf( "\n#********** Variable "); 
                   5365:        fprintf(ficresp, "\n#********** Variable "); 
                   5366:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5367:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5368:        fprintf(ficlog, "\n#********** Variable "); 
1.340     brouard  5369:        for (z1=1; z1<=cptcoveff; z1++){
1.251     brouard  5370:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  5371:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5372:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5373:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5374:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5375:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  5376:          }else{
1.330     brouard  5377:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5378:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5379:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5380:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5381:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5382:          }
                   5383:        }
                   5384:        printf( "**********\n#");
                   5385:        fprintf(ficresp, "**********\n#");
                   5386:        fprintf(ficresphtm, "**********</h3>\n");
                   5387:        fprintf(ficresphtmfr, "**********</h3>\n");
                   5388:        fprintf(ficlog, "**********\n");
                   5389:       }
1.284     brouard  5390:       /*
                   5391:        Printing means of quantitative variables if any
                   5392:       */
                   5393:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5394:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5395:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5396:        if(weightopt==1){
                   5397:          printf(" Weighted mean and standard deviation of");
                   5398:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5399:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5400:        }
1.311     brouard  5401:        /* mu = \frac{w x}{\sum w}
                   5402:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5403:        */
                   5404:        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]));
                   5405:        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]));
                   5406:        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  5407:       }
                   5408:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5409:       /*       for(m=1;m<=lastpass;m++){ */
                   5410:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5411:       /*   } */
                   5412:       /* } */
1.283     brouard  5413: 
1.251     brouard  5414:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335     brouard  5415:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  5416:         fprintf(ficresp, " Age");
1.335     brouard  5417:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   5418:          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]]);
                   5419:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5420:        }
1.251     brouard  5421:       for(i=1; i<=nlstate;i++) {
1.335     brouard  5422:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5423:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5424:       }
1.335     brouard  5425:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5426:       fprintf(ficresphtm, "\n");
                   5427:       
                   5428:       /* Header of frequency table by age */
                   5429:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5430:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5431:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5432:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5433:          if(s2!=0 && m!=0)
                   5434:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5435:        }
1.226     brouard  5436:       }
1.251     brouard  5437:       fprintf(ficresphtmfr, "\n");
                   5438:     
                   5439:       /* For each age */
                   5440:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5441:        fprintf(ficresphtm,"<tr>");
                   5442:        if(iage==iagemax+1){
                   5443:          fprintf(ficlog,"1");
                   5444:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5445:        }else if(iage==iagemax+2){
                   5446:          fprintf(ficlog,"0");
                   5447:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5448:        }else if(iage==iagemax+3){
                   5449:          fprintf(ficlog,"Total");
                   5450:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5451:        }else{
1.240     brouard  5452:          if(first==1){
1.251     brouard  5453:            first=0;
                   5454:            printf("See log file for details...\n");
                   5455:          }
                   5456:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5457:          fprintf(ficlog,"Age %d", iage);
                   5458:        }
1.265     brouard  5459:        for(s1=1; s1 <=nlstate ; s1++){
                   5460:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5461:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5462:        }
1.265     brouard  5463:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5464:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5465:            pos += freq[s1][m][iage];
                   5466:          if(pp[s1]>=1.e-10){
1.251     brouard  5467:            if(first==1){
1.265     brouard  5468:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5469:            }
1.265     brouard  5470:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5471:          }else{
                   5472:            if(first==1)
1.265     brouard  5473:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5474:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5475:          }
                   5476:        }
                   5477:       
1.265     brouard  5478:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5479:          /* posprop[s1]=0; */
                   5480:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5481:            pp[s1] += freq[s1][m][iage];
                   5482:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5483:       
                   5484:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5485:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5486:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5487:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5488:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5489:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5490:        }
                   5491:        
                   5492:        /* Writing ficresp */
1.335     brouard  5493:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5494:           if( iage <= iagemax){
                   5495:            fprintf(ficresp," %d",iage);
                   5496:           }
                   5497:         }else if( nj==2){
                   5498:           if( iage <= iagemax){
                   5499:            fprintf(ficresp," %d",iage);
1.335     brouard  5500:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  5501:           }
1.240     brouard  5502:        }
1.265     brouard  5503:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5504:          if(pos>=1.e-5){
1.251     brouard  5505:            if(first==1)
1.265     brouard  5506:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5507:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5508:          }else{
                   5509:            if(first==1)
1.265     brouard  5510:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5511:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5512:          }
                   5513:          if( iage <= iagemax){
                   5514:            if(pos>=1.e-5){
1.335     brouard  5515:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5516:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5517:               }else if( nj==2){
                   5518:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5519:               }
                   5520:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5521:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5522:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5523:            } else{
1.335     brouard  5524:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  5525:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5526:            }
1.240     brouard  5527:          }
1.265     brouard  5528:          pospropt[s1] +=posprop[s1];
                   5529:        } /* end loop s1 */
1.251     brouard  5530:        /* pospropt=0.; */
1.265     brouard  5531:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5532:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5533:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5534:              if(first==1){
1.265     brouard  5535:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5536:              }
1.265     brouard  5537:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5538:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5539:            }
1.265     brouard  5540:            if(s1!=0 && m!=0)
                   5541:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5542:          }
1.265     brouard  5543:        } /* end loop s1 */
1.251     brouard  5544:        posproptt=0.; 
1.265     brouard  5545:        for(s1=1; s1 <=nlstate; s1++){
                   5546:          posproptt += pospropt[s1];
1.251     brouard  5547:        }
                   5548:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5549:        fprintf(ficresphtm,"</tr>\n");
1.335     brouard  5550:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  5551:          if(iage <= iagemax)
                   5552:            fprintf(ficresp,"\n");
1.240     brouard  5553:        }
1.251     brouard  5554:        if(first==1)
                   5555:          printf("Others in log...\n");
                   5556:        fprintf(ficlog,"\n");
                   5557:       } /* end loop age iage */
1.265     brouard  5558:       
1.251     brouard  5559:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5560:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5561:        if(posproptt < 1.e-5){
1.265     brouard  5562:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5563:        }else{
1.265     brouard  5564:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5565:        }
1.226     brouard  5566:       }
1.251     brouard  5567:       fprintf(ficresphtm,"</tr>\n");
                   5568:       fprintf(ficresphtm,"</table>\n");
                   5569:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5570:       if(posproptt < 1.e-5){
1.251     brouard  5571:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5572:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5573:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5574:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5575:        invalidvarcomb[j1]=1;
1.226     brouard  5576:       }else{
1.338     brouard  5577:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
1.251     brouard  5578:        invalidvarcomb[j1]=0;
1.226     brouard  5579:       }
1.251     brouard  5580:       fprintf(ficresphtmfr,"</table>\n");
                   5581:       fprintf(ficlog,"\n");
                   5582:       if(j!=0){
                   5583:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5584:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5585:          for(k=1; k <=(nlstate+ndeath); k++){
                   5586:            if (k != i) {
1.265     brouard  5587:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5588:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5589:                  if(j1==1){ /* All dummy covariates to zero */
                   5590:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5591:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5592:                    printf("%d%d ",i,k);
                   5593:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5594:                    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]));
                   5595:                    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]));
                   5596:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5597:                  }
1.253     brouard  5598:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5599:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5600:                    x[iage]= (double)iage;
                   5601:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5602:                    /* 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  5603:                  }
1.268     brouard  5604:                  /* Some are not finite, but linreg will ignore these ages */
                   5605:                  no=0;
1.253     brouard  5606:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5607:                  pstart[s1]=b;
                   5608:                  pstart[s1-1]=a;
1.252     brouard  5609:                }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 */ 
                   5610:                  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]);
                   5611:                  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  5612:                  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  5613:                  printf("%d%d ",i,k);
                   5614:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5615:                  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  5616:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5617:                  ;
                   5618:                }
                   5619:                /* printf("%12.7f )", param[i][jj][k]); */
                   5620:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5621:                s1++; 
1.251     brouard  5622:              } /* end jj */
                   5623:            } /* end k!= i */
                   5624:          } /* end k */
1.265     brouard  5625:        } /* end i, s1 */
1.251     brouard  5626:       } /* end j !=0 */
                   5627:     } /* end selected combination of covariate j1 */
                   5628:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5629:       printf("#Freqsummary: Starting values for the constants:\n");
                   5630:       fprintf(ficlog,"\n");
1.265     brouard  5631:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5632:        for(k=1; k <=(nlstate+ndeath); k++){
                   5633:          if (k != i) {
                   5634:            printf("%d%d ",i,k);
                   5635:            fprintf(ficlog,"%d%d ",i,k);
                   5636:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5637:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5638:              if(jj==1){ /* Age has to be done */
1.265     brouard  5639:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5640:                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]));
                   5641:                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  5642:              }
                   5643:              /* printf("%12.7f )", param[i][jj][k]); */
                   5644:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5645:              s1++; 
1.250     brouard  5646:            }
1.251     brouard  5647:            printf("\n");
                   5648:            fprintf(ficlog,"\n");
1.250     brouard  5649:          }
                   5650:        }
1.284     brouard  5651:       } /* end of state i */
1.251     brouard  5652:       printf("#Freqsummary\n");
                   5653:       fprintf(ficlog,"\n");
1.265     brouard  5654:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   5655:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   5656:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   5657:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5658:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5659:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   5660:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   5661:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  5662:          /* } */
                   5663:        }
1.265     brouard  5664:       } /* end loop s1 */
1.251     brouard  5665:       
                   5666:       printf("\n");
                   5667:       fprintf(ficlog,"\n");
                   5668:     } /* end j=0 */
1.249     brouard  5669:   } /* end j */
1.252     brouard  5670: 
1.253     brouard  5671:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  5672:     for(i=1, jk=1; i <=nlstate; i++){
                   5673:       for(j=1; j <=nlstate+ndeath; j++){
                   5674:        if(j!=i){
                   5675:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5676:          printf("%1d%1d",i,j);
                   5677:          fprintf(ficparo,"%1d%1d",i,j);
                   5678:          for(k=1; k<=ncovmodel;k++){
                   5679:            /*    printf(" %lf",param[i][j][k]); */
                   5680:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5681:            p[jk]=pstart[jk];
                   5682:            printf(" %f ",pstart[jk]);
                   5683:            fprintf(ficparo," %f ",pstart[jk]);
                   5684:            jk++;
                   5685:          }
                   5686:          printf("\n");
                   5687:          fprintf(ficparo,"\n");
                   5688:        }
                   5689:       }
                   5690:     }
                   5691:   } /* end mle=-2 */
1.226     brouard  5692:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5693:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5694:   
1.226     brouard  5695:   fclose(ficresp);
                   5696:   fclose(ficresphtm);
                   5697:   fclose(ficresphtmfr);
1.283     brouard  5698:   free_vector(idq,1,nqfveff);
1.226     brouard  5699:   free_vector(meanq,1,nqfveff);
1.284     brouard  5700:   free_vector(stdq,1,nqfveff);
1.226     brouard  5701:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5702:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5703:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5704:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5705:   free_vector(pospropt,1,nlstate);
                   5706:   free_vector(posprop,1,nlstate);
1.251     brouard  5707:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5708:   free_vector(pp,1,nlstate);
                   5709:   /* End of freqsummary */
                   5710: }
1.126     brouard  5711: 
1.268     brouard  5712: /* Simple linear regression */
                   5713: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5714: 
                   5715:   /* y=a+bx regression */
                   5716:   double   sumx = 0.0;                        /* sum of x                      */
                   5717:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5718:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5719:   double   sumy = 0.0;                        /* sum of y                      */
                   5720:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5721:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5722:   double yhat;
                   5723:   
                   5724:   double denom=0;
                   5725:   int i;
                   5726:   int ne=*no;
                   5727:   
                   5728:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5729:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5730:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5731:       continue;
                   5732:     }
                   5733:     ne=ne+1;
                   5734:     sumx  += x[i];       
                   5735:     sumx2 += x[i]*x[i];  
                   5736:     sumxy += x[i] * y[i];
                   5737:     sumy  += y[i];      
                   5738:     sumy2 += y[i]*y[i]; 
                   5739:     denom = (ne * sumx2 - sumx*sumx);
                   5740:     /* 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); */
                   5741:   } 
                   5742:   
                   5743:   denom = (ne * sumx2 - sumx*sumx);
                   5744:   if (denom == 0) {
                   5745:     // vertical, slope m is infinity
                   5746:     *b = INFINITY;
                   5747:     *a = 0;
                   5748:     if (r) *r = 0;
                   5749:     return 1;
                   5750:   }
                   5751:   
                   5752:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5753:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5754:   if (r!=NULL) {
                   5755:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5756:       sqrt((sumx2 - sumx*sumx/ne) *
                   5757:           (sumy2 - sumy*sumy/ne));
                   5758:   }
                   5759:   *no=ne;
                   5760:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5761:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5762:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5763:       continue;
                   5764:     }
                   5765:     ne=ne+1;
                   5766:     yhat = y[i] - *a -*b* x[i];
                   5767:     sume2  += yhat * yhat ;       
                   5768:     
                   5769:     denom = (ne * sumx2 - sumx*sumx);
                   5770:     /* 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); */
                   5771:   } 
                   5772:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5773:   *sa= *sb * sqrt(sumx2/ne);
                   5774:   
                   5775:   return 0; 
                   5776: }
                   5777: 
1.126     brouard  5778: /************ Prevalence ********************/
1.227     brouard  5779: 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)
                   5780: {  
                   5781:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5782:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5783:      We still use firstpass and lastpass as another selection.
                   5784:   */
1.126     brouard  5785:  
1.227     brouard  5786:   int i, m, jk, j1, bool, z1,j, iv;
                   5787:   int mi; /* Effective wave */
                   5788:   int iage;
                   5789:   double agebegin, ageend;
                   5790: 
                   5791:   double **prop;
                   5792:   double posprop; 
                   5793:   double  y2; /* in fractional years */
                   5794:   int iagemin, iagemax;
                   5795:   int first; /** to stop verbosity which is redirected to log file */
                   5796: 
                   5797:   iagemin= (int) agemin;
                   5798:   iagemax= (int) agemax;
                   5799:   /*pp=vector(1,nlstate);*/
1.251     brouard  5800:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5801:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5802:   j1=0;
1.222     brouard  5803:   
1.227     brouard  5804:   /*j=cptcoveff;*/
                   5805:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5806:   
1.288     brouard  5807:   first=0;
1.335     brouard  5808:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  5809:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5810:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5811:        prop[i][iage]=0.0;
                   5812:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5813:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5814:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5815:     
                   5816:     for (i=1; i<=imx; i++) { /* Each individual */
                   5817:       bool=1;
                   5818:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5819:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5820:        m=mw[mi][i];
                   5821:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5822:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5823:        for (z1=1; z1<=cptcoveff; z1++){
                   5824:          if( Fixed[Tmodelind[z1]]==1){
1.341   ! brouard  5825:            iv= Tvar[Tmodelind[z1]];/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.332     brouard  5826:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  5827:              bool=0;
                   5828:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  5829:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  5830:              bool=0;
                   5831:            }
                   5832:        }
                   5833:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5834:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5835:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5836:          if(m >=firstpass && m <=lastpass){
                   5837:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5838:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5839:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5840:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5841:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5842:                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); 
                   5843:                exit(1);
                   5844:              }
                   5845:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5846:                /*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]]);*/
                   5847:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5848:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5849:              } /* end valid statuses */ 
                   5850:            } /* end selection of dates */
                   5851:          } /* end selection of waves */
                   5852:        } /* end bool */
                   5853:       } /* end wave */
                   5854:     } /* end individual */
                   5855:     for(i=iagemin; i <= iagemax+3; i++){  
                   5856:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   5857:        posprop += prop[jk][i]; 
                   5858:       } 
                   5859:       
                   5860:       for(jk=1; jk <=nlstate ; jk++){      
                   5861:        if( i <=  iagemax){ 
                   5862:          if(posprop>=1.e-5){ 
                   5863:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   5864:          } else{
1.288     brouard  5865:            if(!first){
                   5866:              first=1;
1.266     brouard  5867:              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]);
                   5868:            }else{
1.288     brouard  5869:              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  5870:            }
                   5871:          }
                   5872:        } 
                   5873:       }/* end jk */ 
                   5874:     }/* end i */ 
1.222     brouard  5875:      /*} *//* end i1 */
1.227     brouard  5876:   } /* end j1 */
1.222     brouard  5877:   
1.227     brouard  5878:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   5879:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  5880:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  5881: }  /* End of prevalence */
1.126     brouard  5882: 
                   5883: /************* Waves Concatenation ***************/
                   5884: 
                   5885: 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)
                   5886: {
1.298     brouard  5887:   /* 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  5888:      Death is a valid wave (if date is known).
                   5889:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   5890:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  5891:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  5892:   */
1.126     brouard  5893: 
1.224     brouard  5894:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  5895:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   5896:      double sum=0., jmean=0.;*/
1.224     brouard  5897:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  5898:   int j, k=0,jk, ju, jl;
                   5899:   double sum=0.;
                   5900:   first=0;
1.214     brouard  5901:   firstwo=0;
1.217     brouard  5902:   firsthree=0;
1.218     brouard  5903:   firstfour=0;
1.164     brouard  5904:   jmin=100000;
1.126     brouard  5905:   jmax=-1;
                   5906:   jmean=0.;
1.224     brouard  5907: 
                   5908: /* Treating live states */
1.214     brouard  5909:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  5910:     mi=0;  /* First valid wave */
1.227     brouard  5911:     mli=0; /* Last valid wave */
1.309     brouard  5912:     m=firstpass;  /* Loop on waves */
                   5913:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  5914:       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 */
                   5915:        mli=m-1;/* mw[++mi][i]=m-1; */
                   5916:       }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  5917:        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  5918:        mli=m;
1.224     brouard  5919:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   5920:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  5921:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  5922:       }
1.309     brouard  5923:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  5924: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  5925:        break;
1.224     brouard  5926: #else
1.317     brouard  5927:        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  5928:          if(firsthree == 0){
1.302     brouard  5929:            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  5930:            firsthree=1;
1.317     brouard  5931:          }else if(firsthree >=1 && firsthree < 10){
                   5932:            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);
                   5933:            firsthree++;
                   5934:          }else if(firsthree == 10){
                   5935:            printf("Information, too many Information flags: no more reported to log either\n");
                   5936:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   5937:            firsthree++;
                   5938:          }else{
                   5939:            firsthree++;
1.227     brouard  5940:          }
1.309     brouard  5941:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  5942:          mli=m;
                   5943:        }
                   5944:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   5945:          nbwarn++;
1.309     brouard  5946:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  5947:            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);
                   5948:            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);
                   5949:          }
                   5950:          break;
                   5951:        }
                   5952:        break;
1.224     brouard  5953: #endif
1.227     brouard  5954:       }/* End m >= lastpass */
1.126     brouard  5955:     }/* end while */
1.224     brouard  5956: 
1.227     brouard  5957:     /* 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  5958:     /* After last pass */
1.224     brouard  5959: /* Treating death states */
1.214     brouard  5960:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  5961:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   5962:       /* } */
1.126     brouard  5963:       mi++;    /* Death is another wave */
                   5964:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  5965:       /* Only death is a correct wave */
1.126     brouard  5966:       mw[mi][i]=m;
1.257     brouard  5967:     } /* else not in a death state */
1.224     brouard  5968: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  5969:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  5970:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  5971:        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  5972:          nbwarn++;
                   5973:          if(firstfiv==0){
1.309     brouard  5974:            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  5975:            firstfiv=1;
                   5976:          }else{
1.309     brouard  5977:            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  5978:          }
1.309     brouard  5979:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   5980:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  5981:          nberr++;
                   5982:          if(firstwo==0){
1.309     brouard  5983:            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  5984:            firstwo=1;
                   5985:          }
1.309     brouard  5986:          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  5987:        }
1.257     brouard  5988:       }else{ /* if date of interview is unknown */
1.227     brouard  5989:        /* death is known but not confirmed by death status at any wave */
                   5990:        if(firstfour==0){
1.309     brouard  5991:          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  5992:          firstfour=1;
                   5993:        }
1.309     brouard  5994:        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  5995:       }
1.224     brouard  5996:     } /* end if date of death is known */
                   5997: #endif
1.309     brouard  5998:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   5999:     /* wav[i]=mw[mi][i];   */
1.126     brouard  6000:     if(mi==0){
                   6001:       nbwarn++;
                   6002:       if(first==0){
1.227     brouard  6003:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   6004:        first=1;
1.126     brouard  6005:       }
                   6006:       if(first==1){
1.227     brouard  6007:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  6008:       }
                   6009:     } /* end mi==0 */
                   6010:   } /* End individuals */
1.214     brouard  6011:   /* wav and mw are no more changed */
1.223     brouard  6012:        
1.317     brouard  6013:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6014:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6015: 
                   6016: 
1.126     brouard  6017:   for(i=1; i<=imx; i++){
                   6018:     for(mi=1; mi<wav[i];mi++){
                   6019:       if (stepm <=0)
1.227     brouard  6020:        dh[mi][i]=1;
1.126     brouard  6021:       else{
1.260     brouard  6022:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  6023:          if (agedc[i] < 2*AGESUP) {
                   6024:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   6025:            if(j==0) j=1;  /* Survives at least one month after exam */
                   6026:            else if(j<0){
                   6027:              nberr++;
                   6028:              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]);
                   6029:              j=1; /* Temporary Dangerous patch */
                   6030:              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);
                   6031:              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]);
                   6032:              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);
                   6033:            }
                   6034:            k=k+1;
                   6035:            if (j >= jmax){
                   6036:              jmax=j;
                   6037:              ijmax=i;
                   6038:            }
                   6039:            if (j <= jmin){
                   6040:              jmin=j;
                   6041:              ijmin=i;
                   6042:            }
                   6043:            sum=sum+j;
                   6044:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   6045:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   6046:          }
                   6047:        }
                   6048:        else{
                   6049:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  6050: /*       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  6051:                                        
1.227     brouard  6052:          k=k+1;
                   6053:          if (j >= jmax) {
                   6054:            jmax=j;
                   6055:            ijmax=i;
                   6056:          }
                   6057:          else if (j <= jmin){
                   6058:            jmin=j;
                   6059:            ijmin=i;
                   6060:          }
                   6061:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   6062:          /*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]);*/
                   6063:          if(j<0){
                   6064:            nberr++;
                   6065:            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]);
                   6066:            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]);
                   6067:          }
                   6068:          sum=sum+j;
                   6069:        }
                   6070:        jk= j/stepm;
                   6071:        jl= j -jk*stepm;
                   6072:        ju= j -(jk+1)*stepm;
                   6073:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   6074:          if(jl==0){
                   6075:            dh[mi][i]=jk;
                   6076:            bh[mi][i]=0;
                   6077:          }else{ /* We want a negative bias in order to only have interpolation ie
                   6078:                  * to avoid the price of an extra matrix product in likelihood */
                   6079:            dh[mi][i]=jk+1;
                   6080:            bh[mi][i]=ju;
                   6081:          }
                   6082:        }else{
                   6083:          if(jl <= -ju){
                   6084:            dh[mi][i]=jk;
                   6085:            bh[mi][i]=jl;       /* bias is positive if real duration
                   6086:                                 * is higher than the multiple of stepm and negative otherwise.
                   6087:                                 */
                   6088:          }
                   6089:          else{
                   6090:            dh[mi][i]=jk+1;
                   6091:            bh[mi][i]=ju;
                   6092:          }
                   6093:          if(dh[mi][i]==0){
                   6094:            dh[mi][i]=1; /* At least one step */
                   6095:            bh[mi][i]=ju; /* At least one step */
                   6096:            /*  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);*/
                   6097:          }
                   6098:        } /* end if mle */
1.126     brouard  6099:       }
                   6100:     } /* end wave */
                   6101:   }
                   6102:   jmean=sum/k;
                   6103:   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  6104:   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  6105: }
1.126     brouard  6106: 
                   6107: /*********** Tricode ****************************/
1.220     brouard  6108:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  6109:  {
                   6110:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   6111:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   6112:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   6113:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   6114:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   6115:     */
1.130     brouard  6116: 
1.242     brouard  6117:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   6118:    int modmaxcovj=0; /* Modality max of covariates j */
                   6119:    int cptcode=0; /* Modality max of covariates j */
                   6120:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  6121: 
                   6122: 
1.242     brouard  6123:    /* cptcoveff=0;  */
                   6124:    /* *cptcov=0; */
1.126     brouard  6125:  
1.242     brouard  6126:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  6127:    for (k=1; k <= maxncov; k++)
                   6128:      for(j=1; j<=2; j++)
                   6129:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  6130: 
1.242     brouard  6131:    /* Loop on covariates without age and products and no quantitative variable */
1.335     brouard  6132:    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  6133:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
1.339     brouard  6134:      printf("Testing k=%d, cptcovt=%d\n",k, cptcovt);
                   6135:      if(Dummy[k]==0 && Typevar[k] !=1 && Typevar[k] != 2){ /* Dummy covariate and not age product nor fixed product */ 
1.242     brouard  6136:        switch(Fixed[k]) {
                   6137:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  6138:         modmaxcovj=0;
                   6139:         modmincovj=0;
1.242     brouard  6140:         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  6141:           /* 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  6142:           ij=(int)(covar[Tvar[k]][i]);
                   6143:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   6144:            * If product of Vn*Vm, still boolean *:
                   6145:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   6146:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   6147:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   6148:              modality of the nth covariate of individual i. */
                   6149:           if (ij > modmaxcovj)
                   6150:             modmaxcovj=ij; 
                   6151:           else if (ij < modmincovj) 
                   6152:             modmincovj=ij; 
1.287     brouard  6153:           if (ij <0 || ij >1 ){
1.311     brouard  6154:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6155:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6156:             fflush(ficlog);
                   6157:             exit(1);
1.287     brouard  6158:           }
                   6159:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  6160:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   6161:             exit(1);
                   6162:           }else
                   6163:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   6164:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   6165:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   6166:           /* getting the maximum value of the modality of the covariate
                   6167:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   6168:              female ies 1, then modmaxcovj=1.
                   6169:           */
                   6170:         } /* end for loop on individuals i */
                   6171:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6172:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6173:         cptcode=modmaxcovj;
                   6174:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   6175:         /*for (i=0; i<=cptcode; i++) {*/
                   6176:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   6177:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6178:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6179:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   6180:             if( j != -1){
                   6181:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   6182:                                  covariate for which somebody answered excluding 
                   6183:                                  undefined. Usually 2: 0 and 1. */
                   6184:             }
                   6185:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   6186:                                     covariate for which somebody answered including 
                   6187:                                     undefined. Usually 3: -1, 0 and 1. */
                   6188:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   6189:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   6190:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  6191:                        
1.242     brouard  6192:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   6193:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   6194:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   6195:         /* modmincovj=3; modmaxcovj = 7; */
                   6196:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   6197:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   6198:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   6199:         /* nbcode[Tvar[j]][ij]=k; */
                   6200:         /* nbcode[Tvar[j]][1]=0; */
                   6201:         /* nbcode[Tvar[j]][2]=1; */
                   6202:         /* nbcode[Tvar[j]][3]=2; */
                   6203:         /* To be continued (not working yet). */
                   6204:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  6205: 
                   6206:         /* 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*/
                   6207:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   6208:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   6209:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   6210:         /*, could be restored in the future */
                   6211:         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  6212:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   6213:             break;
                   6214:           }
                   6215:           ij++;
1.287     brouard  6216:           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  6217:           cptcode = ij; /* New max modality for covar j */
                   6218:         } /* end of loop on modality i=-1 to 1 or more */
                   6219:         break;
                   6220:        case 1: /* Testing on varying covariate, could be simple and
                   6221:                * should look at waves or product of fixed *
                   6222:                * varying. No time to test -1, assuming 0 and 1 only */
                   6223:         ij=0;
                   6224:         for(i=0; i<=1;i++){
                   6225:           nbcode[Tvar[k]][++ij]=i;
                   6226:         }
                   6227:         break;
                   6228:        default:
                   6229:         break;
                   6230:        } /* end switch */
                   6231:      } /* end dummy test */
1.334     brouard  6232:      if(Dummy[k]==1 && Typevar[k] !=1){ /* Quantitative covariate and not age product */ 
1.311     brouard  6233:        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  6234:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   6235:           printf("Error k=%d \n",k);
                   6236:           exit(1);
                   6237:         }
1.311     brouard  6238:         if(isnan(covar[Tvar[k]][i])){
                   6239:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6240:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6241:           fflush(ficlog);
                   6242:           exit(1);
                   6243:          }
                   6244:        }
1.335     brouard  6245:      } /* end Quanti */
1.287     brouard  6246:    } /* 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  6247:   
                   6248:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   6249:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   6250:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   6251:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   6252:      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 */ 
                   6253:      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 */
                   6254:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   6255:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   6256:   
                   6257:    ij=0;
                   6258:    /* 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  6259:    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 */
                   6260:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  6261:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6262:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335     brouard  6263:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   6264:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   6265:        /* 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  6266:        /* If product not in single variable we don't print results */
                   6267:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335     brouard  6268:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   6269:        /* k=       1    2   3     4       5       6      7       8        9  */
                   6270:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   6271:        /* ij            1    2                                            3  */  
                   6272:        /* Tvaraff[ij]=  4    3                                            1  */
                   6273:        /* Tmodelind[ij]=2    3                                            9  */
                   6274:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  6275:        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*/
                   6276:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   6277:        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 */
                   6278:        if(Fixed[k]!=0)
                   6279:         anyvaryingduminmodel=1;
                   6280:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   6281:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6282:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   6283:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   6284:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   6285:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6286:      } 
                   6287:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   6288:    /* ij--; */
                   6289:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335     brouard  6290:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  6291:                * because they can be excluded from the model and real
                   6292:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   6293:    for(j=ij+1; j<= cptcovt; j++){
                   6294:      Tvaraff[j]=0;
                   6295:      Tmodelind[j]=0;
                   6296:    }
                   6297:    for(j=ntveff+1; j<= cptcovt; j++){
                   6298:      TmodelInvind[j]=0;
                   6299:    }
                   6300:    /* To be sorted */
                   6301:    ;
                   6302:  }
1.126     brouard  6303: 
1.145     brouard  6304: 
1.126     brouard  6305: /*********** Health Expectancies ****************/
                   6306: 
1.235     brouard  6307:  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  6308: 
                   6309: {
                   6310:   /* Health expectancies, no variances */
1.329     brouard  6311:   /* cij is the combination in the list of combination of dummy covariates */
                   6312:   /* strstart is a string of time at start of computing */
1.164     brouard  6313:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  6314:   int nhstepma, nstepma; /* Decreasing with age */
                   6315:   double age, agelim, hf;
                   6316:   double ***p3mat;
                   6317:   double eip;
                   6318: 
1.238     brouard  6319:   /* pstamp(ficreseij); */
1.126     brouard  6320:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   6321:   fprintf(ficreseij,"# Age");
                   6322:   for(i=1; i<=nlstate;i++){
                   6323:     for(j=1; j<=nlstate;j++){
                   6324:       fprintf(ficreseij," e%1d%1d ",i,j);
                   6325:     }
                   6326:     fprintf(ficreseij," e%1d. ",i);
                   6327:   }
                   6328:   fprintf(ficreseij,"\n");
                   6329: 
                   6330:   
                   6331:   if(estepm < stepm){
                   6332:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6333:   }
                   6334:   else  hstepm=estepm;   
                   6335:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6336:    * This is mainly to measure the difference between two models: for example
                   6337:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6338:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6339:    * progression in between and thus overestimating or underestimating according
                   6340:    * to the curvature of the survival function. If, for the same date, we 
                   6341:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6342:    * to compare the new estimate of Life expectancy with the same linear 
                   6343:    * hypothesis. A more precise result, taking into account a more precise
                   6344:    * curvature will be obtained if estepm is as small as stepm. */
                   6345: 
                   6346:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6347:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6348:      nhstepm is the number of hstepm from age to agelim 
                   6349:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  6350:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  6351:      and note for a fixed period like estepm months */
                   6352:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6353:      survival function given by stepm (the optimization length). Unfortunately it
                   6354:      means that if the survival funtion is printed only each two years of age and if
                   6355:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6356:      results. So we changed our mind and took the option of the best precision.
                   6357:   */
                   6358:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6359: 
                   6360:   agelim=AGESUP;
                   6361:   /* If stepm=6 months */
                   6362:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6363:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6364:     
                   6365: /* nhstepm age range expressed in number of stepm */
                   6366:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6367:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6368:   /* if (stepm >= YEARM) hstepm=1;*/
                   6369:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6370:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6371: 
                   6372:   for (age=bage; age<=fage; age ++){ 
                   6373:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6374:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6375:     /* if (stepm >= YEARM) hstepm=1;*/
                   6376:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   6377: 
                   6378:     /* If stepm=6 months */
                   6379:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6380:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  6381:     /* 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  6382:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  6383:     
                   6384:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6385:     
                   6386:     printf("%d|",(int)age);fflush(stdout);
                   6387:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6388:     
                   6389:     /* Computing expectancies */
                   6390:     for(i=1; i<=nlstate;i++)
                   6391:       for(j=1; j<=nlstate;j++)
                   6392:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6393:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   6394:          
                   6395:          /* 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]);*/
                   6396: 
                   6397:        }
                   6398: 
                   6399:     fprintf(ficreseij,"%3.0f",age );
                   6400:     for(i=1; i<=nlstate;i++){
                   6401:       eip=0;
                   6402:       for(j=1; j<=nlstate;j++){
                   6403:        eip +=eij[i][j][(int)age];
                   6404:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   6405:       }
                   6406:       fprintf(ficreseij,"%9.4f", eip );
                   6407:     }
                   6408:     fprintf(ficreseij,"\n");
                   6409:     
                   6410:   }
                   6411:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6412:   printf("\n");
                   6413:   fprintf(ficlog,"\n");
                   6414:   
                   6415: }
                   6416: 
1.235     brouard  6417:  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  6418: 
                   6419: {
                   6420:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6421:      to initial status i, ei. .
1.126     brouard  6422:   */
1.336     brouard  6423:   /* Very time consuming function, but already optimized with precov */
1.126     brouard  6424:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6425:   int nhstepma, nstepma; /* Decreasing with age */
                   6426:   double age, agelim, hf;
                   6427:   double ***p3matp, ***p3matm, ***varhe;
                   6428:   double **dnewm,**doldm;
                   6429:   double *xp, *xm;
                   6430:   double **gp, **gm;
                   6431:   double ***gradg, ***trgradg;
                   6432:   int theta;
                   6433: 
                   6434:   double eip, vip;
                   6435: 
                   6436:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6437:   xp=vector(1,npar);
                   6438:   xm=vector(1,npar);
                   6439:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6440:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6441:   
                   6442:   pstamp(ficresstdeij);
                   6443:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6444:   fprintf(ficresstdeij,"# Age");
                   6445:   for(i=1; i<=nlstate;i++){
                   6446:     for(j=1; j<=nlstate;j++)
                   6447:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6448:     fprintf(ficresstdeij," e%1d. ",i);
                   6449:   }
                   6450:   fprintf(ficresstdeij,"\n");
                   6451: 
                   6452:   pstamp(ficrescveij);
                   6453:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6454:   fprintf(ficrescveij,"# Age");
                   6455:   for(i=1; i<=nlstate;i++)
                   6456:     for(j=1; j<=nlstate;j++){
                   6457:       cptj= (j-1)*nlstate+i;
                   6458:       for(i2=1; i2<=nlstate;i2++)
                   6459:        for(j2=1; j2<=nlstate;j2++){
                   6460:          cptj2= (j2-1)*nlstate+i2;
                   6461:          if(cptj2 <= cptj)
                   6462:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6463:        }
                   6464:     }
                   6465:   fprintf(ficrescveij,"\n");
                   6466:   
                   6467:   if(estepm < stepm){
                   6468:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6469:   }
                   6470:   else  hstepm=estepm;   
                   6471:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6472:    * This is mainly to measure the difference between two models: for example
                   6473:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6474:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6475:    * progression in between and thus overestimating or underestimating according
                   6476:    * to the curvature of the survival function. If, for the same date, we 
                   6477:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6478:    * to compare the new estimate of Life expectancy with the same linear 
                   6479:    * hypothesis. A more precise result, taking into account a more precise
                   6480:    * curvature will be obtained if estepm is as small as stepm. */
                   6481: 
                   6482:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6483:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6484:      nhstepm is the number of hstepm from age to agelim 
                   6485:      nstepm is the number of stepm from age to agelin. 
                   6486:      Look at hpijx to understand the reason of that which relies in memory size
                   6487:      and note for a fixed period like estepm months */
                   6488:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6489:      survival function given by stepm (the optimization length). Unfortunately it
                   6490:      means that if the survival funtion is printed only each two years of age and if
                   6491:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6492:      results. So we changed our mind and took the option of the best precision.
                   6493:   */
                   6494:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6495: 
                   6496:   /* If stepm=6 months */
                   6497:   /* nhstepm age range expressed in number of stepm */
                   6498:   agelim=AGESUP;
                   6499:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6500:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6501:   /* if (stepm >= YEARM) hstepm=1;*/
                   6502:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6503:   
                   6504:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6505:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6506:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6507:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6508:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6509:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6510: 
                   6511:   for (age=bage; age<=fage; age ++){ 
                   6512:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6513:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6514:     /* if (stepm >= YEARM) hstepm=1;*/
                   6515:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6516:                
1.126     brouard  6517:     /* If stepm=6 months */
                   6518:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6519:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6520:     
                   6521:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6522:                
1.126     brouard  6523:     /* Computing  Variances of health expectancies */
                   6524:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6525:        decrease memory allocation */
                   6526:     for(theta=1; theta <=npar; theta++){
                   6527:       for(i=1; i<=npar; i++){ 
1.222     brouard  6528:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6529:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6530:       }
1.235     brouard  6531:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6532:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6533:                        
1.126     brouard  6534:       for(j=1; j<= nlstate; j++){
1.222     brouard  6535:        for(i=1; i<=nlstate; i++){
                   6536:          for(h=0; h<=nhstepm-1; h++){
                   6537:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6538:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6539:          }
                   6540:        }
1.126     brouard  6541:       }
1.218     brouard  6542:                        
1.126     brouard  6543:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6544:        for(h=0; h<=nhstepm-1; h++){
                   6545:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6546:        }
1.126     brouard  6547:     }/* End theta */
                   6548:     
                   6549:     
                   6550:     for(h=0; h<=nhstepm-1; h++)
                   6551:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6552:        for(theta=1; theta <=npar; theta++)
                   6553:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6554:     
1.218     brouard  6555:                
1.222     brouard  6556:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6557:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6558:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6559:                
1.222     brouard  6560:     printf("%d|",(int)age);fflush(stdout);
                   6561:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6562:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6563:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6564:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6565:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6566:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6567:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6568:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6569:       }
                   6570:     }
1.320     brouard  6571:     /* if((int)age ==50){ */
                   6572:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6573:     /* } */
1.126     brouard  6574:     /* Computing expectancies */
1.235     brouard  6575:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6576:     for(i=1; i<=nlstate;i++)
                   6577:       for(j=1; j<=nlstate;j++)
1.222     brouard  6578:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6579:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6580:                                        
1.222     brouard  6581:          /* 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  6582:                                        
1.222     brouard  6583:        }
1.269     brouard  6584: 
                   6585:     /* Standard deviation of expectancies ij */                
1.126     brouard  6586:     fprintf(ficresstdeij,"%3.0f",age );
                   6587:     for(i=1; i<=nlstate;i++){
                   6588:       eip=0.;
                   6589:       vip=0.;
                   6590:       for(j=1; j<=nlstate;j++){
1.222     brouard  6591:        eip += eij[i][j][(int)age];
                   6592:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6593:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6594:        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  6595:       }
                   6596:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6597:     }
                   6598:     fprintf(ficresstdeij,"\n");
1.218     brouard  6599:                
1.269     brouard  6600:     /* Variance of expectancies ij */          
1.126     brouard  6601:     fprintf(ficrescveij,"%3.0f",age );
                   6602:     for(i=1; i<=nlstate;i++)
                   6603:       for(j=1; j<=nlstate;j++){
1.222     brouard  6604:        cptj= (j-1)*nlstate+i;
                   6605:        for(i2=1; i2<=nlstate;i2++)
                   6606:          for(j2=1; j2<=nlstate;j2++){
                   6607:            cptj2= (j2-1)*nlstate+i2;
                   6608:            if(cptj2 <= cptj)
                   6609:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6610:          }
1.126     brouard  6611:       }
                   6612:     fprintf(ficrescveij,"\n");
1.218     brouard  6613:                
1.126     brouard  6614:   }
                   6615:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6616:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6617:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6618:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6619:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6620:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6621:   printf("\n");
                   6622:   fprintf(ficlog,"\n");
1.218     brouard  6623:        
1.126     brouard  6624:   free_vector(xm,1,npar);
                   6625:   free_vector(xp,1,npar);
                   6626:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6627:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6628:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6629: }
1.218     brouard  6630:  
1.126     brouard  6631: /************ Variance ******************/
1.235     brouard  6632:  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  6633:  {
1.279     brouard  6634:    /** Variance of health expectancies 
                   6635:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6636:     * double **newm;
                   6637:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6638:     */
1.218     brouard  6639:   
                   6640:    /* int movingaverage(); */
                   6641:    double **dnewm,**doldm;
                   6642:    double **dnewmp,**doldmp;
                   6643:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6644:    int first=0;
1.218     brouard  6645:    int k;
                   6646:    double *xp;
1.279     brouard  6647:    double **gp, **gm;  /**< for var eij */
                   6648:    double ***gradg, ***trgradg; /**< for var eij */
                   6649:    double **gradgp, **trgradgp; /**< for var p point j */
                   6650:    double *gpp, *gmp; /**< for var p point j */
                   6651:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  6652:    double ***p3mat;
                   6653:    double age,agelim, hf;
                   6654:    /* double ***mobaverage; */
                   6655:    int theta;
                   6656:    char digit[4];
                   6657:    char digitp[25];
                   6658: 
                   6659:    char fileresprobmorprev[FILENAMELENGTH];
                   6660: 
                   6661:    if(popbased==1){
                   6662:      if(mobilav!=0)
                   6663:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   6664:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   6665:    }
                   6666:    else 
                   6667:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  6668: 
1.218     brouard  6669:    /* if (mobilav!=0) { */
                   6670:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6671:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   6672:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6673:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6674:    /*   } */
                   6675:    /* } */
                   6676: 
                   6677:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   6678:    sprintf(digit,"%-d",ij);
                   6679:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   6680:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   6681:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   6682:    strcat(fileresprobmorprev,fileresu);
                   6683:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   6684:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   6685:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   6686:    }
                   6687:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6688:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6689:    pstamp(ficresprobmorprev);
                   6690:    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  6691:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.337     brouard  6692: 
                   6693:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
                   6694:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
                   6695:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   6696:    /* } */
                   6697:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
                   6698:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  6699:    }
1.337     brouard  6700:    /* for(j=1;j<=cptcoveff;j++)  */
                   6701:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
1.238     brouard  6702:    fprintf(ficresprobmorprev,"\n");
                   6703: 
1.218     brouard  6704:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   6705:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6706:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   6707:      for(i=1; i<=nlstate;i++)
                   6708:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   6709:    }  
                   6710:    fprintf(ficresprobmorprev,"\n");
                   6711:   
                   6712:    fprintf(ficgp,"\n# Routine varevsij");
                   6713:    fprintf(ficgp,"\nunset title \n");
                   6714:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   6715:    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");
                   6716:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  6717: 
1.218     brouard  6718:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6719:    pstamp(ficresvij);
                   6720:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   6721:    if(popbased==1)
                   6722:      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);
                   6723:    else
                   6724:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   6725:    fprintf(ficresvij,"# Age");
                   6726:    for(i=1; i<=nlstate;i++)
                   6727:      for(j=1; j<=nlstate;j++)
                   6728:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6729:    fprintf(ficresvij,"\n");
                   6730: 
                   6731:    xp=vector(1,npar);
                   6732:    dnewm=matrix(1,nlstate,1,npar);
                   6733:    doldm=matrix(1,nlstate,1,nlstate);
                   6734:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6735:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6736: 
                   6737:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6738:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6739:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6740:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6741:   
1.218     brouard  6742:    if(estepm < stepm){
                   6743:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6744:    }
                   6745:    else  hstepm=estepm;   
                   6746:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6747:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6748:       nhstepm is the number of hstepm from age to agelim 
                   6749:       nstepm is the number of stepm from age to agelim. 
                   6750:       Look at function hpijx to understand why because of memory size limitations, 
                   6751:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6752:       survival function given by stepm (the optimization length). Unfortunately it
                   6753:       means that if the survival funtion is printed every two years of age and if
                   6754:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6755:       results. So we changed our mind and took the option of the best precision.
                   6756:    */
                   6757:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6758:    agelim = AGESUP;
                   6759:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6760:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6761:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6762:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6763:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6764:      gp=matrix(0,nhstepm,1,nlstate);
                   6765:      gm=matrix(0,nhstepm,1,nlstate);
                   6766:                
                   6767:                
                   6768:      for(theta=1; theta <=npar; theta++){
                   6769:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6770:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6771:        }
1.279     brouard  6772:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6773:        * returns into prlim .
1.288     brouard  6774:        */
1.242     brouard  6775:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6776: 
                   6777:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6778:        if (popbased==1) {
                   6779:         if(mobilav ==0){
                   6780:           for(i=1; i<=nlstate;i++)
                   6781:             prlim[i][i]=probs[(int)age][i][ij];
                   6782:         }else{ /* mobilav */ 
                   6783:           for(i=1; i<=nlstate;i++)
                   6784:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6785:         }
                   6786:        }
1.295     brouard  6787:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6788:        */                      
                   6789:        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  6790:        /**< 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  6791:        * at horizon h in state j including mortality.
                   6792:        */
1.218     brouard  6793:        for(j=1; j<= nlstate; j++){
                   6794:         for(h=0; h<=nhstepm; h++){
                   6795:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6796:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6797:         }
                   6798:        }
1.279     brouard  6799:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6800:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6801:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6802:        */
                   6803:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6804:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6805:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6806:        }
                   6807:        
                   6808:        /* Again with minus shift */
1.218     brouard  6809:                        
                   6810:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6811:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6812: 
1.242     brouard  6813:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6814:                        
                   6815:        if (popbased==1) {
                   6816:         if(mobilav ==0){
                   6817:           for(i=1; i<=nlstate;i++)
                   6818:             prlim[i][i]=probs[(int)age][i][ij];
                   6819:         }else{ /* mobilav */ 
                   6820:           for(i=1; i<=nlstate;i++)
                   6821:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6822:         }
                   6823:        }
                   6824:                        
1.235     brouard  6825:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6826:                        
                   6827:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6828:         for(h=0; h<=nhstepm; h++){
                   6829:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6830:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6831:         }
                   6832:        }
                   6833:        /* This for computing probability of death (h=1 means
                   6834:          computed over hstepm matrices product = hstepm*stepm months) 
                   6835:          as a weighted average of prlim.
                   6836:        */
                   6837:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6838:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6839:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6840:        }    
1.279     brouard  6841:        /* end shifting computations */
                   6842: 
                   6843:        /**< Computing gradient matrix at horizon h 
                   6844:        */
1.218     brouard  6845:        for(j=1; j<= nlstate; j++) /* vareij */
                   6846:         for(h=0; h<=nhstepm; h++){
                   6847:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6848:         }
1.279     brouard  6849:        /**< Gradient of overall mortality p.3 (or p.j) 
                   6850:        */
                   6851:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  6852:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   6853:        }
                   6854:                        
                   6855:      } /* End theta */
1.279     brouard  6856:      
                   6857:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  6858:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   6859:                
                   6860:      for(h=0; h<=nhstepm; h++) /* veij */
                   6861:        for(j=1; j<=nlstate;j++)
                   6862:         for(theta=1; theta <=npar; theta++)
                   6863:           trgradg[h][j][theta]=gradg[h][theta][j];
                   6864:                
                   6865:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   6866:        for(theta=1; theta <=npar; theta++)
                   6867:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  6868:      /**< as well as its transposed matrix 
                   6869:       */               
1.218     brouard  6870:                
                   6871:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6872:      for(i=1;i<=nlstate;i++)
                   6873:        for(j=1;j<=nlstate;j++)
                   6874:         vareij[i][j][(int)age] =0.;
1.279     brouard  6875: 
                   6876:      /* Computing trgradg by matcov by gradg at age and summing over h
                   6877:       * and k (nhstepm) formula 15 of article
                   6878:       * Lievre-Brouard-Heathcote
                   6879:       */
                   6880:      
1.218     brouard  6881:      for(h=0;h<=nhstepm;h++){
                   6882:        for(k=0;k<=nhstepm;k++){
                   6883:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   6884:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   6885:         for(i=1;i<=nlstate;i++)
                   6886:           for(j=1;j<=nlstate;j++)
                   6887:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   6888:        }
                   6889:      }
                   6890:                
1.279     brouard  6891:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   6892:       * p.j overall mortality formula 49 but computed directly because
                   6893:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   6894:       * wix is independent of theta.
                   6895:       */
1.218     brouard  6896:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   6897:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   6898:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   6899:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   6900:         varppt[j][i]=doldmp[j][i];
                   6901:      /* end ppptj */
                   6902:      /*  x centered again */
                   6903:                
1.242     brouard  6904:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  6905:                
                   6906:      if (popbased==1) {
                   6907:        if(mobilav ==0){
                   6908:         for(i=1; i<=nlstate;i++)
                   6909:           prlim[i][i]=probs[(int)age][i][ij];
                   6910:        }else{ /* mobilav */ 
                   6911:         for(i=1; i<=nlstate;i++)
                   6912:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   6913:        }
                   6914:      }
                   6915:                
                   6916:      /* This for computing probability of death (h=1 means
                   6917:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   6918:        as a weighted average of prlim.
                   6919:      */
1.235     brouard  6920:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  6921:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6922:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   6923:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   6924:      }    
                   6925:      /* end probability of death */
                   6926:                
                   6927:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   6928:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6929:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   6930:        for(i=1; i<=nlstate;i++){
                   6931:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   6932:        }
                   6933:      } 
                   6934:      fprintf(ficresprobmorprev,"\n");
                   6935:                
                   6936:      fprintf(ficresvij,"%.0f ",age );
                   6937:      for(i=1; i<=nlstate;i++)
                   6938:        for(j=1; j<=nlstate;j++){
                   6939:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   6940:        }
                   6941:      fprintf(ficresvij,"\n");
                   6942:      free_matrix(gp,0,nhstepm,1,nlstate);
                   6943:      free_matrix(gm,0,nhstepm,1,nlstate);
                   6944:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   6945:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   6946:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6947:    } /* End age */
                   6948:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   6949:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   6950:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   6951:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   6952:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   6953:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   6954:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   6955:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   6956:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   6957:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   6958:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6959:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6960:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   6961:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   6962:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   6963:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   6964:    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);
                   6965:    /*  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  6966:     */
1.218     brouard  6967:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   6968:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  6969: 
1.218     brouard  6970:    free_vector(xp,1,npar);
                   6971:    free_matrix(doldm,1,nlstate,1,nlstate);
                   6972:    free_matrix(dnewm,1,nlstate,1,npar);
                   6973:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6974:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   6975:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6976:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6977:    fclose(ficresprobmorprev);
                   6978:    fflush(ficgp);
                   6979:    fflush(fichtm); 
                   6980:  }  /* end varevsij */
1.126     brouard  6981: 
                   6982: /************ Variance of prevlim ******************/
1.269     brouard  6983:  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  6984: {
1.205     brouard  6985:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  6986:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  6987: 
1.268     brouard  6988:   double **dnewmpar,**doldm;
1.126     brouard  6989:   int i, j, nhstepm, hstepm;
                   6990:   double *xp;
                   6991:   double *gp, *gm;
                   6992:   double **gradg, **trgradg;
1.208     brouard  6993:   double **mgm, **mgp;
1.126     brouard  6994:   double age,agelim;
                   6995:   int theta;
                   6996:   
                   6997:   pstamp(ficresvpl);
1.288     brouard  6998:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  6999:   fprintf(ficresvpl,"# Age ");
                   7000:   if(nresult >=1)
                   7001:     fprintf(ficresvpl," Result# ");
1.126     brouard  7002:   for(i=1; i<=nlstate;i++)
                   7003:       fprintf(ficresvpl," %1d-%1d",i,i);
                   7004:   fprintf(ficresvpl,"\n");
                   7005: 
                   7006:   xp=vector(1,npar);
1.268     brouard  7007:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  7008:   doldm=matrix(1,nlstate,1,nlstate);
                   7009:   
                   7010:   hstepm=1*YEARM; /* Every year of age */
                   7011:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7012:   agelim = AGESUP;
                   7013:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7014:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7015:     if (stepm >= YEARM) hstepm=1;
                   7016:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7017:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  7018:     mgp=matrix(1,npar,1,nlstate);
                   7019:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  7020:     gp=vector(1,nlstate);
                   7021:     gm=vector(1,nlstate);
                   7022: 
                   7023:     for(theta=1; theta <=npar; theta++){
                   7024:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7025:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7026:       }
1.288     brouard  7027:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7028:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7029:       /* else */
                   7030:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7031:       for(i=1;i<=nlstate;i++){
1.126     brouard  7032:        gp[i] = prlim[i][i];
1.208     brouard  7033:        mgp[theta][i] = prlim[i][i];
                   7034:       }
1.126     brouard  7035:       for(i=1; i<=npar; i++) /* Computes gradient */
                   7036:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  7037:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7038:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7039:       /* else */
                   7040:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7041:       for(i=1;i<=nlstate;i++){
1.126     brouard  7042:        gm[i] = prlim[i][i];
1.208     brouard  7043:        mgm[theta][i] = prlim[i][i];
                   7044:       }
1.126     brouard  7045:       for(i=1;i<=nlstate;i++)
                   7046:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  7047:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  7048:     } /* End theta */
                   7049: 
                   7050:     trgradg =matrix(1,nlstate,1,npar);
                   7051: 
                   7052:     for(j=1; j<=nlstate;j++)
                   7053:       for(theta=1; theta <=npar; theta++)
                   7054:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  7055:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7056:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7057:     /*   for(j=1; j<=nlstate;j++){ */
                   7058:     /*         printf(" %d ",j); */
                   7059:     /*         for(theta=1; theta <=npar; theta++) */
                   7060:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7061:     /*         printf("\n "); */
                   7062:     /*   } */
                   7063:     /* } */
                   7064:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7065:     /*   printf("\n gradg %d ",(int)age); */
                   7066:     /*   for(j=1; j<=nlstate;j++){ */
                   7067:     /*         printf("%d ",j); */
                   7068:     /*         for(theta=1; theta <=npar; theta++) */
                   7069:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7070:     /*         printf("\n "); */
                   7071:     /*   } */
                   7072:     /* } */
1.126     brouard  7073: 
                   7074:     for(i=1;i<=nlstate;i++)
                   7075:       varpl[i][(int)age] =0.;
1.209     brouard  7076:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  7077:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7078:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7079:     }else{
1.268     brouard  7080:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7081:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7082:     }
1.126     brouard  7083:     for(i=1;i<=nlstate;i++)
                   7084:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7085: 
                   7086:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  7087:     if(nresult >=1)
                   7088:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  7089:     for(i=1; i<=nlstate;i++){
1.126     brouard  7090:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  7091:       /* for(j=1;j<=nlstate;j++) */
                   7092:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   7093:     }
1.126     brouard  7094:     fprintf(ficresvpl,"\n");
                   7095:     free_vector(gp,1,nlstate);
                   7096:     free_vector(gm,1,nlstate);
1.208     brouard  7097:     free_matrix(mgm,1,npar,1,nlstate);
                   7098:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  7099:     free_matrix(gradg,1,npar,1,nlstate);
                   7100:     free_matrix(trgradg,1,nlstate,1,npar);
                   7101:   } /* End age */
                   7102: 
                   7103:   free_vector(xp,1,npar);
                   7104:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  7105:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   7106: 
                   7107: }
                   7108: 
                   7109: 
                   7110: /************ Variance of backprevalence limit ******************/
1.269     brouard  7111:  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  7112: {
                   7113:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   7114:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   7115: 
                   7116:   double **dnewmpar,**doldm;
                   7117:   int i, j, nhstepm, hstepm;
                   7118:   double *xp;
                   7119:   double *gp, *gm;
                   7120:   double **gradg, **trgradg;
                   7121:   double **mgm, **mgp;
                   7122:   double age,agelim;
                   7123:   int theta;
                   7124:   
                   7125:   pstamp(ficresvbl);
                   7126:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   7127:   fprintf(ficresvbl,"# Age ");
                   7128:   if(nresult >=1)
                   7129:     fprintf(ficresvbl," Result# ");
                   7130:   for(i=1; i<=nlstate;i++)
                   7131:       fprintf(ficresvbl," %1d-%1d",i,i);
                   7132:   fprintf(ficresvbl,"\n");
                   7133: 
                   7134:   xp=vector(1,npar);
                   7135:   dnewmpar=matrix(1,nlstate,1,npar);
                   7136:   doldm=matrix(1,nlstate,1,nlstate);
                   7137:   
                   7138:   hstepm=1*YEARM; /* Every year of age */
                   7139:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7140:   agelim = AGEINF;
                   7141:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   7142:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7143:     if (stepm >= YEARM) hstepm=1;
                   7144:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7145:     gradg=matrix(1,npar,1,nlstate);
                   7146:     mgp=matrix(1,npar,1,nlstate);
                   7147:     mgm=matrix(1,npar,1,nlstate);
                   7148:     gp=vector(1,nlstate);
                   7149:     gm=vector(1,nlstate);
                   7150: 
                   7151:     for(theta=1; theta <=npar; theta++){
                   7152:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7153:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7154:       }
                   7155:       if(mobilavproj > 0 )
                   7156:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7157:       else
                   7158:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7159:       for(i=1;i<=nlstate;i++){
                   7160:        gp[i] = bprlim[i][i];
                   7161:        mgp[theta][i] = bprlim[i][i];
                   7162:       }
                   7163:      for(i=1; i<=npar; i++) /* Computes gradient */
                   7164:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   7165:        if(mobilavproj > 0 )
                   7166:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7167:        else
                   7168:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7169:       for(i=1;i<=nlstate;i++){
                   7170:        gm[i] = bprlim[i][i];
                   7171:        mgm[theta][i] = bprlim[i][i];
                   7172:       }
                   7173:       for(i=1;i<=nlstate;i++)
                   7174:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   7175:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   7176:     } /* End theta */
                   7177: 
                   7178:     trgradg =matrix(1,nlstate,1,npar);
                   7179: 
                   7180:     for(j=1; j<=nlstate;j++)
                   7181:       for(theta=1; theta <=npar; theta++)
                   7182:        trgradg[j][theta]=gradg[theta][j];
                   7183:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7184:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7185:     /*   for(j=1; j<=nlstate;j++){ */
                   7186:     /*         printf(" %d ",j); */
                   7187:     /*         for(theta=1; theta <=npar; theta++) */
                   7188:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7189:     /*         printf("\n "); */
                   7190:     /*   } */
                   7191:     /* } */
                   7192:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7193:     /*   printf("\n gradg %d ",(int)age); */
                   7194:     /*   for(j=1; j<=nlstate;j++){ */
                   7195:     /*         printf("%d ",j); */
                   7196:     /*         for(theta=1; theta <=npar; theta++) */
                   7197:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7198:     /*         printf("\n "); */
                   7199:     /*   } */
                   7200:     /* } */
                   7201: 
                   7202:     for(i=1;i<=nlstate;i++)
                   7203:       varbpl[i][(int)age] =0.;
                   7204:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   7205:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7206:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7207:     }else{
                   7208:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7209:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7210:     }
                   7211:     for(i=1;i<=nlstate;i++)
                   7212:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7213: 
                   7214:     fprintf(ficresvbl,"%.0f ",age );
                   7215:     if(nresult >=1)
                   7216:       fprintf(ficresvbl,"%d ",nres );
                   7217:     for(i=1; i<=nlstate;i++)
                   7218:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   7219:     fprintf(ficresvbl,"\n");
                   7220:     free_vector(gp,1,nlstate);
                   7221:     free_vector(gm,1,nlstate);
                   7222:     free_matrix(mgm,1,npar,1,nlstate);
                   7223:     free_matrix(mgp,1,npar,1,nlstate);
                   7224:     free_matrix(gradg,1,npar,1,nlstate);
                   7225:     free_matrix(trgradg,1,nlstate,1,npar);
                   7226:   } /* End age */
                   7227: 
                   7228:   free_vector(xp,1,npar);
                   7229:   free_matrix(doldm,1,nlstate,1,npar);
                   7230:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  7231: 
                   7232: }
                   7233: 
                   7234: /************ Variance of one-step probabilities  ******************/
                   7235: 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  7236:  {
                   7237:    int i, j=0,  k1, l1, tj;
                   7238:    int k2, l2, j1,  z1;
                   7239:    int k=0, l;
                   7240:    int first=1, first1, first2;
1.326     brouard  7241:    int nres=0; /* New */
1.222     brouard  7242:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   7243:    double **dnewm,**doldm;
                   7244:    double *xp;
                   7245:    double *gp, *gm;
                   7246:    double **gradg, **trgradg;
                   7247:    double **mu;
                   7248:    double age, cov[NCOVMAX+1];
                   7249:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   7250:    int theta;
                   7251:    char fileresprob[FILENAMELENGTH];
                   7252:    char fileresprobcov[FILENAMELENGTH];
                   7253:    char fileresprobcor[FILENAMELENGTH];
                   7254:    double ***varpij;
                   7255: 
                   7256:    strcpy(fileresprob,"PROB_"); 
                   7257:    strcat(fileresprob,fileres);
                   7258:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   7259:      printf("Problem with resultfile: %s\n", fileresprob);
                   7260:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   7261:    }
                   7262:    strcpy(fileresprobcov,"PROBCOV_"); 
                   7263:    strcat(fileresprobcov,fileresu);
                   7264:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   7265:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   7266:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   7267:    }
                   7268:    strcpy(fileresprobcor,"PROBCOR_"); 
                   7269:    strcat(fileresprobcor,fileresu);
                   7270:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   7271:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   7272:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   7273:    }
                   7274:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7275:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7276:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7277:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7278:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7279:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7280:    pstamp(ficresprob);
                   7281:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   7282:    fprintf(ficresprob,"# Age");
                   7283:    pstamp(ficresprobcov);
                   7284:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   7285:    fprintf(ficresprobcov,"# Age");
                   7286:    pstamp(ficresprobcor);
                   7287:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   7288:    fprintf(ficresprobcor,"# Age");
1.126     brouard  7289: 
                   7290: 
1.222     brouard  7291:    for(i=1; i<=nlstate;i++)
                   7292:      for(j=1; j<=(nlstate+ndeath);j++){
                   7293:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   7294:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   7295:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   7296:      }  
                   7297:    /* fprintf(ficresprob,"\n");
                   7298:       fprintf(ficresprobcov,"\n");
                   7299:       fprintf(ficresprobcor,"\n");
                   7300:    */
                   7301:    xp=vector(1,npar);
                   7302:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7303:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7304:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   7305:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   7306:    first=1;
                   7307:    fprintf(ficgp,"\n# Routine varprob");
                   7308:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   7309:    fprintf(fichtm,"\n");
                   7310: 
1.288     brouard  7311:    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  7312:    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);
                   7313:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  7314: and drawn. It helps understanding how is the covariance between two incidences.\
                   7315:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  7316:    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  7317: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   7318: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   7319: standard deviations wide on each axis. <br>\
                   7320:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   7321:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   7322: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   7323: 
1.222     brouard  7324:    cov[1]=1;
                   7325:    /* tj=cptcoveff; */
1.225     brouard  7326:    tj = (int) pow(2,cptcoveff);
1.222     brouard  7327:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   7328:    j1=0;
1.332     brouard  7329: 
                   7330:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   7331:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.334     brouard  7332:      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  7333:      if(tj != 1 && TKresult[nres]!= j1)
                   7334:        continue;
                   7335: 
                   7336:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   7337:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   7338:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  7339:      if  (cptcovn>0) {
1.334     brouard  7340:        fprintf(ficresprob, "\n#********** Variable ");
                   7341:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   7342:        fprintf(ficgp, "\n#********** Variable ");
                   7343:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   7344:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   7345: 
                   7346:        /* Including quantitative variables of the resultline to be done */
                   7347:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
1.338     brouard  7348:         printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   7349:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   7350:         /* 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  7351:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   7352:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   7353:             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  */
                   7354:             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  */
                   7355:             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  */
                   7356:             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  */
                   7357:             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  */
                   7358:             fprintf(ficresprob,"fixed ");
                   7359:             fprintf(ficresprobcov,"fixed ");
                   7360:             fprintf(ficgp,"fixed ");
                   7361:             fprintf(fichtmcov,"fixed ");
                   7362:             fprintf(ficresprobcor,"fixed ");
                   7363:           }else{
                   7364:             fprintf(ficresprob,"varyi ");
                   7365:             fprintf(ficresprobcov,"varyi ");
                   7366:             fprintf(ficgp,"varyi ");
                   7367:             fprintf(fichtmcov,"varyi ");
                   7368:             fprintf(ficresprobcor,"varyi ");
                   7369:           }
                   7370:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   7371:           /* For each selected (single) quantitative value */
1.337     brouard  7372:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
1.334     brouard  7373:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   7374:             fprintf(ficresprob,"fixed ");
                   7375:             fprintf(ficresprobcov,"fixed ");
                   7376:             fprintf(ficgp,"fixed ");
                   7377:             fprintf(fichtmcov,"fixed ");
                   7378:             fprintf(ficresprobcor,"fixed ");
                   7379:           }else{
                   7380:             fprintf(ficresprob,"varyi ");
                   7381:             fprintf(ficresprobcov,"varyi ");
                   7382:             fprintf(ficgp,"varyi ");
                   7383:             fprintf(fichtmcov,"varyi ");
                   7384:             fprintf(ficresprobcor,"varyi ");
                   7385:           }
                   7386:         }else{
                   7387:           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 */
                   7388:           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 */
                   7389:           exit(1);
                   7390:         }
                   7391:        } /* End loop on variable of this resultline */
                   7392:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  7393:        fprintf(ficresprob, "**********\n#\n");
                   7394:        fprintf(ficresprobcov, "**********\n#\n");
                   7395:        fprintf(ficgp, "**********\n#\n");
                   7396:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   7397:        fprintf(ficresprobcor, "**********\n#");    
                   7398:        if(invalidvarcomb[j1]){
                   7399:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   7400:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   7401:         continue;
                   7402:        }
                   7403:      }
                   7404:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   7405:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7406:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   7407:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  7408:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  7409:        cov[2]=age;
                   7410:        if(nagesqr==1)
                   7411:         cov[3]= age*age;
1.334     brouard  7412:        /* New code end of combination but for each resultline */
                   7413:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   7414:         if(Typevar[k1]==1){ /* A product with age */
                   7415:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  7416:         }else{
1.334     brouard  7417:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  7418:         }
1.334     brouard  7419:        }/* End of loop on model equation */
                   7420: /* Old code */
                   7421:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   7422:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   7423:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   7424:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   7425:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   7426:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   7427:        /*                                                                  * 1  1 1 1 1 */
                   7428:        /*                                                                  * 2  2 1 1 1 */
                   7429:        /*                                                                  * 3  1 2 1 1 */
                   7430:        /*                                                                  *\/ */
                   7431:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   7432:        /* } */
                   7433:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   7434:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   7435:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   7436:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   7437:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   7438:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   7439:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7440:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   7441:        /*         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]); */
                   7442:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   7443:        /*         /\* exit(1); *\/ */
                   7444:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   7445:        /*       } */
                   7446:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7447:        /* } */
                   7448:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   7449:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   7450:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7451:        /*           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]])]; */
                   7452:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7453:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   7454:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   7455:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   7456:        /*         } */
                   7457:        /*       }else{ */
                   7458:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7459:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   7460:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   7461:        /*         }else{ */
                   7462:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   7463:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   7464:        /*         } */
                   7465:        /*       } */
                   7466:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7467:        /* } */                 
1.326     brouard  7468: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  7469:        for(theta=1; theta <=npar; theta++){
                   7470:         for(i=1; i<=npar; i++)
                   7471:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7472:                                
1.222     brouard  7473:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7474:                                
1.222     brouard  7475:         k=0;
                   7476:         for(i=1; i<= (nlstate); i++){
                   7477:           for(j=1; j<=(nlstate+ndeath);j++){
                   7478:             k=k+1;
                   7479:             gp[k]=pmmij[i][j];
                   7480:           }
                   7481:         }
1.220     brouard  7482:                                
1.222     brouard  7483:         for(i=1; i<=npar; i++)
                   7484:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7485:                                
1.222     brouard  7486:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7487:         k=0;
                   7488:         for(i=1; i<=(nlstate); i++){
                   7489:           for(j=1; j<=(nlstate+ndeath);j++){
                   7490:             k=k+1;
                   7491:             gm[k]=pmmij[i][j];
                   7492:           }
                   7493:         }
1.220     brouard  7494:                                
1.222     brouard  7495:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7496:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7497:        }
1.126     brouard  7498: 
1.222     brouard  7499:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7500:         for(theta=1; theta <=npar; theta++)
                   7501:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7502:                        
1.222     brouard  7503:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7504:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7505:                        
1.222     brouard  7506:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7507:                        
1.222     brouard  7508:        k=0;
                   7509:        for(i=1; i<=(nlstate); i++){
                   7510:         for(j=1; j<=(nlstate+ndeath);j++){
                   7511:           k=k+1;
                   7512:           mu[k][(int) age]=pmmij[i][j];
                   7513:         }
                   7514:        }
                   7515:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7516:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7517:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7518:                        
1.222     brouard  7519:        /*printf("\n%d ",(int)age);
                   7520:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7521:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7522:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7523:         }*/
1.220     brouard  7524:                        
1.222     brouard  7525:        fprintf(ficresprob,"\n%d ",(int)age);
                   7526:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7527:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7528:                        
1.222     brouard  7529:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7530:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7531:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7532:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7533:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7534:        }
                   7535:        i=0;
                   7536:        for (k=1; k<=(nlstate);k++){
                   7537:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7538:           i++;
                   7539:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7540:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7541:           for (j=1; j<=i;j++){
                   7542:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7543:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7544:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7545:           }
                   7546:         }
                   7547:        }/* end of loop for state */
                   7548:      } /* end of loop for age */
                   7549:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7550:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7551:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7552:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7553:     
                   7554:      /* Confidence intervalle of pij  */
                   7555:      /*
                   7556:        fprintf(ficgp,"\nunset parametric;unset label");
                   7557:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7558:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7559:        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);
                   7560:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7561:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7562:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7563:      */
                   7564:                
                   7565:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7566:      first1=1;first2=2;
                   7567:      for (k2=1; k2<=(nlstate);k2++){
                   7568:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7569:         if(l2==k2) continue;
                   7570:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7571:         for (k1=1; k1<=(nlstate);k1++){
                   7572:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7573:             if(l1==k1) continue;
                   7574:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7575:             if(i<=j) continue;
                   7576:             for (age=bage; age<=fage; age ++){ 
                   7577:               if ((int)age %5==0){
                   7578:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7579:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7580:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7581:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7582:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7583:                 c12=cv12/sqrt(v1*v2);
                   7584:                 /* Computing eigen value of matrix of covariance */
                   7585:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7586:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7587:                 if ((lc2 <0) || (lc1 <0) ){
                   7588:                   if(first2==1){
                   7589:                     first1=0;
                   7590:                     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);
                   7591:                   }
                   7592:                   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);
                   7593:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7594:                   /* lc2=fabs(lc2); */
                   7595:                 }
1.220     brouard  7596:                                                                
1.222     brouard  7597:                 /* Eigen vectors */
1.280     brouard  7598:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7599:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7600:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7601:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7602:                 }else
                   7603:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7604:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7605:                 v21=(lc1-v1)/cv12*v11;
                   7606:                 v12=-v21;
                   7607:                 v22=v11;
                   7608:                 tnalp=v21/v11;
                   7609:                 if(first1==1){
                   7610:                   first1=0;
                   7611:                   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);
                   7612:                 }
                   7613:                 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);
                   7614:                 /*printf(fignu*/
                   7615:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7616:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7617:                 if(first==1){
                   7618:                   first=0;
                   7619:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7620:                   fprintf(ficgp,"\nset parametric;unset label");
                   7621:                   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);
                   7622:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7623:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7624:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7625: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7626:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7627:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7628:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7629:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7630:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7631:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7632:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7633:                   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  7634:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   7635:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  7636:                 }else{
                   7637:                   first=0;
                   7638:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   7639:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7640:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7641:                   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  7642:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   7643:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  7644:                 }/* if first */
                   7645:               } /* age mod 5 */
                   7646:             } /* end loop age */
                   7647:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7648:             first=1;
                   7649:           } /*l12 */
                   7650:         } /* k12 */
                   7651:        } /*l1 */
                   7652:      }/* k1 */
1.332     brouard  7653:    }  /* loop on combination of covariates j1 */
1.326     brouard  7654:    } /* loop on nres */
1.222     brouard  7655:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   7656:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   7657:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7658:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   7659:    free_vector(xp,1,npar);
                   7660:    fclose(ficresprob);
                   7661:    fclose(ficresprobcov);
                   7662:    fclose(ficresprobcor);
                   7663:    fflush(ficgp);
                   7664:    fflush(fichtmcov);
                   7665:  }
1.126     brouard  7666: 
                   7667: 
                   7668: /******************* Printing html file ***********/
1.201     brouard  7669: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7670:                  int lastpass, int stepm, int weightopt, char model[],\
                   7671:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  7672:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   7673:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   7674:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  7675:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  7676:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  7677:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   7678:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   7679: </ul>");
1.319     brouard  7680: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   7681: /* </ul>", model); */
1.214     brouard  7682:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   7683:    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",
                   7684:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  7685:    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  7686:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   7687:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  7688:    fprintf(fichtm,"\
                   7689:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  7690:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  7691:    fprintf(fichtm,"\
1.217     brouard  7692:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   7693:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   7694:    fprintf(fichtm,"\
1.288     brouard  7695:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7696:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  7697:    fprintf(fichtm,"\
1.288     brouard  7698:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  7699:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   7700:    fprintf(fichtm,"\
1.211     brouard  7701:  - (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  7702:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7703:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  7704:    if(prevfcast==1){
                   7705:      fprintf(fichtm,"\
                   7706:  - Prevalence projections by age and states:                           \
1.201     brouard  7707:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  7708:    }
1.126     brouard  7709: 
                   7710: 
1.225     brouard  7711:    m=pow(2,cptcoveff);
1.222     brouard  7712:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7713: 
1.317     brouard  7714:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  7715: 
                   7716:    jj1=0;
                   7717: 
                   7718:    fprintf(fichtm," \n<ul>");
1.337     brouard  7719:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7720:      /* k1=nres; */
1.338     brouard  7721:      k1=TKresult[nres];
                   7722:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
1.337     brouard  7723:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   7724:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   7725:    /*     continue; */
1.264     brouard  7726:      jj1++;
                   7727:      if (cptcovn > 0) {
                   7728:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
1.337     brouard  7729:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   7730:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7731:        }
1.337     brouard  7732:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   7733:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   7734:        /* } */
                   7735:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7736:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7737:        /* } */
1.264     brouard  7738:        fprintf(fichtm,"\">");
                   7739:        
                   7740:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7741:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  7742:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7743:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7744:        }
1.337     brouard  7745:        /* fprintf(fichtm,"************ Results for covariates"); */
                   7746:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   7747:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   7748:        /* } */
                   7749:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7750:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7751:        /* } */
1.264     brouard  7752:        if(invalidvarcomb[k1]){
                   7753:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7754:         continue;
                   7755:        }
                   7756:        fprintf(fichtm,"</a></li>");
                   7757:      } /* cptcovn >0 */
                   7758:    }
1.317     brouard  7759:    fprintf(fichtm," \n</ul>");
1.264     brouard  7760: 
1.222     brouard  7761:    jj1=0;
1.237     brouard  7762: 
1.337     brouard  7763:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7764:      /* k1=nres; */
1.338     brouard  7765:      k1=TKresult[nres];
                   7766:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  7767:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   7768:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   7769:    /*     continue; */
1.220     brouard  7770: 
1.222     brouard  7771:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7772:      jj1++;
                   7773:      if (cptcovn > 0) {
1.264     brouard  7774:        fprintf(fichtm,"\n<p><a name=\"rescov");
1.337     brouard  7775:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7776:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7777:        }
1.337     brouard  7778:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7779:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7780:        /* } */
1.264     brouard  7781:        fprintf(fichtm,"\"</a>");
                   7782:  
1.222     brouard  7783:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  7784:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7785:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   7786:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  7787:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7788:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  7789:        }
1.230     brouard  7790:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.338     brouard  7791:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  7792:        if(invalidvarcomb[k1]){
                   7793:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   7794:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   7795:         continue;
                   7796:        }
                   7797:      }
                   7798:      /* aij, bij */
1.259     brouard  7799:      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  7800: <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  7801:      /* Pij */
1.241     brouard  7802:      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> \
                   7803: <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  7804:      /* Quasi-incidences */
                   7805:      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  7806:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  7807:  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  7808: 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> \
                   7809: <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  7810:      /* Survival functions (period) in state j */
                   7811:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7812:        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);
                   7813:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7814:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  7815:      }
                   7816:      /* State specific survival functions (period) */
                   7817:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7818:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   7819:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.329     brouard  7820:  <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);
                   7821:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7822:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  7823:      }
1.288     brouard  7824:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  7825:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7826:        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  7827:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
1.329     brouard  7828:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  7829:      }
1.296     brouard  7830:      if(prevbcast==1){
1.288     brouard  7831:        /* Backward prevalence in each health state */
1.222     brouard  7832:        for(cpt=1; cpt<=nlstate;cpt++){
1.338     brouard  7833:         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);
                   7834:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
                   7835:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  7836:        }
1.217     brouard  7837:      }
1.222     brouard  7838:      if(prevfcast==1){
1.288     brouard  7839:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7840:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  7841:         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);
                   7842:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   7843:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   7844:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  7845:        }
                   7846:      }
1.296     brouard  7847:      if(prevbcast==1){
1.268     brouard  7848:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   7849:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  7850:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   7851:  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 \
                   7852:  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  7853: 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);
                   7854:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   7855:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  7856:        }
                   7857:      }
1.220     brouard  7858:         
1.222     brouard  7859:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  7860:        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);
                   7861:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   7862:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  7863:      }
                   7864:      /* } /\* end i1 *\/ */
1.337     brouard  7865:    }/* End k1=nres */
1.222     brouard  7866:    fprintf(fichtm,"</ul>");
1.126     brouard  7867: 
1.222     brouard  7868:    fprintf(fichtm,"\
1.126     brouard  7869: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  7870:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  7871:  - 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  7872: But because parameters are usually highly correlated (a higher incidence of disability \
                   7873: and a higher incidence of recovery can give very close observed transition) it might \
                   7874: be very useful to look not only at linear confidence intervals estimated from the \
                   7875: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   7876: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   7877: covariance matrix of the one-step probabilities. \
                   7878: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  7879: 
1.222     brouard  7880:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   7881:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   7882:    fprintf(fichtm,"\
1.126     brouard  7883:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7884:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  7885: 
1.222     brouard  7886:    fprintf(fichtm,"\
1.126     brouard  7887:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7888:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   7889:    fprintf(fichtm,"\
1.126     brouard  7890:  - 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): \
                   7891:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7892:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  7893:    fprintf(fichtm,"\
1.126     brouard  7894:  - (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): \
                   7895:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7896:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  7897:    fprintf(fichtm,"\
1.288     brouard  7898:  - 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  7899:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   7900:    fprintf(fichtm,"\
1.128     brouard  7901:  - 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  7902:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   7903:    fprintf(fichtm,"\
1.288     brouard  7904:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  7905:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  7906: 
                   7907: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   7908: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   7909: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   7910: /*     <br>",fileres,fileres,fileres,fileres); */
                   7911: /*  else  */
1.338     brouard  7912: /*    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  7913:    fflush(fichtm);
1.126     brouard  7914: 
1.225     brouard  7915:    m=pow(2,cptcoveff);
1.222     brouard  7916:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7917: 
1.317     brouard  7918:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   7919: 
                   7920:   jj1=0;
                   7921: 
                   7922:    fprintf(fichtm," \n<ul>");
1.337     brouard  7923:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7924:      /* k1=nres; */
1.338     brouard  7925:      k1=TKresult[nres];
1.337     brouard  7926:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   7927:      /* if(m != 1 && TKresult[nres]!= k1) */
                   7928:      /*   continue; */
1.317     brouard  7929:      jj1++;
                   7930:      if (cptcovn > 0) {
                   7931:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
1.337     brouard  7932:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7933:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  7934:        }
                   7935:        fprintf(fichtm,"\">");
                   7936:        
                   7937:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7938:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  7939:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7940:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  7941:        }
                   7942:        if(invalidvarcomb[k1]){
                   7943:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7944:         continue;
                   7945:        }
                   7946:        fprintf(fichtm,"</a></li>");
                   7947:      } /* cptcovn >0 */
1.337     brouard  7948:    } /* End nres */
1.317     brouard  7949:    fprintf(fichtm," \n</ul>");
                   7950: 
1.222     brouard  7951:    jj1=0;
1.237     brouard  7952: 
1.241     brouard  7953:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  7954:      /* k1=nres; */
1.338     brouard  7955:      k1=TKresult[nres];
                   7956:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  7957:      /* for(k1=1; k1<=m;k1++){ */
                   7958:      /* if(m != 1 && TKresult[nres]!= k1) */
                   7959:      /*   continue; */
1.222     brouard  7960:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7961:      jj1++;
1.126     brouard  7962:      if (cptcovn > 0) {
1.317     brouard  7963:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
1.337     brouard  7964:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7965:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  7966:        }
                   7967:        fprintf(fichtm,"\"</a>");
                   7968:        
1.126     brouard  7969:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  7970:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
                   7971:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   7972:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  7973:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  7974:        }
1.237     brouard  7975: 
1.338     brouard  7976:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  7977: 
1.222     brouard  7978:        if(invalidvarcomb[k1]){
                   7979:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   7980:         continue;
                   7981:        }
1.337     brouard  7982:      } /* If cptcovn >0 */
1.126     brouard  7983:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  7984:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  7985: 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);
                   7986:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   7987:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  7988:      }
                   7989:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  7990: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  7991: true period expectancies (those weighted with period prevalences are also\
                   7992:  drawn in addition to the population based expectancies computed using\
1.314     brouard  7993:  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);
                   7994:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   7995:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  7996:      /* } /\* end i1 *\/ */
1.241     brouard  7997:   }/* End nres */
1.222     brouard  7998:    fprintf(fichtm,"</ul>");
                   7999:    fflush(fichtm);
1.126     brouard  8000: }
                   8001: 
                   8002: /******************* Gnuplot file **************/
1.296     brouard  8003: 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  8004: 
                   8005:   char dirfileres[132],optfileres[132];
1.264     brouard  8006:   char gplotcondition[132], gplotlabel[132];
1.237     brouard  8007:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,k4=0,ij=0, ijp=0, l=0;
1.211     brouard  8008:   int lv=0, vlv=0, kl=0;
1.130     brouard  8009:   int ng=0;
1.201     brouard  8010:   int vpopbased;
1.223     brouard  8011:   int ioffset; /* variable offset for columns */
1.270     brouard  8012:   int iyearc=1; /* variable column for year of projection  */
                   8013:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  8014:   int nres=0; /* Index of resultline */
1.266     brouard  8015:   int istart=1; /* For starting graphs in projections */
1.219     brouard  8016: 
1.126     brouard  8017: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   8018: /*     printf("Problem with file %s",optionfilegnuplot); */
                   8019: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   8020: /*   } */
                   8021: 
                   8022:   /*#ifdef windows */
                   8023:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  8024:   /*#endif */
1.225     brouard  8025:   m=pow(2,cptcoveff);
1.126     brouard  8026: 
1.274     brouard  8027:   /* diagram of the model */
                   8028:   fprintf(ficgp,"\n#Diagram of the model \n");
                   8029:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   8030:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   8031:   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);
                   8032: 
                   8033:   fprintf(ficgp,"\n#Centripete arrows (turning in other direction (1-i) instead of (i-1)) \nset for [i=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);
                   8034:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   8035:   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);
                   8036:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   8037:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   8038:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   8039:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   8040: 
1.202     brouard  8041:   /* Contribution to likelihood */
                   8042:   /* Plot the probability implied in the likelihood */
1.223     brouard  8043:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   8044:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   8045:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   8046:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  8047: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  8048:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   8049: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  8050:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   8051:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8052:   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));
                   8053:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8054:   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));
                   8055:   for (i=1; i<= nlstate ; i ++) {
                   8056:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   8057:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   8058:     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);
                   8059:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   8060:       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);
                   8061:     }
                   8062:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8063:   }
                   8064:   /* 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 */               
                   8065:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8066:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8067:   fprintf(ficgp,"\nset out;unset log\n");
                   8068:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  8069: 
1.126     brouard  8070:   strcpy(dirfileres,optionfilefiname);
                   8071:   strcpy(optfileres,"vpl");
1.223     brouard  8072:   /* 1eme*/
1.238     brouard  8073:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
1.337     brouard  8074:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
1.236     brouard  8075:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8076:        k1=TKresult[nres];
1.338     brouard  8077:        if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.238     brouard  8078:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.337     brouard  8079:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8080:        /*   continue; */
1.238     brouard  8081:        /* We are interested in selected combination by the resultline */
1.246     brouard  8082:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  8083:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  8084:        strcpy(gplotlabel,"(");
1.337     brouard  8085:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8086:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8087:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8088: 
                   8089:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
                   8090:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
                   8091:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8092:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8093:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8094:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8095:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
                   8096:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
                   8097:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
                   8098:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8099:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8100:        /* } */
                   8101:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8102:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
                   8103:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8104:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.264     brouard  8105:        }
                   8106:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  8107:        /* printf("\n#\n"); */
1.238     brouard  8108:        fprintf(ficgp,"\n#\n");
                   8109:        if(invalidvarcomb[k1]){
1.260     brouard  8110:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  8111:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8112:          continue;
                   8113:        }
1.235     brouard  8114:       
1.241     brouard  8115:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   8116:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  8117:        /* 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  8118:        fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  8119:        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);
                   8120:        /* 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); */
                   8121:       /* k1-1 error should be nres-1*/
1.238     brouard  8122:        for (i=1; i<= nlstate ; i ++) {
                   8123:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8124:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   8125:        }
1.288     brouard  8126:        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  8127:        for (i=1; i<= nlstate ; i ++) {
                   8128:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8129:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8130:        } 
1.260     brouard  8131:        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  8132:        for (i=1; i<= nlstate ; i ++) {
                   8133:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8134:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8135:        }  
1.265     brouard  8136:        /* 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)); */
                   8137:        
                   8138:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   8139:         if(cptcoveff ==0){
1.271     brouard  8140:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  8141:        }else{
                   8142:          kl=0;
                   8143:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8144:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8145:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  8146:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8147:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8148:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8149:            vlv= nbcode[Tvaraff[k]][lv];
                   8150:            kl++;
                   8151:            /* 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 *\/ */
                   8152:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8153:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8154:            /* ''  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*/
                   8155:            if(k==cptcoveff){
                   8156:              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], \
                   8157:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   8158:            }else{
                   8159:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   8160:              kl++;
                   8161:            }
                   8162:          } /* end covariate */
                   8163:        } /* end if no covariate */
                   8164: 
1.296     brouard  8165:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  8166:          /* 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  8167:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  8168:          if(cptcoveff ==0){
1.245     brouard  8169:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  8170:          }else{
                   8171:            kl=0;
                   8172:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8173:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8174:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  8175:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8176:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8177:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8178:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8179:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  8180:              kl++;
1.238     brouard  8181:              /* 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 *\/ */
                   8182:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8183:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8184:              /* ''  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*/
                   8185:              if(k==cptcoveff){
1.245     brouard  8186:                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  8187:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  8188:              }else{
1.332     brouard  8189:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  8190:                kl++;
                   8191:              }
                   8192:            } /* end covariate */
                   8193:          } /* end if no covariate */
1.296     brouard  8194:          if(prevbcast == 1){
1.268     brouard  8195:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   8196:            /* k1-1 error should be nres-1*/
                   8197:            for (i=1; i<= nlstate ; i ++) {
                   8198:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8199:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   8200:            }
1.271     brouard  8201:            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  8202:            for (i=1; i<= nlstate ; i ++) {
                   8203:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8204:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8205:            } 
1.276     brouard  8206:            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  8207:            for (i=1; i<= nlstate ; i ++) {
                   8208:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8209:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8210:            } 
1.274     brouard  8211:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  8212:          } /* end if backprojcast */
1.296     brouard  8213:        } /* end if prevbcast */
1.276     brouard  8214:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   8215:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  8216:       } /* nres */
1.337     brouard  8217:     /* } /\* k1 *\/ */
1.201     brouard  8218:   } /* cpt */
1.235     brouard  8219: 
                   8220:   
1.126     brouard  8221:   /*2 eme*/
1.337     brouard  8222:   /* for (k1=1; k1<= m ; k1 ++){   */
1.238     brouard  8223:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8224:       k1=TKresult[nres];
1.338     brouard  8225:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8226:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8227:       /*       continue; */
1.238     brouard  8228:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  8229:       strcpy(gplotlabel,"(");
1.337     brouard  8230:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8231:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8232:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8233:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8234:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8235:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8236:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8237:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8238:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8239:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8240:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8241:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8242:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8243:       /* } */
                   8244:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
                   8245:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8246:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8247:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8248:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  8249:       }
1.264     brouard  8250:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8251:       fprintf(ficgp,"\n#\n");
1.223     brouard  8252:       if(invalidvarcomb[k1]){
                   8253:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8254:        continue;
                   8255:       }
1.219     brouard  8256:                        
1.241     brouard  8257:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  8258:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  8259:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   8260:        if(vpopbased==0){
1.238     brouard  8261:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  8262:        }else
1.238     brouard  8263:          fprintf(ficgp,"\nreplot ");
                   8264:        for (i=1; i<= nlstate+1 ; i ++) {
                   8265:          k=2*i;
1.261     brouard  8266:          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  8267:          for (j=1; j<= nlstate+1 ; j ++) {
                   8268:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8269:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8270:          }   
                   8271:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   8272:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  8273:          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  8274:          for (j=1; j<= nlstate+1 ; j ++) {
                   8275:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8276:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8277:          }   
                   8278:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  8279:          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  8280:          for (j=1; j<= nlstate+1 ; j ++) {
                   8281:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8282:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8283:          }   
                   8284:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   8285:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   8286:        } /* state */
                   8287:       } /* vpopbased */
1.264     brouard  8288:       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  8289:     } /* end nres */
1.337     brouard  8290:   /* } /\* k1 end 2 eme*\/ */
1.238     brouard  8291:        
                   8292:        
                   8293:   /*3eme*/
1.337     brouard  8294:   /* for (k1=1; k1<= m ; k1 ++){ */
1.238     brouard  8295:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8296:       k1=TKresult[nres];
1.338     brouard  8297:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8298:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8299:       /*       continue; */
1.238     brouard  8300: 
1.332     brouard  8301:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  8302:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  8303:        strcpy(gplotlabel,"(");
1.337     brouard  8304:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8305:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8306:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8307:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8308:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8309:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8310:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8311:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8312:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8313:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8314:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8315:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8316:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8317:        /* } */
                   8318:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8319:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8320:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8321:        }
1.264     brouard  8322:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8323:        fprintf(ficgp,"\n#\n");
                   8324:        if(invalidvarcomb[k1]){
                   8325:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8326:          continue;
                   8327:        }
                   8328:                        
                   8329:        /*       k=2+nlstate*(2*cpt-2); */
                   8330:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  8331:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  8332:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  8333:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  8334: 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  8335:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8336:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8337:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   8338:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8339:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8340:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  8341:                                
1.238     brouard  8342:        */
                   8343:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  8344:          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  8345:          /*    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  8346:                                
1.238     brouard  8347:        } 
1.261     brouard  8348:        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  8349:       }
1.264     brouard  8350:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  8351:     } /* end nres */
1.337     brouard  8352:   /* } /\* end kl 3eme *\/ */
1.126     brouard  8353:   
1.223     brouard  8354:   /* 4eme */
1.201     brouard  8355:   /* Survival functions (period) from state i in state j by initial state i */
1.337     brouard  8356:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
1.238     brouard  8357:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8358:       k1=TKresult[nres];
1.338     brouard  8359:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8360:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8361:       /*       continue; */
1.238     brouard  8362:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  8363:        strcpy(gplotlabel,"(");
1.337     brouard  8364:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
                   8365:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8366:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8367:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8368:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8369:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8370:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8371:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8372:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8373:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8374:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8375:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8376:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8377:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8378:        /* } */
                   8379:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8380:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8381:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8382:        }       
1.264     brouard  8383:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8384:        fprintf(ficgp,"\n#\n");
                   8385:        if(invalidvarcomb[k1]){
                   8386:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8387:          continue;
1.223     brouard  8388:        }
1.238     brouard  8389:       
1.241     brouard  8390:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  8391:        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  8392:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8393: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8394:        k=3;
                   8395:        for (i=1; i<= nlstate ; i ++){
                   8396:          if(i==1){
                   8397:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8398:          }else{
                   8399:            fprintf(ficgp,", '' ");
                   8400:          }
                   8401:          l=(nlstate+ndeath)*(i-1)+1;
                   8402:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8403:          for (j=2; j<= nlstate+ndeath ; j ++)
                   8404:            fprintf(ficgp,"+$%d",k+l+j-1);
                   8405:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   8406:        } /* nlstate */
1.264     brouard  8407:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8408:       } /* end cpt state*/ 
                   8409:     } /* end nres */
1.337     brouard  8410:   /* } /\* end covariate k1 *\/   */
1.238     brouard  8411: 
1.220     brouard  8412: /* 5eme */
1.201     brouard  8413:   /* Survival functions (period) from state i in state j by final state j */
1.337     brouard  8414:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
1.238     brouard  8415:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8416:       k1=TKresult[nres];
1.338     brouard  8417:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8418:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8419:       /*       continue; */
1.238     brouard  8420:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  8421:        strcpy(gplotlabel,"(");
1.238     brouard  8422:        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  8423:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8424:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8425:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8426:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8427:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8428:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8429:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8430:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8431:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8432:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8433:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8434:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8435:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8436:        /* } */
                   8437:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8438:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8439:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8440:        }       
1.264     brouard  8441:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8442:        fprintf(ficgp,"\n#\n");
                   8443:        if(invalidvarcomb[k1]){
                   8444:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8445:          continue;
                   8446:        }
1.227     brouard  8447:       
1.241     brouard  8448:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  8449:        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  8450:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8451: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8452:        k=3;
                   8453:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8454:          if(j==1)
                   8455:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8456:          else
                   8457:            fprintf(ficgp,", '' ");
                   8458:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8459:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   8460:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   8461:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   8462:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   8463:        } /* nlstate */
                   8464:        fprintf(ficgp,", '' ");
                   8465:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   8466:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8467:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8468:          if(j < nlstate)
                   8469:            fprintf(ficgp,"$%d +",k+l);
                   8470:          else
                   8471:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   8472:        }
1.264     brouard  8473:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8474:       } /* end cpt state*/ 
1.337     brouard  8475:     /* } /\* end covariate *\/   */
1.238     brouard  8476:   } /* end nres */
1.227     brouard  8477:   
1.220     brouard  8478: /* 6eme */
1.202     brouard  8479:   /* CV preval stable (period) for each covariate */
1.337     brouard  8480:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8481:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8482:      k1=TKresult[nres];
1.338     brouard  8483:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8484:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8485:      /*  continue; */
1.255     brouard  8486:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  8487:       strcpy(gplotlabel,"(");      
1.288     brouard  8488:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8489:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8490:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8491:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8492:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8493:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8494:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8495:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8496:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8497:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8498:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8499:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8500:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8501:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8502:       /* } */
                   8503:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8504:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8505:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8506:       }        
1.264     brouard  8507:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8508:       fprintf(ficgp,"\n#\n");
1.223     brouard  8509:       if(invalidvarcomb[k1]){
1.227     brouard  8510:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8511:        continue;
1.223     brouard  8512:       }
1.227     brouard  8513:       
1.241     brouard  8514:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  8515:       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  8516:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8517: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  8518:       k=3; /* Offset */
1.255     brouard  8519:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  8520:        if(i==1)
                   8521:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8522:        else
                   8523:          fprintf(ficgp,", '' ");
1.255     brouard  8524:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  8525:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8526:        for (j=2; j<= nlstate ; j ++)
                   8527:          fprintf(ficgp,"+$%d",k+l+j-1);
                   8528:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  8529:       } /* nlstate */
1.264     brouard  8530:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  8531:     } /* end cpt state*/ 
                   8532:   } /* end covariate */  
1.227     brouard  8533:   
                   8534:   
1.220     brouard  8535: /* 7eme */
1.296     brouard  8536:   if(prevbcast == 1){
1.288     brouard  8537:     /* CV backward prevalence  for each covariate */
1.337     brouard  8538:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8539:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8540:       k1=TKresult[nres];
1.338     brouard  8541:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8542:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8543:       /*       continue; */
1.268     brouard  8544:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  8545:        strcpy(gplotlabel,"(");      
1.288     brouard  8546:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8547:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8548:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8549:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8550:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8551:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8552:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8553:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8554:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8555:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8556:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8557:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8558:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8559:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8560:        /* } */
                   8561:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8562:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8563:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8564:        }       
1.264     brouard  8565:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8566:        fprintf(ficgp,"\n#\n");
                   8567:        if(invalidvarcomb[k1]){
                   8568:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8569:          continue;
                   8570:        }
                   8571:        
1.241     brouard  8572:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  8573:        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  8574:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8575: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  8576:        k=3; /* Offset */
1.268     brouard  8577:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  8578:          if(i==1)
                   8579:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   8580:          else
                   8581:            fprintf(ficgp,", '' ");
                   8582:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  8583:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  8584:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   8585:          /* 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  8586:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  8587:          /* for (j=2; j<= nlstate ; j ++) */
                   8588:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   8589:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  8590:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  8591:        } /* nlstate */
1.264     brouard  8592:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  8593:       } /* end cpt state*/ 
                   8594:     } /* end covariate */  
1.296     brouard  8595:   } /* End if prevbcast */
1.218     brouard  8596:   
1.223     brouard  8597:   /* 8eme */
1.218     brouard  8598:   if(prevfcast==1){
1.288     brouard  8599:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  8600:     
1.337     brouard  8601:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8602:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8603:       k1=TKresult[nres];
1.338     brouard  8604:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8605:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8606:       /*       continue; */
1.211     brouard  8607:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  8608:        strcpy(gplotlabel,"(");      
1.288     brouard  8609:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8610:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8611:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8612:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8613:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   8614:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   8615:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8616:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8617:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8618:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8619:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8620:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8621:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8622:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8623:        /* } */
                   8624:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8625:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8626:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8627:        }       
1.264     brouard  8628:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8629:        fprintf(ficgp,"\n#\n");
                   8630:        if(invalidvarcomb[k1]){
                   8631:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8632:          continue;
                   8633:        }
                   8634:        
                   8635:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  8636:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  8637:        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  8638:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  8639: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  8640: 
                   8641:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8642:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8643:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8644:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  8645:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8646:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8647:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8648:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  8649:          if(i==istart){
1.227     brouard  8650:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   8651:          }else{
                   8652:            fprintf(ficgp,",\\\n '' ");
                   8653:          }
                   8654:          if(cptcoveff ==0){ /* No covariate */
                   8655:            ioffset=2; /* Age is in 2 */
                   8656:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8657:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8658:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8659:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8660:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  8661:            if(i==nlstate+1){
1.270     brouard  8662:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  8663:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8664:              fprintf(ficgp,",\\\n '' ");
                   8665:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8666:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  8667:                     offyear,                           \
1.268     brouard  8668:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  8669:            }else
1.227     brouard  8670:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   8671:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8672:          }else{ /* more than 2 covariates */
1.270     brouard  8673:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8674:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8675:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8676:            iyearc=ioffset-1;
                   8677:            iagec=ioffset;
1.227     brouard  8678:            fprintf(ficgp," u %d:(",ioffset); 
                   8679:            kl=0;
                   8680:            strcpy(gplotcondition,"(");
                   8681:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
1.332     brouard  8682:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8683:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8684:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8685:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8686:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8687:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   8688:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8689:              kl++;
                   8690:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8691:              kl++;
                   8692:              if(k <cptcoveff && cptcoveff>1)
                   8693:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8694:            }
                   8695:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8696:            /* 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 *\/ */
                   8697:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8698:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8699:            /* ''  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*/
                   8700:            if(i==nlstate+1){
1.270     brouard  8701:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   8702:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  8703:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8704:              fprintf(ficgp," u %d:(",iagec); 
                   8705:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   8706:                      iyearc, iagec, offyear,                           \
                   8707:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  8708: /*  '' 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  8709:            }else{
                   8710:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   8711:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8712:            }
                   8713:          } /* end if covariate */
                   8714:        } /* nlstate */
1.264     brouard  8715:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  8716:       } /* end cpt state*/
                   8717:     } /* end covariate */
                   8718:   } /* End if prevfcast */
1.227     brouard  8719:   
1.296     brouard  8720:   if(prevbcast==1){
1.268     brouard  8721:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   8722:     
1.337     brouard  8723:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.268     brouard  8724:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8725:      k1=TKresult[nres];
1.338     brouard  8726:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8727:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8728:        /*      continue; */
1.268     brouard  8729:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   8730:        strcpy(gplotlabel,"(");      
                   8731:        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  8732:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8733:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8734:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8735:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   8736:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   8737:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8738:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8739:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8740:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8741:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8742:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8743:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8744:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8745:        /* } */
                   8746:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8747:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8748:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.268     brouard  8749:        }       
                   8750:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   8751:        fprintf(ficgp,"\n#\n");
                   8752:        if(invalidvarcomb[k1]){
                   8753:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8754:          continue;
                   8755:        }
                   8756:        
                   8757:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   8758:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   8759:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   8760:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   8761: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8762: 
                   8763:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8764:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8765:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8766:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   8767:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8768:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8769:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8770:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8771:          if(i==istart){
                   8772:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   8773:          }else{
                   8774:            fprintf(ficgp,",\\\n '' ");
                   8775:          }
                   8776:          if(cptcoveff ==0){ /* No covariate */
                   8777:            ioffset=2; /* Age is in 2 */
                   8778:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8779:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8780:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8781:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8782:            fprintf(ficgp," u %d:(", ioffset); 
                   8783:            if(i==nlstate+1){
1.270     brouard  8784:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  8785:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8786:              fprintf(ficgp,",\\\n '' ");
                   8787:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8788:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  8789:                     offbyear,                          \
                   8790:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   8791:            }else
                   8792:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   8793:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   8794:          }else{ /* more than 2 covariates */
1.270     brouard  8795:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8796:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8797:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8798:            iyearc=ioffset-1;
                   8799:            iagec=ioffset;
1.268     brouard  8800:            fprintf(ficgp," u %d:(",ioffset); 
                   8801:            kl=0;
                   8802:            strcpy(gplotcondition,"(");
1.337     brouard  8803:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
1.338     brouard  8804:              if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
1.337     brouard  8805:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
                   8806:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8807:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8808:                lv=Tvresult[nres][k];
                   8809:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
                   8810:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8811:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8812:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8813:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   8814:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8815:                kl++;
                   8816:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   8817:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
                   8818:                kl++;
1.338     brouard  8819:                if(k <cptcovs && cptcovs>1)
1.337     brouard  8820:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8821:              }
1.268     brouard  8822:            }
                   8823:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8824:            /* 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 *\/ */
                   8825:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8826:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8827:            /* ''  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*/
                   8828:            if(i==nlstate+1){
1.270     brouard  8829:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   8830:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  8831:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8832:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  8833:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  8834:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   8835:                      iyearc,iagec,offbyear,                            \
                   8836:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  8837: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   8838:            }else{
                   8839:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   8840:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   8841:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   8842:            }
                   8843:          } /* end if covariate */
                   8844:        } /* nlstate */
                   8845:        fprintf(ficgp,"\nset out; unset label;\n");
                   8846:       } /* end cpt state*/
                   8847:     } /* end covariate */
1.296     brouard  8848:   } /* End if prevbcast */
1.268     brouard  8849:   
1.227     brouard  8850:   
1.238     brouard  8851:   /* 9eme writing MLE parameters */
                   8852:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  8853:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  8854:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  8855:     for(k=1; k <=(nlstate+ndeath); k++){
                   8856:       if (k != i) {
1.227     brouard  8857:        fprintf(ficgp,"#   current state %d\n",k);
                   8858:        for(j=1; j <=ncovmodel; j++){
                   8859:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   8860:          jk++; 
                   8861:        }
                   8862:        fprintf(ficgp,"\n");
1.126     brouard  8863:       }
                   8864:     }
1.223     brouard  8865:   }
1.187     brouard  8866:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  8867:   
1.145     brouard  8868:   /*goto avoid;*/
1.238     brouard  8869:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   8870:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  8871:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   8872:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   8873:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   8874:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   8875:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8876:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8877:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8878:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8879:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   8880:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8881:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   8882:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   8883:   fprintf(ficgp,"#\n");
1.223     brouard  8884:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  8885:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.338     brouard  8886:     fprintf(ficgp,"#model=1+age+%s \n",model);
1.238     brouard  8887:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  8888:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
1.337     brouard  8889:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
1.237     brouard  8890:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8891:      /* k1=nres; */
1.338     brouard  8892:       k1=TKresult[nres];
                   8893:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8894:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
1.264     brouard  8895:       strcpy(gplotlabel,"(");
1.276     brouard  8896:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.337     brouard  8897:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   8898:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
                   8899:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
                   8900:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8901:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8902:       }
                   8903:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8904:       /*       continue; */
                   8905:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
                   8906:       /* strcpy(gplotlabel,"("); */
                   8907:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
                   8908:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   8909:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   8910:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8911:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8912:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8913:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8914:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8915:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8916:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8917:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8918:       /* } */
                   8919:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8920:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8921:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8922:       /* }      */
1.264     brouard  8923:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  8924:       fprintf(ficgp,"\n#\n");
1.264     brouard  8925:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  8926:       fprintf(ficgp,"\nset key outside ");
                   8927:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   8928:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  8929:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   8930:       if (ng==1){
                   8931:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   8932:        fprintf(ficgp,"\nunset log y");
                   8933:       }else if (ng==2){
                   8934:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   8935:        fprintf(ficgp,"\nset log y");
                   8936:       }else if (ng==3){
                   8937:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   8938:        fprintf(ficgp,"\nset log y");
                   8939:       }else
                   8940:        fprintf(ficgp,"\nunset title ");
                   8941:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   8942:       i=1;
                   8943:       for(k2=1; k2<=nlstate; k2++) {
                   8944:        k3=i;
                   8945:        for(k=1; k<=(nlstate+ndeath); k++) {
                   8946:          if (k != k2){
                   8947:            switch( ng) {
                   8948:            case 1:
                   8949:              if(nagesqr==0)
                   8950:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   8951:              else /* nagesqr =1 */
                   8952:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8953:              break;
                   8954:            case 2: /* ng=2 */
                   8955:              if(nagesqr==0)
                   8956:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   8957:              else /* nagesqr =1 */
                   8958:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8959:              break;
                   8960:            case 3:
                   8961:              if(nagesqr==0)
                   8962:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   8963:              else /* nagesqr =1 */
                   8964:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   8965:              break;
                   8966:            }
                   8967:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  8968:            ijp=1; /* product no age */
                   8969:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   8970:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  8971:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  8972:              switch(Typevar[j]){
                   8973:              case 1:
                   8974:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8975:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   8976:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8977:                      if(DummyV[j]==0){/* Bug valgrind */
                   8978:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   8979:                      }else{ /* quantitative */
                   8980:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8981:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8982:                      }
                   8983:                      ij++;
1.268     brouard  8984:                    }
1.237     brouard  8985:                  }
1.329     brouard  8986:                }
                   8987:                break;
                   8988:              case 2:
                   8989:                if(cptcovprod >0){
                   8990:                  if(j==Tprod[ijp]) { /* */ 
                   8991:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8992:                    if(ijp <=cptcovprod) { /* Product */
                   8993:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8994:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8995:                          /* 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)]); */
                   8996:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8997:                        }else{ /* Vn is dummy and Vm is quanti */
                   8998:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8999:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9000:                        }
                   9001:                      }else{ /* Vn*Vm Vn is quanti */
                   9002:                        if(DummyV[Tvard[ijp][2]]==0){
                   9003:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9004:                        }else{ /* Both quanti */
                   9005:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9006:                        }
1.268     brouard  9007:                      }
1.329     brouard  9008:                      ijp++;
1.237     brouard  9009:                    }
1.329     brouard  9010:                  } /* end Tprod */
                   9011:                }
                   9012:                break;
                   9013:              case 0:
                   9014:                /* simple covariate */
1.264     brouard  9015:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  9016:                if(Dummy[j]==0){
                   9017:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   9018:                }else{ /* quantitative */
                   9019:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  9020:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  9021:                }
1.329     brouard  9022:               /* end simple */
                   9023:                break;
                   9024:              default:
                   9025:                break;
                   9026:              } /* end switch */
1.237     brouard  9027:            } /* end j */
1.329     brouard  9028:          }else{ /* k=k2 */
                   9029:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   9030:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   9031:            }else
                   9032:              i=i-ncovmodel;
1.223     brouard  9033:          }
1.227     brouard  9034:          
1.223     brouard  9035:          if(ng != 1){
                   9036:            fprintf(ficgp,")/(1");
1.227     brouard  9037:            
1.264     brouard  9038:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  9039:              if(nagesqr==0)
1.264     brouard  9040:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  9041:              else /* nagesqr =1 */
1.264     brouard  9042:                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  9043:               
1.223     brouard  9044:              ij=1;
1.329     brouard  9045:              ijp=1;
                   9046:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   9047:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   9048:                switch(Typevar[j]){
                   9049:                case 1:
                   9050:                  if(cptcovage >0){ 
                   9051:                    if(j==Tage[ij]) { /* Bug valgrind */
                   9052:                      if(ij <=cptcovage) { /* Bug valgrind */
                   9053:                        if(DummyV[j]==0){/* Bug valgrind */
                   9054:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   9055:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   9056:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   9057:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   9058:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9059:                        }else{ /* quantitative */
                   9060:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9061:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9062:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9063:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9064:                        }
                   9065:                        ij++;
                   9066:                      }
                   9067:                    }
                   9068:                  }
                   9069:                  break;
                   9070:                case 2:
                   9071:                  if(cptcovprod >0){
                   9072:                    if(j==Tprod[ijp]) { /* */ 
                   9073:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9074:                      if(ijp <=cptcovprod) { /* Product */
                   9075:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9076:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9077:                            /* 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)]); */
                   9078:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9079:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9080:                          }else{ /* Vn is dummy and Vm is quanti */
                   9081:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9082:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9083:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9084:                          }
                   9085:                        }else{ /* Vn*Vm Vn is quanti */
                   9086:                          if(DummyV[Tvard[ijp][2]]==0){
                   9087:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9088:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9089:                          }else{ /* Both quanti */
                   9090:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9091:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9092:                          } 
                   9093:                        }
                   9094:                        ijp++;
                   9095:                      }
                   9096:                    } /* end Tprod */
                   9097:                  } /* end if */
                   9098:                  break;
                   9099:                case 0: 
                   9100:                  /* simple covariate */
                   9101:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   9102:                  if(Dummy[j]==0){
                   9103:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9104:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   9105:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9106:                  }else{ /* quantitative */
                   9107:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   9108:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   9109:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9110:                  }
                   9111:                  /* end simple */
                   9112:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   9113:                  break;
                   9114:                default:
                   9115:                  break;
                   9116:                } /* end switch */
1.223     brouard  9117:              }
                   9118:              fprintf(ficgp,")");
                   9119:            }
                   9120:            fprintf(ficgp,")");
                   9121:            if(ng ==2)
1.276     brouard  9122:              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  9123:            else /* ng= 3 */
1.276     brouard  9124:              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  9125:           }else{ /* end ng <> 1 */
1.223     brouard  9126:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  9127:              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  9128:          }
                   9129:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   9130:            fprintf(ficgp,",");
                   9131:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   9132:            fprintf(ficgp,",");
                   9133:          i=i+ncovmodel;
                   9134:        } /* end k */
                   9135:       } /* end k2 */
1.276     brouard  9136:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   9137:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.337     brouard  9138:     } /* end resultline */
1.223     brouard  9139:   } /* end ng */
                   9140:   /* avoid: */
                   9141:   fflush(ficgp); 
1.126     brouard  9142: }  /* end gnuplot */
                   9143: 
                   9144: 
                   9145: /*************** Moving average **************/
1.219     brouard  9146: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  9147:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  9148:    
1.222     brouard  9149:    int i, cpt, cptcod;
                   9150:    int modcovmax =1;
                   9151:    int mobilavrange, mob;
                   9152:    int iage=0;
1.288     brouard  9153:    int firstA1=0, firstA2=0;
1.222     brouard  9154: 
1.266     brouard  9155:    double sum=0., sumr=0.;
1.222     brouard  9156:    double age;
1.266     brouard  9157:    double *sumnewp, *sumnewm, *sumnewmr;
                   9158:    double *agemingood, *agemaxgood; 
                   9159:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  9160:   
                   9161:   
1.278     brouard  9162:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   9163:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  9164: 
                   9165:    sumnewp = vector(1,ncovcombmax);
                   9166:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  9167:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  9168:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  9169:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  9170:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  9171:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  9172: 
                   9173:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  9174:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  9175:      sumnewp[cptcod]=0.;
1.266     brouard  9176:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   9177:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  9178:    }
                   9179:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   9180:   
1.266     brouard  9181:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   9182:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  9183:      else mobilavrange=mobilav;
                   9184:      for (age=bage; age<=fage; age++)
                   9185:        for (i=1; i<=nlstate;i++)
                   9186:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   9187:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9188:      /* We keep the original values on the extreme ages bage, fage and for 
                   9189:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   9190:        we use a 5 terms etc. until the borders are no more concerned. 
                   9191:      */ 
                   9192:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   9193:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  9194:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   9195:           sumnewm[cptcod]=0.;
                   9196:           for (i=1; i<=nlstate;i++){
1.222     brouard  9197:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   9198:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   9199:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   9200:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   9201:             }
                   9202:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  9203:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9204:           } /* end i */
                   9205:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   9206:         } /* end cptcod */
1.222     brouard  9207:        }/* end age */
                   9208:      }/* end mob */
1.266     brouard  9209:    }else{
                   9210:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  9211:      return -1;
1.266     brouard  9212:    }
                   9213: 
                   9214:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  9215:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   9216:      if(invalidvarcomb[cptcod]){
                   9217:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   9218:        continue;
                   9219:      }
1.219     brouard  9220: 
1.266     brouard  9221:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   9222:        sumnewm[cptcod]=0.;
                   9223:        sumnewmr[cptcod]=0.;
                   9224:        for (i=1; i<=nlstate;i++){
                   9225:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9226:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9227:        }
                   9228:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9229:         agemingoodr[cptcod]=age;
                   9230:        }
                   9231:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9232:           agemingood[cptcod]=age;
                   9233:        }
                   9234:      } /* age */
                   9235:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  9236:        sumnewm[cptcod]=0.;
1.266     brouard  9237:        sumnewmr[cptcod]=0.;
1.222     brouard  9238:        for (i=1; i<=nlstate;i++){
                   9239:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9240:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9241:        }
                   9242:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9243:         agemaxgoodr[cptcod]=age;
1.222     brouard  9244:        }
                   9245:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  9246:         agemaxgood[cptcod]=age;
                   9247:        }
                   9248:      } /* age */
                   9249:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   9250:      /* but they will change */
1.288     brouard  9251:      firstA1=0;firstA2=0;
1.266     brouard  9252:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   9253:        sumnewm[cptcod]=0.;
                   9254:        sumnewmr[cptcod]=0.;
                   9255:        for (i=1; i<=nlstate;i++){
                   9256:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9257:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9258:        }
                   9259:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9260:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9261:           agemaxgoodr[cptcod]=age;  /* age min */
                   9262:           for (i=1; i<=nlstate;i++)
                   9263:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9264:         }else{ /* bad we change the value with the values of good ages */
                   9265:           for (i=1; i<=nlstate;i++){
                   9266:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   9267:           } /* i */
                   9268:         } /* end bad */
                   9269:        }else{
                   9270:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9271:           agemaxgood[cptcod]=age;
                   9272:         }else{ /* bad we change the value with the values of good ages */
                   9273:           for (i=1; i<=nlstate;i++){
                   9274:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   9275:           } /* i */
                   9276:         } /* end bad */
                   9277:        }/* end else */
                   9278:        sum=0.;sumr=0.;
                   9279:        for (i=1; i<=nlstate;i++){
                   9280:         sum+=mobaverage[(int)age][i][cptcod];
                   9281:         sumr+=probs[(int)age][i][cptcod];
                   9282:        }
                   9283:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  9284:         if(!firstA1){
                   9285:           firstA1=1;
                   9286:           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);
                   9287:         }
                   9288:         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  9289:        } /* end bad */
                   9290:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9291:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  9292:         if(!firstA2){
                   9293:           firstA2=1;
                   9294:           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);
                   9295:         }
                   9296:         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  9297:        } /* end bad */
                   9298:      }/* age */
1.266     brouard  9299: 
                   9300:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  9301:        sumnewm[cptcod]=0.;
1.266     brouard  9302:        sumnewmr[cptcod]=0.;
1.222     brouard  9303:        for (i=1; i<=nlstate;i++){
                   9304:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9305:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9306:        } 
                   9307:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9308:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   9309:           agemingoodr[cptcod]=age;
                   9310:           for (i=1; i<=nlstate;i++)
                   9311:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9312:         }else{ /* bad we change the value with the values of good ages */
                   9313:           for (i=1; i<=nlstate;i++){
                   9314:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   9315:           } /* i */
                   9316:         } /* end bad */
                   9317:        }else{
                   9318:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9319:           agemingood[cptcod]=age;
                   9320:         }else{ /* bad */
                   9321:           for (i=1; i<=nlstate;i++){
                   9322:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   9323:           } /* i */
                   9324:         } /* end bad */
                   9325:        }/* end else */
                   9326:        sum=0.;sumr=0.;
                   9327:        for (i=1; i<=nlstate;i++){
                   9328:         sum+=mobaverage[(int)age][i][cptcod];
                   9329:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  9330:        }
1.266     brouard  9331:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  9332:         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  9333:        } /* end bad */
                   9334:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9335:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  9336:         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  9337:        } /* end bad */
                   9338:      }/* age */
1.266     brouard  9339: 
1.222     brouard  9340:                
                   9341:      for (age=bage; age<=fage; age++){
1.235     brouard  9342:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  9343:        sumnewp[cptcod]=0.;
                   9344:        sumnewm[cptcod]=0.;
                   9345:        for (i=1; i<=nlstate;i++){
                   9346:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   9347:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9348:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   9349:        }
                   9350:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   9351:      }
                   9352:      /* printf("\n"); */
                   9353:      /* } */
1.266     brouard  9354: 
1.222     brouard  9355:      /* brutal averaging */
1.266     brouard  9356:      /* for (i=1; i<=nlstate;i++){ */
                   9357:      /*   for (age=1; age<=bage; age++){ */
                   9358:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   9359:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9360:      /*   }     */
                   9361:      /*   for (age=fage; age<=AGESUP; age++){ */
                   9362:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   9363:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9364:      /*   } */
                   9365:      /* } /\* end i status *\/ */
                   9366:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   9367:      /*   for (age=1; age<=AGESUP; age++){ */
                   9368:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   9369:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   9370:      /*   } */
                   9371:      /* } */
1.222     brouard  9372:    }/* end cptcod */
1.266     brouard  9373:    free_vector(agemaxgoodr,1, ncovcombmax);
                   9374:    free_vector(agemaxgood,1, ncovcombmax);
                   9375:    free_vector(agemingood,1, ncovcombmax);
                   9376:    free_vector(agemingoodr,1, ncovcombmax);
                   9377:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  9378:    free_vector(sumnewm,1, ncovcombmax);
                   9379:    free_vector(sumnewp,1, ncovcombmax);
                   9380:    return 0;
                   9381:  }/* End movingaverage */
1.218     brouard  9382:  
1.126     brouard  9383: 
1.296     brouard  9384:  
1.126     brouard  9385: /************** Forecasting ******************/
1.296     brouard  9386: /* 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)*/
                   9387: 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){
                   9388:   /* dateintemean, mean date of interviews
                   9389:      dateprojd, year, month, day of starting projection 
                   9390:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  9391:      agemin, agemax range of age
                   9392:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   9393:   */
1.296     brouard  9394:   /* double anprojd, mprojd, jprojd; */
                   9395:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  9396:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  9397:   double agec; /* generic age */
1.296     brouard  9398:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  9399:   double *popeffectif,*popcount;
                   9400:   double ***p3mat;
1.218     brouard  9401:   /* double ***mobaverage; */
1.126     brouard  9402:   char fileresf[FILENAMELENGTH];
                   9403: 
                   9404:   agelim=AGESUP;
1.211     brouard  9405:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9406:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9407:      We still use firstpass and lastpass as another selection.
                   9408:   */
1.214     brouard  9409:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9410:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  9411:  
1.201     brouard  9412:   strcpy(fileresf,"F_"); 
                   9413:   strcat(fileresf,fileresu);
1.126     brouard  9414:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   9415:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   9416:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   9417:   }
1.235     brouard  9418:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   9419:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  9420: 
1.225     brouard  9421:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  9422: 
                   9423: 
                   9424:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9425:   if (stepm<=12) stepsize=1;
                   9426:   if(estepm < stepm){
                   9427:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9428:   }
1.270     brouard  9429:   else{
                   9430:     hstepm=estepm;   
                   9431:   }
                   9432:   if(estepm > stepm){ /* Yes every two year */
                   9433:     stepsize=2;
                   9434:   }
1.296     brouard  9435:   hstepm=hstepm/stepm;
1.126     brouard  9436: 
1.296     brouard  9437:   
                   9438:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9439:   /*                              fractional in yp1 *\/ */
                   9440:   /* aintmean=yp; */
                   9441:   /* yp2=modf((yp1*12),&yp); */
                   9442:   /* mintmean=yp; */
                   9443:   /* yp1=modf((yp2*30.5),&yp); */
                   9444:   /* jintmean=yp; */
                   9445:   /* if(jintmean==0) jintmean=1; */
                   9446:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  9447: 
1.296     brouard  9448: 
                   9449:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   9450:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   9451:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  9452:   i1=pow(2,cptcoveff);
1.126     brouard  9453:   if (cptcovn < 1){i1=1;}
                   9454:   
1.296     brouard  9455:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  9456:   
                   9457:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  9458:   
1.126     brouard  9459: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  9460:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.332     brouard  9461:     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) */
1.253     brouard  9462:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  9463:       continue;
1.227     brouard  9464:     if(invalidvarcomb[k]){
                   9465:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9466:       continue;
                   9467:     }
                   9468:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   9469:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9470:       /* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); */
                   9471:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.227     brouard  9472:     }
1.235     brouard  9473:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  9474:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  9475:     }
1.227     brouard  9476:     fprintf(ficresf," yearproj age");
                   9477:     for(j=1; j<=nlstate+ndeath;j++){ 
                   9478:       for(i=1; i<=nlstate;i++)               
                   9479:        fprintf(ficresf," p%d%d",i,j);
                   9480:       fprintf(ficresf," wp.%d",j);
                   9481:     }
1.296     brouard  9482:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  9483:       fprintf(ficresf,"\n");
1.296     brouard  9484:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  9485:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   9486:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  9487:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   9488:        nhstepm = nhstepm/hstepm; 
                   9489:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9490:        oldm=oldms;savm=savms;
1.268     brouard  9491:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  9492:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  9493:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  9494:        for (h=0; h<=nhstepm; h++){
                   9495:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  9496:            break;
                   9497:          }
                   9498:        }
                   9499:        fprintf(ficresf,"\n");
                   9500:        for(j=1;j<=cptcoveff;j++) 
1.332     brouard  9501:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
                   9502:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /* TnsdVar[Tvaraff]  correct */
1.296     brouard  9503:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  9504:        
                   9505:        for(j=1; j<=nlstate+ndeath;j++) {
                   9506:          ppij=0.;
                   9507:          for(i=1; i<=nlstate;i++) {
1.278     brouard  9508:            if (mobilav>=1)
                   9509:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   9510:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   9511:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   9512:            }
1.268     brouard  9513:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   9514:          } /* end i */
                   9515:          fprintf(ficresf," %.3f", ppij);
                   9516:        }/* end j */
1.227     brouard  9517:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9518:       } /* end agec */
1.266     brouard  9519:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   9520:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  9521:     } /* end yearp */
                   9522:   } /* end  k */
1.219     brouard  9523:        
1.126     brouard  9524:   fclose(ficresf);
1.215     brouard  9525:   printf("End of Computing forecasting \n");
                   9526:   fprintf(ficlog,"End of Computing forecasting\n");
                   9527: 
1.126     brouard  9528: }
                   9529: 
1.269     brouard  9530: /************** Back Forecasting ******************/
1.296     brouard  9531:  /* 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){ */
                   9532:  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){
                   9533:   /* back1, year, month, day of starting backprojection
1.267     brouard  9534:      agemin, agemax range of age
                   9535:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  9536:      anback2 year of end of backprojection (same day and month as back1).
                   9537:      prevacurrent and prev are prevalences.
1.267     brouard  9538:   */
                   9539:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   9540:   double agec; /* generic age */
1.302     brouard  9541:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  9542:   double *popeffectif,*popcount;
                   9543:   double ***p3mat;
                   9544:   /* double ***mobaverage; */
                   9545:   char fileresfb[FILENAMELENGTH];
                   9546:  
1.268     brouard  9547:   agelim=AGEINF;
1.267     brouard  9548:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9549:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9550:      We still use firstpass and lastpass as another selection.
                   9551:   */
                   9552:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9553:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   9554: 
                   9555:   /*Do we need to compute prevalence again?*/
                   9556: 
                   9557:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   9558:   
                   9559:   strcpy(fileresfb,"FB_");
                   9560:   strcat(fileresfb,fileresu);
                   9561:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   9562:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   9563:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   9564:   }
                   9565:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9566:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9567:   
                   9568:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   9569:   
                   9570:    
                   9571:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9572:   if (stepm<=12) stepsize=1;
                   9573:   if(estepm < stepm){
                   9574:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9575:   }
1.270     brouard  9576:   else{
                   9577:     hstepm=estepm;   
                   9578:   }
                   9579:   if(estepm >= stepm){ /* Yes every two year */
                   9580:     stepsize=2;
                   9581:   }
1.267     brouard  9582:   
                   9583:   hstepm=hstepm/stepm;
1.296     brouard  9584:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9585:   /*                              fractional in yp1 *\/ */
                   9586:   /* aintmean=yp; */
                   9587:   /* yp2=modf((yp1*12),&yp); */
                   9588:   /* mintmean=yp; */
                   9589:   /* yp1=modf((yp2*30.5),&yp); */
                   9590:   /* jintmean=yp; */
                   9591:   /* if(jintmean==0) jintmean=1; */
                   9592:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  9593:   
                   9594:   i1=pow(2,cptcoveff);
                   9595:   if (cptcovn < 1){i1=1;}
                   9596:   
1.296     brouard  9597:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   9598:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  9599:   
                   9600:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   9601:   
                   9602:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9603:   for(k=1; k<=i1;k++){
                   9604:     if(i1 != 1 && TKresult[nres]!= k)
                   9605:       continue;
                   9606:     if(invalidvarcomb[k]){
                   9607:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9608:       continue;
                   9609:     }
1.268     brouard  9610:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  9611:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9612:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.267     brouard  9613:     }
                   9614:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9615:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9616:     }
                   9617:     fprintf(ficresfb," yearbproj age");
                   9618:     for(j=1; j<=nlstate+ndeath;j++){
                   9619:       for(i=1; i<=nlstate;i++)
1.268     brouard  9620:        fprintf(ficresfb," b%d%d",i,j);
                   9621:       fprintf(ficresfb," b.%d",j);
1.267     brouard  9622:     }
1.296     brouard  9623:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  9624:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   9625:       fprintf(ficresfb,"\n");
1.296     brouard  9626:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  9627:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  9628:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   9629:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  9630:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  9631:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  9632:        nhstepm = nhstepm/hstepm;
                   9633:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9634:        oldm=oldms;savm=savms;
1.268     brouard  9635:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  9636:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  9637:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  9638:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   9639:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   9640:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  9641:        for (h=0; h<=nhstepm; h++){
1.268     brouard  9642:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   9643:            break;
                   9644:          }
                   9645:        }
                   9646:        fprintf(ficresfb,"\n");
                   9647:        for(j=1;j<=cptcoveff;j++)
1.332     brouard  9648:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.296     brouard  9649:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  9650:        for(i=1; i<=nlstate+ndeath;i++) {
                   9651:          ppij=0.;ppi=0.;
                   9652:          for(j=1; j<=nlstate;j++) {
                   9653:            /* if (mobilav==1) */
1.269     brouard  9654:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   9655:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   9656:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   9657:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  9658:              /* else { */
                   9659:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   9660:              /* } */
1.268     brouard  9661:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   9662:          } /* end j */
                   9663:          if(ppi <0.99){
                   9664:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9665:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9666:          }
                   9667:          fprintf(ficresfb," %.3f", ppij);
                   9668:        }/* end j */
1.267     brouard  9669:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9670:       } /* end agec */
                   9671:     } /* end yearp */
                   9672:   } /* end k */
1.217     brouard  9673:   
1.267     brouard  9674:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  9675:   
1.267     brouard  9676:   fclose(ficresfb);
                   9677:   printf("End of Computing Back forecasting \n");
                   9678:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  9679:        
1.267     brouard  9680: }
1.217     brouard  9681: 
1.269     brouard  9682: /* Variance of prevalence limit: varprlim */
                   9683:  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  9684:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  9685:  
                   9686:    char fileresvpl[FILENAMELENGTH];  
                   9687:    FILE *ficresvpl;
                   9688:    double **oldm, **savm;
                   9689:    double **varpl; /* Variances of prevalence limits by age */   
                   9690:    int i1, k, nres, j ;
                   9691:    
                   9692:     strcpy(fileresvpl,"VPL_");
                   9693:     strcat(fileresvpl,fileresu);
                   9694:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  9695:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  9696:       exit(0);
                   9697:     }
1.288     brouard  9698:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   9699:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  9700:     
                   9701:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9702:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9703:     
                   9704:     i1=pow(2,cptcoveff);
                   9705:     if (cptcovn < 1){i1=1;}
                   9706: 
1.337     brouard  9707:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9708:        k=TKresult[nres];
1.338     brouard  9709:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  9710:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
1.269     brouard  9711:       if(i1 != 1 && TKresult[nres]!= k)
                   9712:        continue;
                   9713:       fprintf(ficresvpl,"\n#****** ");
                   9714:       printf("\n#****** ");
                   9715:       fprintf(ficlog,"\n#****** ");
1.337     brouard  9716:       for(j=1;j<=cptcovs;j++) {
                   9717:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9718:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9719:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9720:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9721:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.269     brouard  9722:       }
1.337     brouard  9723:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   9724:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9725:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9726:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9727:       /* }      */
1.269     brouard  9728:       fprintf(ficresvpl,"******\n");
                   9729:       printf("******\n");
                   9730:       fprintf(ficlog,"******\n");
                   9731:       
                   9732:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9733:       oldm=oldms;savm=savms;
                   9734:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   9735:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   9736:       /*}*/
                   9737:     }
                   9738:     
                   9739:     fclose(ficresvpl);
1.288     brouard  9740:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   9741:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  9742: 
                   9743:  }
                   9744: /* Variance of back prevalence: varbprlim */
                   9745:  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){
                   9746:       /*------- Variance of back (stable) prevalence------*/
                   9747: 
                   9748:    char fileresvbl[FILENAMELENGTH];  
                   9749:    FILE  *ficresvbl;
                   9750: 
                   9751:    double **oldm, **savm;
                   9752:    double **varbpl; /* Variances of back prevalence limits by age */   
                   9753:    int i1, k, nres, j ;
                   9754: 
                   9755:    strcpy(fileresvbl,"VBL_");
                   9756:    strcat(fileresvbl,fileresu);
                   9757:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   9758:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   9759:      exit(0);
                   9760:    }
                   9761:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   9762:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   9763:    
                   9764:    
                   9765:    i1=pow(2,cptcoveff);
                   9766:    if (cptcovn < 1){i1=1;}
                   9767:    
1.337     brouard  9768:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9769:      k=TKresult[nres];
1.338     brouard  9770:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  9771:     /* for(k=1; k<=i1;k++){ */
                   9772:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   9773:     /*          continue; */
1.269     brouard  9774:        fprintf(ficresvbl,"\n#****** ");
                   9775:        printf("\n#****** ");
                   9776:        fprintf(ficlog,"\n#****** ");
1.337     brouard  9777:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
1.338     brouard  9778:         printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   9779:         fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   9780:         fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
1.337     brouard  9781:        /* for(j=1;j<=cptcoveff;j++) { */
                   9782:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9783:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9784:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9785:        /* } */
                   9786:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   9787:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9788:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9789:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
1.269     brouard  9790:        }
                   9791:        fprintf(ficresvbl,"******\n");
                   9792:        printf("******\n");
                   9793:        fprintf(ficlog,"******\n");
                   9794:        
                   9795:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9796:        oldm=oldms;savm=savms;
                   9797:        
                   9798:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   9799:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   9800:        /*}*/
                   9801:      }
                   9802:    
                   9803:    fclose(ficresvbl);
                   9804:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   9805:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   9806: 
                   9807:  } /* End of varbprlim */
                   9808: 
1.126     brouard  9809: /************** Forecasting *****not tested NB*************/
1.227     brouard  9810: /* 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  9811:   
1.227     brouard  9812: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   9813: /*   int *popage; */
                   9814: /*   double calagedatem, agelim, kk1, kk2; */
                   9815: /*   double *popeffectif,*popcount; */
                   9816: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   9817: /*   /\* double ***mobaverage; *\/ */
                   9818: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  9819: 
1.227     brouard  9820: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9821: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9822: /*   agelim=AGESUP; */
                   9823: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  9824:   
1.227     brouard  9825: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  9826:   
                   9827:   
1.227     brouard  9828: /*   strcpy(filerespop,"POP_");  */
                   9829: /*   strcat(filerespop,fileresu); */
                   9830: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   9831: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   9832: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   9833: /*   } */
                   9834: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   9835: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  9836: 
1.227     brouard  9837: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  9838: 
1.227     brouard  9839: /*   /\* if (mobilav!=0) { *\/ */
                   9840: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   9841: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   9842: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9843: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9844: /*   /\*   } *\/ */
                   9845: /*   /\* } *\/ */
1.126     brouard  9846: 
1.227     brouard  9847: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   9848: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  9849:   
1.227     brouard  9850: /*   agelim=AGESUP; */
1.126     brouard  9851:   
1.227     brouard  9852: /*   hstepm=1; */
                   9853: /*   hstepm=hstepm/stepm;  */
1.218     brouard  9854:        
1.227     brouard  9855: /*   if (popforecast==1) { */
                   9856: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   9857: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   9858: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   9859: /*     }  */
                   9860: /*     popage=ivector(0,AGESUP); */
                   9861: /*     popeffectif=vector(0,AGESUP); */
                   9862: /*     popcount=vector(0,AGESUP); */
1.126     brouard  9863:     
1.227     brouard  9864: /*     i=1;    */
                   9865: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  9866:     
1.227     brouard  9867: /*     imx=i; */
                   9868: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   9869: /*   } */
1.218     brouard  9870:   
1.227     brouard  9871: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   9872: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   9873: /*       k=k+1; */
                   9874: /*       fprintf(ficrespop,"\n#******"); */
                   9875: /*       for(j=1;j<=cptcoveff;j++) { */
                   9876: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   9877: /*       } */
                   9878: /*       fprintf(ficrespop,"******\n"); */
                   9879: /*       fprintf(ficrespop,"# Age"); */
                   9880: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   9881: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  9882:       
1.227     brouard  9883: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   9884: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  9885:        
1.227     brouard  9886: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9887: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9888: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9889:          
1.227     brouard  9890: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9891: /*       oldm=oldms;savm=savms; */
                   9892: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  9893:          
1.227     brouard  9894: /*       for (h=0; h<=nhstepm; h++){ */
                   9895: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9896: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9897: /*         }  */
                   9898: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9899: /*           kk1=0.;kk2=0; */
                   9900: /*           for(i=1; i<=nlstate;i++) {               */
                   9901: /*             if (mobilav==1)  */
                   9902: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   9903: /*             else { */
                   9904: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   9905: /*             } */
                   9906: /*           } */
                   9907: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   9908: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   9909: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   9910: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   9911: /*           } */
                   9912: /*         } */
                   9913: /*         for(i=1; i<=nlstate;i++){ */
                   9914: /*           kk1=0.; */
                   9915: /*           for(j=1; j<=nlstate;j++){ */
                   9916: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   9917: /*           } */
                   9918: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   9919: /*         } */
1.218     brouard  9920:            
1.227     brouard  9921: /*         if (h==(int)(calagedatem+12*cpt)) */
                   9922: /*           for(j=1; j<=nlstate;j++)  */
                   9923: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   9924: /*       } */
                   9925: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9926: /*     } */
                   9927: /*       } */
1.218     brouard  9928:       
1.227     brouard  9929: /*       /\******\/ */
1.218     brouard  9930:       
1.227     brouard  9931: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   9932: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   9933: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9934: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9935: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9936:          
1.227     brouard  9937: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9938: /*       oldm=oldms;savm=savms; */
                   9939: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   9940: /*       for (h=0; h<=nhstepm; h++){ */
                   9941: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9942: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9943: /*         }  */
                   9944: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9945: /*           kk1=0.;kk2=0; */
                   9946: /*           for(i=1; i<=nlstate;i++) {               */
                   9947: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   9948: /*           } */
                   9949: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   9950: /*         } */
                   9951: /*       } */
                   9952: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9953: /*     } */
                   9954: /*       } */
                   9955: /*     }  */
                   9956: /*   } */
1.218     brouard  9957:   
1.227     brouard  9958: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  9959:   
1.227     brouard  9960: /*   if (popforecast==1) { */
                   9961: /*     free_ivector(popage,0,AGESUP); */
                   9962: /*     free_vector(popeffectif,0,AGESUP); */
                   9963: /*     free_vector(popcount,0,AGESUP); */
                   9964: /*   } */
                   9965: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9966: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9967: /*   fclose(ficrespop); */
                   9968: /* } /\* End of popforecast *\/ */
1.218     brouard  9969:  
1.126     brouard  9970: int fileappend(FILE *fichier, char *optionfich)
                   9971: {
                   9972:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   9973:     printf("Problem with file: %s\n", optionfich);
                   9974:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   9975:     return (0);
                   9976:   }
                   9977:   fflush(fichier);
                   9978:   return (1);
                   9979: }
                   9980: 
                   9981: 
                   9982: /**************** function prwizard **********************/
                   9983: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   9984: {
                   9985: 
                   9986:   /* Wizard to print covariance matrix template */
                   9987: 
1.164     brouard  9988:   char ca[32], cb[32];
                   9989:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  9990:   int numlinepar;
                   9991: 
                   9992:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9993:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9994:   for(i=1; i <=nlstate; i++){
                   9995:     jj=0;
                   9996:     for(j=1; j <=nlstate+ndeath; j++){
                   9997:       if(j==i) continue;
                   9998:       jj++;
                   9999:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   10000:       printf("%1d%1d",i,j);
                   10001:       fprintf(ficparo,"%1d%1d",i,j);
                   10002:       for(k=1; k<=ncovmodel;k++){
                   10003:        /*        printf(" %lf",param[i][j][k]); */
                   10004:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   10005:        printf(" 0.");
                   10006:        fprintf(ficparo," 0.");
                   10007:       }
                   10008:       printf("\n");
                   10009:       fprintf(ficparo,"\n");
                   10010:     }
                   10011:   }
                   10012:   printf("# Scales (for hessian or gradient estimation)\n");
                   10013:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   10014:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   10015:   for(i=1; i <=nlstate; i++){
                   10016:     jj=0;
                   10017:     for(j=1; j <=nlstate+ndeath; j++){
                   10018:       if(j==i) continue;
                   10019:       jj++;
                   10020:       fprintf(ficparo,"%1d%1d",i,j);
                   10021:       printf("%1d%1d",i,j);
                   10022:       fflush(stdout);
                   10023:       for(k=1; k<=ncovmodel;k++){
                   10024:        /*      printf(" %le",delti3[i][j][k]); */
                   10025:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   10026:        printf(" 0.");
                   10027:        fprintf(ficparo," 0.");
                   10028:       }
                   10029:       numlinepar++;
                   10030:       printf("\n");
                   10031:       fprintf(ficparo,"\n");
                   10032:     }
                   10033:   }
                   10034:   printf("# Covariance matrix\n");
                   10035: /* # 121 Var(a12)\n\ */
                   10036: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10037: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10038: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10039: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10040: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10041: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10042: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10043:   fflush(stdout);
                   10044:   fprintf(ficparo,"# Covariance matrix\n");
                   10045:   /* # 121 Var(a12)\n\ */
                   10046:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10047:   /* #   ...\n\ */
                   10048:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   10049:   
                   10050:   for(itimes=1;itimes<=2;itimes++){
                   10051:     jj=0;
                   10052:     for(i=1; i <=nlstate; i++){
                   10053:       for(j=1; j <=nlstate+ndeath; j++){
                   10054:        if(j==i) continue;
                   10055:        for(k=1; k<=ncovmodel;k++){
                   10056:          jj++;
                   10057:          ca[0]= k+'a'-1;ca[1]='\0';
                   10058:          if(itimes==1){
                   10059:            printf("#%1d%1d%d",i,j,k);
                   10060:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   10061:          }else{
                   10062:            printf("%1d%1d%d",i,j,k);
                   10063:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   10064:            /*  printf(" %.5le",matcov[i][j]); */
                   10065:          }
                   10066:          ll=0;
                   10067:          for(li=1;li <=nlstate; li++){
                   10068:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   10069:              if(lj==li) continue;
                   10070:              for(lk=1;lk<=ncovmodel;lk++){
                   10071:                ll++;
                   10072:                if(ll<=jj){
                   10073:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   10074:                  if(ll<jj){
                   10075:                    if(itimes==1){
                   10076:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10077:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10078:                    }else{
                   10079:                      printf(" 0.");
                   10080:                      fprintf(ficparo," 0.");
                   10081:                    }
                   10082:                  }else{
                   10083:                    if(itimes==1){
                   10084:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   10085:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   10086:                    }else{
                   10087:                      printf(" 0.");
                   10088:                      fprintf(ficparo," 0.");
                   10089:                    }
                   10090:                  }
                   10091:                }
                   10092:              } /* end lk */
                   10093:            } /* end lj */
                   10094:          } /* end li */
                   10095:          printf("\n");
                   10096:          fprintf(ficparo,"\n");
                   10097:          numlinepar++;
                   10098:        } /* end k*/
                   10099:       } /*end j */
                   10100:     } /* end i */
                   10101:   } /* end itimes */
                   10102: 
                   10103: } /* end of prwizard */
                   10104: /******************* Gompertz Likelihood ******************************/
                   10105: double gompertz(double x[])
                   10106: { 
1.302     brouard  10107:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  10108:   int i,n=0; /* n is the size of the sample */
                   10109: 
1.220     brouard  10110:   for (i=1;i<=imx ; i++) {
1.126     brouard  10111:     sump=sump+weight[i];
                   10112:     /*    sump=sump+1;*/
                   10113:     num=num+1;
                   10114:   }
1.302     brouard  10115:   L=0.0;
                   10116:   /* agegomp=AGEGOMP; */
1.126     brouard  10117:   /* for (i=0; i<=imx; i++) 
                   10118:      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]);*/
                   10119: 
1.302     brouard  10120:   for (i=1;i<=imx ; i++) {
                   10121:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   10122:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   10123:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   10124:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   10125:      * +
                   10126:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   10127:      */
                   10128:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   10129:        if (cens[i] == 1){
                   10130:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   10131:        } else if (cens[i] == 0){
1.126     brouard  10132:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  10133:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   10134:       } else
                   10135:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  10136:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  10137:        L=L+A*weight[i];
1.126     brouard  10138:        /*      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  10139:      }
                   10140:   }
1.126     brouard  10141: 
1.302     brouard  10142:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  10143:  
                   10144:   return -2*L*num/sump;
                   10145: }
                   10146: 
1.136     brouard  10147: #ifdef GSL
                   10148: /******************* Gompertz_f Likelihood ******************************/
                   10149: double gompertz_f(const gsl_vector *v, void *params)
                   10150: { 
1.302     brouard  10151:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  10152:   double *x= (double *) v->data;
                   10153:   int i,n=0; /* n is the size of the sample */
                   10154: 
                   10155:   for (i=0;i<=imx-1 ; i++) {
                   10156:     sump=sump+weight[i];
                   10157:     /*    sump=sump+1;*/
                   10158:     num=num+1;
                   10159:   }
                   10160:  
                   10161:  
                   10162:   /* for (i=0; i<=imx; i++) 
                   10163:      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]);*/
                   10164:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   10165:   for (i=1;i<=imx ; i++)
                   10166:     {
                   10167:       if (cens[i] == 1 && wav[i]>1)
                   10168:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   10169:       
                   10170:       if (cens[i] == 0 && wav[i]>1)
                   10171:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   10172:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   10173:       
                   10174:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   10175:       if (wav[i] > 1 ) { /* ??? */
                   10176:        LL=LL+A*weight[i];
                   10177:        /*      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]);*/
                   10178:       }
                   10179:     }
                   10180: 
                   10181:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   10182:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   10183:  
                   10184:   return -2*LL*num/sump;
                   10185: }
                   10186: #endif
                   10187: 
1.126     brouard  10188: /******************* Printing html file ***********/
1.201     brouard  10189: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  10190:                  int lastpass, int stepm, int weightopt, char model[],\
                   10191:                  int imx,  double p[],double **matcov,double agemortsup){
                   10192:   int i,k;
                   10193: 
                   10194:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   10195:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   10196:   for (i=1;i<=2;i++) 
                   10197:     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  10198:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  10199:   fprintf(fichtm,"</ul>");
                   10200: 
                   10201: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   10202: 
                   10203:  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>");
                   10204: 
                   10205:  for (k=agegomp;k<(agemortsup-2);k++) 
                   10206:    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]);
                   10207: 
                   10208:  
                   10209:   fflush(fichtm);
                   10210: }
                   10211: 
                   10212: /******************* Gnuplot file **************/
1.201     brouard  10213: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  10214: 
                   10215:   char dirfileres[132],optfileres[132];
1.164     brouard  10216: 
1.126     brouard  10217:   int ng;
                   10218: 
                   10219: 
                   10220:   /*#ifdef windows */
                   10221:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   10222:     /*#endif */
                   10223: 
                   10224: 
                   10225:   strcpy(dirfileres,optionfilefiname);
                   10226:   strcpy(optfileres,"vpl");
1.199     brouard  10227:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  10228:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  10229:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  10230:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  10231:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   10232: 
                   10233: } 
                   10234: 
1.136     brouard  10235: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   10236: {
1.126     brouard  10237: 
1.136     brouard  10238:   /*-------- data file ----------*/
                   10239:   FILE *fic;
                   10240:   char dummy[]="                         ";
1.240     brouard  10241:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  10242:   int lstra;
1.136     brouard  10243:   int linei, month, year,iout;
1.302     brouard  10244:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  10245:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  10246:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  10247:   char *stratrunc;
1.223     brouard  10248: 
1.240     brouard  10249:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   10250:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.328     brouard  10251:   for(v=1;v<NCOVMAX;v++){
                   10252:     DummyV[v]=0;
                   10253:     FixedV[v]=0;
                   10254:   }
1.126     brouard  10255: 
1.240     brouard  10256:   for(v=1; v <=ncovcol;v++){
                   10257:     DummyV[v]=0;
                   10258:     FixedV[v]=0;
                   10259:   }
                   10260:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   10261:     DummyV[v]=1;
                   10262:     FixedV[v]=0;
                   10263:   }
                   10264:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   10265:     DummyV[v]=0;
                   10266:     FixedV[v]=1;
                   10267:   }
                   10268:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   10269:     DummyV[v]=1;
                   10270:     FixedV[v]=1;
                   10271:   }
                   10272:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   10273:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   10274:     fprintf(ficlog,"Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   10275:   }
1.339     brouard  10276:   
                   10277:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
                   10278:   
1.136     brouard  10279:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  10280:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10281:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  10282:   }
1.126     brouard  10283: 
1.302     brouard  10284:     /* Is it a BOM UTF-8 Windows file? */
                   10285:   /* First data line */
                   10286:   linei=0;
                   10287:   while(fgets(line, MAXLINE, fic)) {
                   10288:     noffset=0;
                   10289:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   10290:     {
                   10291:       noffset=noffset+3;
                   10292:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   10293:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   10294:       fflush(ficlog); return 1;
                   10295:     }
                   10296:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   10297:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   10298:     {
                   10299:       noffset=noffset+2;
1.304     brouard  10300:       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);
                   10301:       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  10302:       fflush(ficlog); return 1;
                   10303:     }
                   10304:     else if( line[0] == 0 && line[1] == 0)
                   10305:     {
                   10306:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   10307:        noffset=noffset+4;
1.304     brouard  10308:        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);
                   10309:        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  10310:        fflush(ficlog); return 1;
                   10311:       }
                   10312:     } else{
                   10313:       ;/*printf(" Not a BOM file\n");*/
                   10314:     }
                   10315:         /* If line starts with a # it is a comment */
                   10316:     if (line[noffset] == '#') {
                   10317:       linei=linei+1;
                   10318:       break;
                   10319:     }else{
                   10320:       break;
                   10321:     }
                   10322:   }
                   10323:   fclose(fic);
                   10324:   if((fic=fopen(datafile,"r"))==NULL)    {
                   10325:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10326:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   10327:   }
                   10328:   /* Not a Bom file */
                   10329:   
1.136     brouard  10330:   i=1;
                   10331:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   10332:     linei=linei+1;
                   10333:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   10334:       if(line[j] == '\t')
                   10335:        line[j] = ' ';
                   10336:     }
                   10337:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   10338:       ;
                   10339:     };
                   10340:     line[j+1]=0;  /* Trims blanks at end of line */
                   10341:     if(line[0]=='#'){
                   10342:       fprintf(ficlog,"Comment line\n%s\n",line);
                   10343:       printf("Comment line\n%s\n",line);
                   10344:       continue;
                   10345:     }
                   10346:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  10347:     strcpy(line, linetmp);
1.223     brouard  10348:     
                   10349:     /* Loops on waves */
                   10350:     for (j=maxwav;j>=1;j--){
                   10351:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  10352:        cutv(stra, strb, line, ' '); 
                   10353:        if(strb[0]=='.') { /* Missing value */
                   10354:          lval=-1;
                   10355:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
1.341   ! brouard  10356:          cotvar[j][ncovcol+nqv+ntv+iv][i]=-1; /* For performance reasons */
1.238     brouard  10357:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   10358:            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);
                   10359:            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);
                   10360:            return 1;
                   10361:          }
                   10362:        }else{
                   10363:          errno=0;
                   10364:          /* what_kind_of_number(strb); */
                   10365:          dval=strtod(strb,&endptr); 
                   10366:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   10367:          /* if(strb != endptr && *endptr == '\0') */
                   10368:          /*    dval=dlval; */
                   10369:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10370:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10371:            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);
                   10372:            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);
                   10373:            return 1;
                   10374:          }
                   10375:          cotqvar[j][iv][i]=dval; 
1.341   ! brouard  10376:          cotvar[j][ncovcol+nqv+ntv+iv][i]=dval; /* because cotvar starts now at first ntv */ 
1.238     brouard  10377:        }
                   10378:        strcpy(line,stra);
1.223     brouard  10379:       }/* end loop ntqv */
1.225     brouard  10380:       
1.223     brouard  10381:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  10382:        cutv(stra, strb, line, ' '); 
                   10383:        if(strb[0]=='.') { /* Missing value */
                   10384:          lval=-1;
                   10385:        }else{
                   10386:          errno=0;
                   10387:          lval=strtol(strb,&endptr,10); 
                   10388:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10389:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10390:            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);
                   10391:            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);
                   10392:            return 1;
                   10393:          }
                   10394:        }
                   10395:        if(lval <-1 || lval >1){
                   10396:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10397:  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  10398:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10399:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10400:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10401:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10402:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10403:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10404:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  10405:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10406:  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  10407:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10408:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10409:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10410:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10411:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10412:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10413:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  10414:          return 1;
                   10415:        }
1.341   ! brouard  10416:        cotvar[j][ncovcol+nqv+iv][i]=(double)(lval);
1.238     brouard  10417:        strcpy(line,stra);
1.223     brouard  10418:       }/* end loop ntv */
1.225     brouard  10419:       
1.223     brouard  10420:       /* Statuses  at wave */
1.137     brouard  10421:       cutv(stra, strb, line, ' '); 
1.223     brouard  10422:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  10423:        lval=-1;
1.136     brouard  10424:       }else{
1.238     brouard  10425:        errno=0;
                   10426:        lval=strtol(strb,&endptr,10); 
                   10427:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10428:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10429:          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);
                   10430:          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);
                   10431:          return 1;
                   10432:        }
1.136     brouard  10433:       }
1.225     brouard  10434:       
1.136     brouard  10435:       s[j][i]=lval;
1.225     brouard  10436:       
1.223     brouard  10437:       /* Date of Interview */
1.136     brouard  10438:       strcpy(line,stra);
                   10439:       cutv(stra, strb,line,' ');
1.169     brouard  10440:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10441:       }
1.169     brouard  10442:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  10443:        month=99;
                   10444:        year=9999;
1.136     brouard  10445:       }else{
1.225     brouard  10446:        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);
                   10447:        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);
                   10448:        return 1;
1.136     brouard  10449:       }
                   10450:       anint[j][i]= (double) year; 
1.302     brouard  10451:       mint[j][i]= (double)month;
                   10452:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   10453:       /*       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]); */
                   10454:       /*       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]); */
                   10455:       /* } */
1.136     brouard  10456:       strcpy(line,stra);
1.223     brouard  10457:     } /* End loop on waves */
1.225     brouard  10458:     
1.223     brouard  10459:     /* Date of death */
1.136     brouard  10460:     cutv(stra, strb,line,' '); 
1.169     brouard  10461:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10462:     }
1.169     brouard  10463:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  10464:       month=99;
                   10465:       year=9999;
                   10466:     }else{
1.141     brouard  10467:       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  10468:       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);
                   10469:       return 1;
1.136     brouard  10470:     }
                   10471:     andc[i]=(double) year; 
                   10472:     moisdc[i]=(double) month; 
                   10473:     strcpy(line,stra);
                   10474:     
1.223     brouard  10475:     /* Date of birth */
1.136     brouard  10476:     cutv(stra, strb,line,' '); 
1.169     brouard  10477:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10478:     }
1.169     brouard  10479:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  10480:       month=99;
                   10481:       year=9999;
                   10482:     }else{
1.141     brouard  10483:       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);
                   10484:       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  10485:       return 1;
1.136     brouard  10486:     }
                   10487:     if (year==9999) {
1.141     brouard  10488:       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);
                   10489:       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  10490:       return 1;
                   10491:       
1.136     brouard  10492:     }
                   10493:     annais[i]=(double)(year);
1.302     brouard  10494:     moisnais[i]=(double)(month);
                   10495:     for (j=1;j<=maxwav;j++){
                   10496:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   10497:        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]);
                   10498:        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]);
                   10499:       }
                   10500:     }
                   10501: 
1.136     brouard  10502:     strcpy(line,stra);
1.225     brouard  10503:     
1.223     brouard  10504:     /* Sample weight */
1.136     brouard  10505:     cutv(stra, strb,line,' '); 
                   10506:     errno=0;
                   10507:     dval=strtod(strb,&endptr); 
                   10508:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  10509:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   10510:       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  10511:       fflush(ficlog);
                   10512:       return 1;
                   10513:     }
                   10514:     weight[i]=dval; 
                   10515:     strcpy(line,stra);
1.225     brouard  10516:     
1.223     brouard  10517:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   10518:       cutv(stra, strb, line, ' '); 
                   10519:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  10520:        lval=-1;
1.311     brouard  10521:        coqvar[iv][i]=NAN; 
                   10522:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10523:       }else{
1.225     brouard  10524:        errno=0;
                   10525:        /* what_kind_of_number(strb); */
                   10526:        dval=strtod(strb,&endptr);
                   10527:        /* if(strb != endptr && *endptr == '\0') */
                   10528:        /*   dval=dlval; */
                   10529:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10530:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10531:          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);
                   10532:          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);
                   10533:          return 1;
                   10534:        }
                   10535:        coqvar[iv][i]=dval; 
1.226     brouard  10536:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10537:       }
                   10538:       strcpy(line,stra);
                   10539:     }/* end loop nqv */
1.136     brouard  10540:     
1.223     brouard  10541:     /* Covariate values */
1.136     brouard  10542:     for (j=ncovcol;j>=1;j--){
                   10543:       cutv(stra, strb,line,' '); 
1.223     brouard  10544:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  10545:        lval=-1;
1.136     brouard  10546:       }else{
1.225     brouard  10547:        errno=0;
                   10548:        lval=strtol(strb,&endptr,10); 
                   10549:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10550:          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);
                   10551:          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);
                   10552:          return 1;
                   10553:        }
1.136     brouard  10554:       }
                   10555:       if(lval <-1 || lval >1){
1.225     brouard  10556:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10557:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10558:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10559:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10560:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10561:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10562:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10563:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10564:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  10565:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10566:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10567:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10568:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10569:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10570:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10571:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10572:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10573:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  10574:        return 1;
1.136     brouard  10575:       }
                   10576:       covar[j][i]=(double)(lval);
                   10577:       strcpy(line,stra);
                   10578:     }  
                   10579:     lstra=strlen(stra);
1.225     brouard  10580:     
1.136     brouard  10581:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   10582:       stratrunc = &(stra[lstra-9]);
                   10583:       num[i]=atol(stratrunc);
                   10584:     }
                   10585:     else
                   10586:       num[i]=atol(stra);
                   10587:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   10588:       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;}*/
                   10589:     
                   10590:     i=i+1;
                   10591:   } /* End loop reading  data */
1.225     brouard  10592:   
1.136     brouard  10593:   *imax=i-1; /* Number of individuals */
                   10594:   fclose(fic);
1.225     brouard  10595:   
1.136     brouard  10596:   return (0);
1.164     brouard  10597:   /* endread: */
1.225     brouard  10598:   printf("Exiting readdata: ");
                   10599:   fclose(fic);
                   10600:   return (1);
1.223     brouard  10601: }
1.126     brouard  10602: 
1.234     brouard  10603: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  10604:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  10605:   while (*p2 == ' ')
1.234     brouard  10606:     p2++; 
                   10607:   /* while ((*p1++ = *p2++) !=0) */
                   10608:   /*   ; */
                   10609:   /* do */
                   10610:   /*   while (*p2 == ' ') */
                   10611:   /*     p2++; */
                   10612:   /* while (*p1++ == *p2++); */
                   10613:   *stri=p2; 
1.145     brouard  10614: }
                   10615: 
1.330     brouard  10616: int decoderesult( char resultline[], int nres)
1.230     brouard  10617: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   10618: {
1.235     brouard  10619:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  10620:   char resultsav[MAXLINE];
1.330     brouard  10621:   /* int resultmodel[MAXLINE]; */
1.334     brouard  10622:   /* int modelresult[MAXLINE]; */
1.230     brouard  10623:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   10624: 
1.234     brouard  10625:   removefirstspace(&resultline);
1.332     brouard  10626:   printf("decoderesult:%s\n",resultline);
1.230     brouard  10627: 
1.332     brouard  10628:   strcpy(resultsav,resultline);
                   10629:   printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline);
1.230     brouard  10630:   if (strlen(resultsav) >1){
1.334     brouard  10631:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  10632:   }
1.253     brouard  10633:   if(j == 0){ /* Resultline but no = */
                   10634:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   10635:     return (0);
                   10636:   }
1.234     brouard  10637:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.334     brouard  10638:     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, %s.\n",j, cptcovs, model);
                   10639:     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, %s.\n",j, cptcovs, model);
1.332     brouard  10640:     /* return 1;*/
1.234     brouard  10641:   }
1.334     brouard  10642:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  10643:     if(nbocc(resultsav,'=') >1){
1.318     brouard  10644:       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  10645:       /* 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  10646:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  10647:       /* If a blank, then strc="V4=" and strd='\0' */
                   10648:       if(strc[0]=='\0'){
                   10649:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   10650:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   10651:        return 1;
                   10652:       }
1.234     brouard  10653:     }else
                   10654:       cutl(strc,strd,resultsav,'=');
1.318     brouard  10655:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  10656:     
1.230     brouard  10657:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  10658:     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  10659:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   10660:     /* cptcovsel++;     */
                   10661:     if (nbocc(stra,'=') >0)
                   10662:       strcpy(resultsav,stra); /* and analyzes it */
                   10663:   }
1.235     brouard  10664:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10665:   /* 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  10666:   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  10667:     if(Typevar[k1]==0){ /* Single covariate in model */
                   10668:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  10669:       match=0;
1.318     brouard  10670:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10671:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  10672:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  10673:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  10674:          break;
                   10675:        }
                   10676:       }
                   10677:       if(match == 0){
1.338     brouard  10678:        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]);
                   10679:        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  10680:        return 1;
1.234     brouard  10681:       }
1.332     brouard  10682:     }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*/
                   10683:       /* We feed resultmodel[k1]=k2; */
                   10684:       match=0;
                   10685:       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 */
                   10686:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  10687:          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  10688:          resultmodel[nres][k1]=k2; /* Added here */
                   10689:          printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]);
                   10690:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10691:          break;
                   10692:        }
                   10693:       }
                   10694:       if(match == 0){
1.338     brouard  10695:        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]);
                   10696:        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  10697:       return 1;
                   10698:       }
                   10699:     }else if(Typevar[k1]==2){ /* Product No age We want to get the position in the resultline of the product in the model line*/
                   10700:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   10701:       match=0;
                   10702:       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]);
                   10703:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10704:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10705:          /* modelresult[k2]=k1; */
                   10706:          printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]);
                   10707:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10708:        }
                   10709:       }
                   10710:       if(match == 0){
1.338     brouard  10711:        printf("Error in result line (Product without age first variable): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][1], resultline, model);
                   10712:        fprintf(ficlog,"Error in result line (Product without age first variable): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][1], resultline, model);
1.332     brouard  10713:        return 1;
                   10714:       }
                   10715:       match=0;
                   10716:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10717:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10718:          /* modelresult[k2]=k1;*/
                   10719:          printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]);
                   10720:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10721:          break;
                   10722:        }
                   10723:       }
                   10724:       if(match == 0){
1.338     brouard  10725:        printf("Error in result line (Product without age second variable): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][2], resultline, model);
                   10726:        fprintf(ficlog,"Error in result line (Product without age second variable): V%d is missing in result : %s according to model=1+age+%s\n",Tvardk[k1][2], resultline, model);
1.332     brouard  10727:        return 1;
                   10728:       }
                   10729:     }/* End of testing */
1.333     brouard  10730:   }/* End loop cptcovt */
1.235     brouard  10731:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10732:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  10733:   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)
                   10734:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  10735:     match=0;
1.318     brouard  10736:     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  10737:       if(Typevar[k1]==0){ /* Single only */
1.237     brouard  10738:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.330     brouard  10739:          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  10740:          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  10741:          ++match;
                   10742:        }
                   10743:       }
                   10744:     }
                   10745:     if(match == 0){
1.338     brouard  10746:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   10747:       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  10748:       return 1;
1.234     brouard  10749:     }else if(match > 1){
1.338     brouard  10750:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   10751:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
1.310     brouard  10752:       return 1;
1.234     brouard  10753:     }
                   10754:   }
1.334     brouard  10755:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  10756:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  10757:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  10758:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   10759:   /* 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*/
                   10760:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  10761:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   10762:   /*    1 0 0 0 */
                   10763:   /*    2 1 0 0 */
                   10764:   /*    3 0 1 0 */ 
1.330     brouard  10765:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  10766:   /*    5 0 0 1 */
1.330     brouard  10767:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  10768:   /*    7 0 1 1 */
                   10769:   /*    8 1 1 1 */
1.237     brouard  10770:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   10771:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   10772:   /* V5*age V5 known which value for nres?  */
                   10773:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  10774:   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.
                   10775:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  10776:     /* k counting number of combination of single dummies in the equation model */
                   10777:     /* k4 counting single dummies in the equation model */
                   10778:     /* k4q counting single quantitatives in the equation model */
1.334     brouard  10779:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Dummy and Single, k1 is sorting according to MODEL, but k3 to resultline */
                   10780:        /* 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  10781:       /* 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  10782:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  10783:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   10784:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   10785:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   10786:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   10787:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  10788:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  10789:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  10790:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  10791:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   10792:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   10793:       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  10794:       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  10795:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  10796:       /* Tinvresult[nres][4]=1 */
1.334     brouard  10797:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   10798:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   10799:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   10800:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  10801:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  10802:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.332     brouard  10803:       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  10804:       k4++;;
1.331     brouard  10805:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  10806:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  10807:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  10808:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  10809:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   10810:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   10811:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  10812:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   10813:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   10814:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   10815:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   10816:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   10817:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  10818:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  10819:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  10820:       precov[nres][k1]=Tvalsel[k3q];
                   10821:       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  10822:       k4q++;;
1.331     brouard  10823:     }else if( Dummy[k1]==2 ){ /* For dummy with age product */
                   10824:       /* Tvar[k1]; */ /* Age variable */
1.332     brouard  10825:       /* Wrong we want the value of variable name Tvar[k1] */
                   10826:       
                   10827:       k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
1.331     brouard  10828:       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)*/
1.334     brouard  10829:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
1.332     brouard  10830:       precov[nres][k1]=Tvalsel[k3];
                   10831:       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  10832:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.332     brouard  10833:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
1.331     brouard  10834:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  10835:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
1.332     brouard  10836:       precov[nres][k1]=Tvalsel[k3q];
1.334     brouard  10837:       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.331     brouard  10838:     }else if(Typevar[k1]==2 ){ /* For product quant or dummy (not with age) */
1.332     brouard  10839:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   10840:       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  10841:     }else{
1.332     brouard  10842:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   10843:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  10844:     }
                   10845:   }
1.234     brouard  10846:   
1.334     brouard  10847:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  10848:   return (0);
                   10849: }
1.235     brouard  10850: 
1.230     brouard  10851: int decodemodel( char model[], int lastobs)
                   10852:  /**< This routine decodes the model and returns:
1.224     brouard  10853:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   10854:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   10855:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   10856:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   10857:        * - cptcovage number of covariates with age*products =2
                   10858:        * - cptcovs number of simple covariates
1.339     brouard  10859:        * ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
1.224     brouard  10860:        * - 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  10861:        *     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
1.319     brouard  10862:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  10863:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   10864:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   10865:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   10866:        */
1.319     brouard  10867: /* 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  10868: {
1.238     brouard  10869:   int i, j, k, ks, v;
1.227     brouard  10870:   int  j1, k1, k2, k3, k4;
1.136     brouard  10871:   char modelsav[80];
1.145     brouard  10872:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  10873:   char *strpt;
1.136     brouard  10874: 
1.145     brouard  10875:   /*removespace(model);*/
1.136     brouard  10876:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  10877:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  10878:     if (strstr(model,"AGE") !=0){
1.192     brouard  10879:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   10880:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  10881:       return 1;
                   10882:     }
1.141     brouard  10883:     if (strstr(model,"v") !=0){
1.338     brouard  10884:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
                   10885:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
1.141     brouard  10886:       return 1;
                   10887:     }
1.187     brouard  10888:     strcpy(modelsav,model); 
                   10889:     if ((strpt=strstr(model,"age*age")) !=0){
1.338     brouard  10890:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
1.187     brouard  10891:       if(strpt != model){
1.338     brouard  10892:        printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10893:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10894:  corresponding column of parameters.\n",model);
1.338     brouard  10895:        fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10896:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10897:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  10898:        return 1;
1.225     brouard  10899:       }
1.187     brouard  10900:       nagesqr=1;
                   10901:       if (strstr(model,"+age*age") !=0)
1.234     brouard  10902:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  10903:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  10904:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  10905:       else 
1.234     brouard  10906:        substrchaine(modelsav, model, "age*age");
1.187     brouard  10907:     }else
                   10908:       nagesqr=0;
                   10909:     if (strlen(modelsav) >1){
                   10910:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   10911:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  10912:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  10913:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  10914:                     * cst, age and age*age 
                   10915:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   10916:       /* including age products which are counted in cptcovage.
                   10917:        * but the covariates which are products must be treated 
                   10918:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  10919:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   10920:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  10921:       
                   10922:       
1.187     brouard  10923:       /*   Design
                   10924:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   10925:        *  <          ncovcol=8                >
                   10926:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   10927:        *   k=  1    2      3       4     5       6      7        8
                   10928:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   10929:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  10930:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   10931:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  10932:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   10933:        *  Tage[++cptcovage]=k
                   10934:        *       if products, new covar are created after ncovcol with k1
                   10935:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   10936:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   10937:        *  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
                   10938:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   10939:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   10940:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   10941:        *  <          ncovcol=8                >
                   10942:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   10943:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   10944:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
1.319     brouard  10945:        * p Tvar[1]@12={2,   1,     3,      3,  11,     10,     8,       8,   7,   8,   5,  6}
1.187     brouard  10946:        * p Tprod[1]@2={                         6, 5}
                   10947:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   10948:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   10949:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  10950:        *How to reorganize? Tvars(orted)
1.187     brouard  10951:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   10952:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   10953:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   10954:        * Struct []
                   10955:        */
1.225     brouard  10956:       
1.187     brouard  10957:       /* This loop fills the array Tvar from the string 'model'.*/
                   10958:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   10959:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   10960:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   10961:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   10962:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   10963:       /*       k=1 Tvar[1]=2 (from V2) */
                   10964:       /*       k=5 Tvar[5] */
                   10965:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  10966:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  10967:       /*       } */
1.198     brouard  10968:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  10969:       /*
                   10970:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  10971:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   10972:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   10973:       }
1.187     brouard  10974:       cptcovage=0;
1.319     brouard  10975:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   10976:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   10977:                                         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" */
                   10978:        if (nbocc(modelsav,'+')==0)
                   10979:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  10980:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   10981:        /*scanf("%d",i);*/
1.319     brouard  10982:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V5*age+ V4+V3*age strb=V3*age */
                   10983:          cutl(strc,strd,strb,'*'); /**< k=1 strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
1.234     brouard  10984:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   10985:            /* covar is not filled and then is empty */
                   10986:            cptcovprod--;
                   10987:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
1.319     brouard  10988:            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 */
1.234     brouard  10989:            Typevar[k]=1;  /* 1 for age product */
1.319     brouard  10990:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   10991:            Tage[cptcovage]=k;  /*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
1.234     brouard  10992:            /*printf("stre=%s ", stre);*/
                   10993:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   10994:            cptcovprod--;
                   10995:            cutl(stre,strb,strc,'V');
                   10996:            Tvar[k]=atoi(stre);
                   10997:            Typevar[k]=1;  /* 1 for age product */
                   10998:            cptcovage++;
                   10999:            Tage[cptcovage]=k;
                   11000:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   11001:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   11002:            cptcovn++;
                   11003:            cptcovprodnoage++;k1++;
                   11004:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
1.339     brouard  11005:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
1.234     brouard  11006:                                                because this model-covariate is a construction we invent a new column
                   11007:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
1.335     brouard  11008:                                                If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
1.319     brouard  11009:                                                thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
1.339     brouard  11010:                                                Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
1.335     brouard  11011:            /* Please remark that the new variables are model dependent */
                   11012:            /* If we have 4 variable but the model uses only 3, like in
                   11013:             * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   11014:             *  k=     1     2       3   4     5        6        7       8
                   11015:             * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   11016:             * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   11017:             * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   11018:             */
1.339     brouard  11019:            Typevar[k]=2;  /* 2 for product */
1.234     brouard  11020:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   11021:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.319     brouard  11022:            Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
1.234     brouard  11023:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
1.330     brouard  11024:            Tvardk[k][1] =atoi(strc); /* m 1 for V1*/
1.234     brouard  11025:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
1.330     brouard  11026:            Tvardk[k][2] =atoi(stre); /* n 4 for V4*/
1.234     brouard  11027:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   11028:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   11029:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  11030:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  11031:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
1.339     brouard  11032:            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 */
                   11033:              for (i=1; i<=lastobs;i++){/* For fixed product */
1.234     brouard  11034:              /* Computes the new covariate which is a product of
                   11035:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.339     brouard  11036:              covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   11037:              }
                   11038:            } /*End of FixedV */
1.234     brouard  11039:          } /* End age is not in the model */
                   11040:        } /* End if model includes a product */
1.319     brouard  11041:        else { /* not a product */
1.234     brouard  11042:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   11043:          /*  scanf("%d",i);*/
                   11044:          cutl(strd,strc,strb,'V');
                   11045:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   11046:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   11047:          Tvar[k]=atoi(strd);
                   11048:          Typevar[k]=0;  /* 0 for simple covariates */
                   11049:        }
                   11050:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  11051:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  11052:                                  scanf("%d",i);*/
1.187     brouard  11053:       } /* end of loop + on total covariates */
                   11054:     } /* end if strlen(modelsave == 0) age*age might exist */
                   11055:   } /* end if strlen(model == 0) */
1.136     brouard  11056:   
                   11057:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   11058:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  11059:   
1.136     brouard  11060:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  11061:      printf("cptcovprod=%d ", cptcovprod);
                   11062:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   11063:      scanf("%d ",i);*/
                   11064: 
                   11065: 
1.230     brouard  11066: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   11067:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  11068: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   11069:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   11070:    k =           1    2   3     4       5       6      7      8        9
                   11071:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  11072:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  11073:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   11074:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   11075:          Tmodelind[combination of covar]=k;
1.225     brouard  11076: */  
                   11077: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  11078:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  11079:   /* 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  11080:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  11081:   printf("Model=1+age+%s\n\
1.227     brouard  11082: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   11083: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11084: 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  11085:   fprintf(ficlog,"Model=1+age+%s\n\
1.227     brouard  11086: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   11087: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11088: 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.285     brouard  11089:   for(k=-1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.339     brouard  11090:   for(k=1, ncovf=0, nsd=0, nsq=0, ncovv=0, ncova=0, ncoveff=0, nqfveff=0, ntveff=0, nqtveff=0, ncovvt=0;k<=cptcovt; k++){ /* or cptocvt */
1.234     brouard  11091:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  11092:       Fixed[k]= 0;
                   11093:       Dummy[k]= 0;
1.225     brouard  11094:       ncoveff++;
1.232     brouard  11095:       ncovf++;
1.234     brouard  11096:       nsd++;
                   11097:       modell[k].maintype= FTYPE;
                   11098:       TvarsD[nsd]=Tvar[k];
                   11099:       TvarsDind[nsd]=k;
1.330     brouard  11100:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  11101:       TvarF[ncovf]=Tvar[k];
                   11102:       TvarFind[ncovf]=k;
                   11103:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11104:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.339     brouard  11105:     /* }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /\* Product of fixed dummy (<=ncovcol) covariates For a fixed product k is higher than ncovcol *\/ */
                   11106:     }else if( Tposprod[k]>0  &&  Typevar[k]==2 && 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 */
1.234     brouard  11107:       Fixed[k]= 0;
                   11108:       Dummy[k]= 0;
                   11109:       ncoveff++;
                   11110:       ncovf++;
                   11111:       modell[k].maintype= FTYPE;
                   11112:       TvarF[ncovf]=Tvar[k];
1.330     brouard  11113:       /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
1.234     brouard  11114:       TvarFind[ncovf]=k;
1.230     brouard  11115:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  11116:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  11117:     }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  11118:       Fixed[k]= 0;
                   11119:       Dummy[k]= 1;
1.230     brouard  11120:       nqfveff++;
1.234     brouard  11121:       modell[k].maintype= FTYPE;
                   11122:       modell[k].subtype= FQ;
                   11123:       nsq++;
1.334     brouard  11124:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   11125:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  11126:       ncovf++;
1.234     brouard  11127:       TvarF[ncovf]=Tvar[k];
                   11128:       TvarFind[ncovf]=k;
1.231     brouard  11129:       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  11130:       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  11131:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.339     brouard  11132:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11133:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11134:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11135:       ncovvt++;
                   11136:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11137:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
                   11138: 
1.227     brouard  11139:       Fixed[k]= 1;
                   11140:       Dummy[k]= 0;
1.225     brouard  11141:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  11142:       modell[k].maintype= VTYPE;
                   11143:       modell[k].subtype= VD;
                   11144:       nsd++;
                   11145:       TvarsD[nsd]=Tvar[k];
                   11146:       TvarsDind[nsd]=k;
1.330     brouard  11147:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  11148:       ncovv++; /* Only simple time varying variables */
                   11149:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11150:       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  11151:       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 */
                   11152:       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  11153:       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);
                   11154:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  11155:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.339     brouard  11156:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11157:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11158:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11159:       ncovvt++;
                   11160:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11161:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11162:       
1.234     brouard  11163:       Fixed[k]= 1;
                   11164:       Dummy[k]= 1;
                   11165:       nqtveff++;
                   11166:       modell[k].maintype= VTYPE;
                   11167:       modell[k].subtype= VQ;
                   11168:       ncovv++; /* Only simple time varying variables */
                   11169:       nsq++;
1.334     brouard  11170:       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) */
                   11171:       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  11172:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11173:       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  11174:       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 */
                   11175:       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  11176:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   11177:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   11178:       printf("Quasi TmodelQind[%d]=%d,Tvar[TmodelQind[%d]]=V%d, ncovcol=%d, nqv=%d, ntv=%d,Tvar[k]- ncovcol-nqv-ntv=%d\n",nqtveff,k,nqtveff,Tvar[k], ncovcol, nqv, ntv, Tvar[k]- ncovcol-nqv-ntv);
1.228     brouard  11179:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  11180:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  11181:       ncova++;
                   11182:       TvarA[ncova]=Tvar[k];
                   11183:       TvarAind[ncova]=k;
1.231     brouard  11184:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  11185:        Fixed[k]= 2;
                   11186:        Dummy[k]= 2;
                   11187:        modell[k].maintype= ATYPE;
                   11188:        modell[k].subtype= APFD;
                   11189:        /* ncoveff++; */
1.227     brouard  11190:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  11191:        Fixed[k]= 2;
                   11192:        Dummy[k]= 3;
                   11193:        modell[k].maintype= ATYPE;
                   11194:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   11195:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  11196:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  11197:        Fixed[k]= 3;
                   11198:        Dummy[k]= 2;
                   11199:        modell[k].maintype= ATYPE;
                   11200:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   11201:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  11202:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  11203:        Fixed[k]= 3;
                   11204:        Dummy[k]= 3;
                   11205:        modell[k].maintype= ATYPE;
                   11206:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   11207:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  11208:       }
1.339     brouard  11209:     }else if (Typevar[k] == 2) {  /* product 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  */
                   11210:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11211:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11212:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11213:       k1=Tposprod[k];  /* Position in the products of product k, Tposprod={0, 0, 0, 0, 1} k1=1 first product but second time varying because of V3 */
                   11214:       ncovvt++;
                   11215:       TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   11216:       TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11217:       ncovvt++;
                   11218:       TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   11219:       TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11220: 
                   11221: 
                   11222:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   11223:        if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
1.240     brouard  11224:          Fixed[k]= 1;
                   11225:          Dummy[k]= 0;
                   11226:          modell[k].maintype= FTYPE;
                   11227:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   11228:          ncovf++; /* Fixed variables without age */
                   11229:          TvarF[ncovf]=Tvar[k];
                   11230:          TvarFind[ncovf]=k;
1.339     brouard  11231:        }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
                   11232:          Fixed[k]= 0;  /* Fixed product */
1.240     brouard  11233:          Dummy[k]= 1;
                   11234:          modell[k].maintype= FTYPE;
                   11235:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   11236:          ncovf++; /* Varying variables without age */
                   11237:          TvarF[ncovf]=Tvar[k];
                   11238:          TvarFind[ncovf]=k;
1.339     brouard  11239:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
1.240     brouard  11240:          Fixed[k]= 1;
                   11241:          Dummy[k]= 0;
                   11242:          modell[k].maintype= VTYPE;
                   11243:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   11244:          ncovv++; /* Varying variables without age */
1.339     brouard  11245:          TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   11246:          TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
                   11247:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
1.240     brouard  11248:          Fixed[k]= 1;
                   11249:          Dummy[k]= 1;
                   11250:          modell[k].maintype= VTYPE;
                   11251:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   11252:          ncovv++; /* Varying variables without age */
                   11253:          TvarV[ncovv]=Tvar[k];
                   11254:          TvarVind[ncovv]=k;
                   11255:        }
1.339     brouard  11256:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   11257:        if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
                   11258:          Fixed[k]= 0;  /*  Fixed product */
1.240     brouard  11259:          Dummy[k]= 1;
                   11260:          modell[k].maintype= FTYPE;
                   11261:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   11262:          ncovf++; /* Fixed variables without age */
                   11263:          TvarF[ncovf]=Tvar[k];
                   11264:          TvarFind[ncovf]=k;
1.339     brouard  11265:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
1.240     brouard  11266:          Fixed[k]= 1;
                   11267:          Dummy[k]= 1;
                   11268:          modell[k].maintype= VTYPE;
                   11269:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   11270:          ncovv++; /* Varying variables without age */
                   11271:          TvarV[ncovv]=Tvar[k];
                   11272:          TvarVind[ncovv]=k;
1.339     brouard  11273:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
1.240     brouard  11274:          Fixed[k]= 1;
                   11275:          Dummy[k]= 1;
                   11276:          modell[k].maintype= VTYPE;
                   11277:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   11278:          ncovv++; /* Varying variables without age */
                   11279:          TvarV[ncovv]=Tvar[k];
                   11280:          TvarVind[ncovv]=k;
                   11281:          ncovv++; /* Varying variables without age */
                   11282:          TvarV[ncovv]=Tvar[k];
                   11283:          TvarVind[ncovv]=k;
                   11284:        }
1.339     brouard  11285:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
1.240     brouard  11286:        if(Tvard[k1][2] <=ncovcol){
                   11287:          Fixed[k]= 1;
                   11288:          Dummy[k]= 1;
                   11289:          modell[k].maintype= VTYPE;
                   11290:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   11291:          ncovv++; /* Varying variables without age */
                   11292:          TvarV[ncovv]=Tvar[k];
                   11293:          TvarVind[ncovv]=k;
                   11294:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11295:          Fixed[k]= 1;
                   11296:          Dummy[k]= 1;
                   11297:          modell[k].maintype= VTYPE;
                   11298:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   11299:          ncovv++; /* Varying variables without age */
                   11300:          TvarV[ncovv]=Tvar[k];
                   11301:          TvarVind[ncovv]=k;
                   11302:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11303:          Fixed[k]= 1;
                   11304:          Dummy[k]= 0;
                   11305:          modell[k].maintype= VTYPE;
                   11306:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   11307:          ncovv++; /* Varying variables without age */
                   11308:          TvarV[ncovv]=Tvar[k];
                   11309:          TvarVind[ncovv]=k;
                   11310:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11311:          Fixed[k]= 1;
                   11312:          Dummy[k]= 1;
                   11313:          modell[k].maintype= VTYPE;
                   11314:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   11315:          ncovv++; /* Varying variables without age */
                   11316:          TvarV[ncovv]=Tvar[k];
                   11317:          TvarVind[ncovv]=k;
                   11318:        }
1.339     brouard  11319:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
1.240     brouard  11320:        if(Tvard[k1][2] <=ncovcol){
                   11321:          Fixed[k]= 1;
                   11322:          Dummy[k]= 1;
                   11323:          modell[k].maintype= VTYPE;
                   11324:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   11325:          ncovv++; /* Varying variables without age */
                   11326:          TvarV[ncovv]=Tvar[k];
                   11327:          TvarVind[ncovv]=k;
                   11328:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11329:          Fixed[k]= 1;
                   11330:          Dummy[k]= 1;
                   11331:          modell[k].maintype= VTYPE;
                   11332:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   11333:          ncovv++; /* Varying variables without age */
                   11334:          TvarV[ncovv]=Tvar[k];
                   11335:          TvarVind[ncovv]=k;
                   11336:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11337:          Fixed[k]= 1;
                   11338:          Dummy[k]= 1;
                   11339:          modell[k].maintype= VTYPE;
                   11340:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   11341:          ncovv++; /* Varying variables without age */
                   11342:          TvarV[ncovv]=Tvar[k];
                   11343:          TvarVind[ncovv]=k;
                   11344:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11345:          Fixed[k]= 1;
                   11346:          Dummy[k]= 1;
                   11347:          modell[k].maintype= VTYPE;
                   11348:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   11349:          ncovv++; /* Varying variables without age */
                   11350:          TvarV[ncovv]=Tvar[k];
                   11351:          TvarVind[ncovv]=k;
                   11352:        }
1.227     brouard  11353:       }else{
1.240     brouard  11354:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11355:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11356:       } /*end k1*/
1.225     brouard  11357:     }else{
1.226     brouard  11358:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   11359:       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  11360:     }
1.227     brouard  11361:     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]);
1.231     brouard  11362:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  11363:     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]);
                   11364:   }
                   11365:   /* Searching for doublons in the model */
                   11366:   for(k1=1; k1<= cptcovt;k1++){
                   11367:     for(k2=1; k2 <k1;k2++){
1.285     brouard  11368:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   11369:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  11370:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   11371:          if(Tvar[k1]==Tvar[k2]){
1.338     brouard  11372:            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]);
                   11373:            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  11374:            return(1);
                   11375:          }
                   11376:        }else if (Typevar[k1] ==2){
                   11377:          k3=Tposprod[k1];
                   11378:          k4=Tposprod[k2];
                   11379:          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  11380:            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]]);
                   11381:            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  11382:            return(1);
                   11383:          }
                   11384:        }
1.227     brouard  11385:       }
                   11386:     }
1.225     brouard  11387:   }
                   11388:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   11389:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  11390:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   11391:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  11392:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  11393:   /*endread:*/
1.225     brouard  11394:   printf("Exiting decodemodel: ");
                   11395:   return (1);
1.136     brouard  11396: }
                   11397: 
1.169     brouard  11398: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  11399: {/* Check ages at death */
1.136     brouard  11400:   int i, m;
1.218     brouard  11401:   int firstone=0;
                   11402:   
1.136     brouard  11403:   for (i=1; i<=imx; i++) {
                   11404:     for(m=2; (m<= maxwav); m++) {
                   11405:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   11406:        anint[m][i]=9999;
1.216     brouard  11407:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   11408:          s[m][i]=-1;
1.136     brouard  11409:       }
                   11410:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  11411:        *nberr = *nberr + 1;
1.218     brouard  11412:        if(firstone == 0){
                   11413:          firstone=1;
1.260     brouard  11414:        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  11415:        }
1.262     brouard  11416:        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  11417:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  11418:       }
                   11419:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  11420:        (*nberr)++;
1.259     brouard  11421:        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  11422:        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  11423:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  11424:       }
                   11425:     }
                   11426:   }
                   11427: 
                   11428:   for (i=1; i<=imx; i++)  {
                   11429:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   11430:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  11431:       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  11432:        if (s[m][i] >= nlstate+1) {
1.169     brouard  11433:          if(agedc[i]>0){
                   11434:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  11435:              agev[m][i]=agedc[i];
1.214     brouard  11436:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  11437:            }else {
1.136     brouard  11438:              if ((int)andc[i]!=9999){
                   11439:                nbwarn++;
                   11440:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   11441:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   11442:                agev[m][i]=-1;
                   11443:              }
                   11444:            }
1.169     brouard  11445:          } /* agedc > 0 */
1.214     brouard  11446:        } /* end if */
1.136     brouard  11447:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   11448:                                 years but with the precision of a month */
                   11449:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   11450:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   11451:            agev[m][i]=1;
                   11452:          else if(agev[m][i] < *agemin){ 
                   11453:            *agemin=agev[m][i];
                   11454:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   11455:          }
                   11456:          else if(agev[m][i] >*agemax){
                   11457:            *agemax=agev[m][i];
1.156     brouard  11458:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  11459:          }
                   11460:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   11461:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  11462:        } /* en if 9*/
1.136     brouard  11463:        else { /* =9 */
1.214     brouard  11464:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  11465:          agev[m][i]=1;
                   11466:          s[m][i]=-1;
                   11467:        }
                   11468:       }
1.214     brouard  11469:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  11470:        agev[m][i]=1;
1.214     brouard  11471:       else{
                   11472:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11473:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11474:        agev[m][i]=0;
                   11475:       }
                   11476:     } /* End for lastpass */
                   11477:   }
1.136     brouard  11478:     
                   11479:   for (i=1; i<=imx; i++)  {
                   11480:     for(m=firstpass; (m<=lastpass); m++){
                   11481:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  11482:        (*nberr)++;
1.136     brouard  11483:        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);     
                   11484:        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);     
                   11485:        return 1;
                   11486:       }
                   11487:     }
                   11488:   }
                   11489: 
                   11490:   /*for (i=1; i<=imx; i++){
                   11491:   for (m=firstpass; (m<lastpass); m++){
                   11492:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   11493: }
                   11494: 
                   11495: }*/
                   11496: 
                   11497: 
1.139     brouard  11498:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   11499:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  11500: 
                   11501:   return (0);
1.164     brouard  11502:  /* endread:*/
1.136     brouard  11503:     printf("Exiting calandcheckages: ");
                   11504:     return (1);
                   11505: }
                   11506: 
1.172     brouard  11507: #if defined(_MSC_VER)
                   11508: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11509: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11510: //#include "stdafx.h"
                   11511: //#include <stdio.h>
                   11512: //#include <tchar.h>
                   11513: //#include <windows.h>
                   11514: //#include <iostream>
                   11515: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   11516: 
                   11517: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11518: 
                   11519: BOOL IsWow64()
                   11520: {
                   11521:        BOOL bIsWow64 = FALSE;
                   11522: 
                   11523:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   11524:        //  (HANDLE, PBOOL);
                   11525: 
                   11526:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11527: 
                   11528:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   11529:        const char funcName[] = "IsWow64Process";
                   11530:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   11531:                GetProcAddress(module, funcName);
                   11532: 
                   11533:        if (NULL != fnIsWow64Process)
                   11534:        {
                   11535:                if (!fnIsWow64Process(GetCurrentProcess(),
                   11536:                        &bIsWow64))
                   11537:                        //throw std::exception("Unknown error");
                   11538:                        printf("Unknown error\n");
                   11539:        }
                   11540:        return bIsWow64 != FALSE;
                   11541: }
                   11542: #endif
1.177     brouard  11543: 
1.191     brouard  11544: void syscompilerinfo(int logged)
1.292     brouard  11545: {
                   11546: #include <stdint.h>
                   11547: 
                   11548:   /* #include "syscompilerinfo.h"*/
1.185     brouard  11549:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   11550:    /* /GS /W3 /Gy
                   11551:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   11552:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   11553:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  11554:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   11555:    */ 
                   11556:    /* 64 bits */
1.185     brouard  11557:    /*
                   11558:      /GS /W3 /Gy
                   11559:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   11560:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   11561:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   11562:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   11563:    /* Optimization are useless and O3 is slower than O2 */
                   11564:    /*
                   11565:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   11566:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   11567:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   11568:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   11569:    */
1.186     brouard  11570:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  11571:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   11572:       /PDB:"visual studio
                   11573:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   11574:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   11575:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   11576:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   11577:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   11578:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   11579:       uiAccess='false'"
                   11580:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   11581:       /NOLOGO /TLBID:1
                   11582:    */
1.292     brouard  11583: 
                   11584: 
1.177     brouard  11585: #if defined __INTEL_COMPILER
1.178     brouard  11586: #if defined(__GNUC__)
                   11587:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   11588: #endif
1.177     brouard  11589: #elif defined(__GNUC__) 
1.179     brouard  11590: #ifndef  __APPLE__
1.174     brouard  11591: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  11592: #endif
1.177     brouard  11593:    struct utsname sysInfo;
1.178     brouard  11594:    int cross = CROSS;
                   11595:    if (cross){
                   11596:           printf("Cross-");
1.191     brouard  11597:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  11598:    }
1.174     brouard  11599: #endif
                   11600: 
1.191     brouard  11601:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  11602: #if defined(__clang__)
1.191     brouard  11603:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  11604: #endif
                   11605: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  11606:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  11607: #endif
                   11608: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  11609:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  11610: #endif
                   11611: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  11612:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  11613: #endif
                   11614: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  11615:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  11616: #endif
                   11617: #if defined(_MSC_VER)
1.191     brouard  11618:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  11619: #endif
                   11620: #if defined(__PGI)
1.191     brouard  11621:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  11622: #endif
                   11623: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  11624:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  11625: #endif
1.191     brouard  11626:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  11627:    
1.167     brouard  11628: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   11629: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   11630:     // Windows (x64 and x86)
1.191     brouard  11631:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  11632: #elif __unix__ // all unices, not all compilers
                   11633:     // Unix
1.191     brouard  11634:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  11635: #elif __linux__
                   11636:     // linux
1.191     brouard  11637:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  11638: #elif __APPLE__
1.174     brouard  11639:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  11640:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  11641: #endif
                   11642: 
                   11643: /*  __MINGW32__          */
                   11644: /*  __CYGWIN__  */
                   11645: /* __MINGW64__  */
                   11646: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   11647: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   11648: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   11649: /* _WIN64  // Defined for applications for Win64. */
                   11650: /* _M_X64 // Defined for compilations that target x64 processors. */
                   11651: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  11652: 
1.167     brouard  11653: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  11654:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  11655: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  11656:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  11657: #else
1.191     brouard  11658:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  11659: #endif
                   11660: 
1.169     brouard  11661: #if defined(__GNUC__)
                   11662: # if defined(__GNUC_PATCHLEVEL__)
                   11663: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11664:                             + __GNUC_MINOR__ * 100 \
                   11665:                             + __GNUC_PATCHLEVEL__)
                   11666: # else
                   11667: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11668:                             + __GNUC_MINOR__ * 100)
                   11669: # endif
1.174     brouard  11670:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  11671:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  11672: 
                   11673:    if (uname(&sysInfo) != -1) {
                   11674:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  11675:         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  11676:    }
                   11677:    else
                   11678:       perror("uname() error");
1.179     brouard  11679:    //#ifndef __INTEL_COMPILER 
                   11680: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  11681:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  11682:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  11683: #endif
1.169     brouard  11684: #endif
1.172     brouard  11685: 
1.286     brouard  11686:    //   void main ()
1.172     brouard  11687:    //   {
1.169     brouard  11688: #if defined(_MSC_VER)
1.174     brouard  11689:    if (IsWow64()){
1.191     brouard  11690:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   11691:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  11692:    }
                   11693:    else{
1.191     brouard  11694:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   11695:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  11696:    }
1.172     brouard  11697:    //     printf("\nPress Enter to continue...");
                   11698:    //     getchar();
                   11699:    //   }
                   11700: 
1.169     brouard  11701: #endif
                   11702:    
1.167     brouard  11703: 
1.219     brouard  11704: }
1.136     brouard  11705: 
1.219     brouard  11706: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  11707:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  11708:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  11709:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  11710:   /* double ftolpl = 1.e-10; */
1.180     brouard  11711:   double age, agebase, agelim;
1.203     brouard  11712:   double tot;
1.180     brouard  11713: 
1.202     brouard  11714:   strcpy(filerespl,"PL_");
                   11715:   strcat(filerespl,fileresu);
                   11716:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  11717:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   11718:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  11719:   }
1.288     brouard  11720:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   11721:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  11722:   pstamp(ficrespl);
1.288     brouard  11723:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  11724:   fprintf(ficrespl,"#Age ");
                   11725:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   11726:   fprintf(ficrespl,"\n");
1.180     brouard  11727:   
1.219     brouard  11728:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  11729: 
1.219     brouard  11730:   agebase=ageminpar;
                   11731:   agelim=agemaxpar;
1.180     brouard  11732: 
1.227     brouard  11733:   /* i1=pow(2,ncoveff); */
1.234     brouard  11734:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  11735:   if (cptcovn < 1){i1=1;}
1.180     brouard  11736: 
1.337     brouard  11737:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
1.238     brouard  11738:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  11739:       k=TKresult[nres];
1.338     brouard  11740:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  11741:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
                   11742:       /*       continue; */
1.235     brouard  11743: 
1.238     brouard  11744:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11745:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   11746:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   11747:       /* k=k+1; */
                   11748:       /* to clean */
1.332     brouard  11749:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  11750:       fprintf(ficrespl,"#******");
                   11751:       printf("#******");
                   11752:       fprintf(ficlog,"#******");
1.337     brouard  11753:       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  11754:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
1.337     brouard  11755:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11756:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11757:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11758:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11759:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11760:       }
                   11761:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11762:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11763:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11764:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11765:       /* } */
1.238     brouard  11766:       fprintf(ficrespl,"******\n");
                   11767:       printf("******\n");
                   11768:       fprintf(ficlog,"******\n");
                   11769:       if(invalidvarcomb[k]){
                   11770:        printf("\nCombination (%d) ignored because no case \n",k); 
                   11771:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   11772:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   11773:        continue;
                   11774:       }
1.219     brouard  11775: 
1.238     brouard  11776:       fprintf(ficrespl,"#Age ");
1.337     brouard  11777:       /* for(j=1;j<=cptcoveff;j++) { */
                   11778:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11779:       /* } */
                   11780:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
                   11781:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  11782:       }
                   11783:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   11784:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  11785:     
1.238     brouard  11786:       for (age=agebase; age<=agelim; age++){
                   11787:        /* for (age=agebase; age<=agebase; age++){ */
1.337     brouard  11788:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
                   11789:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
1.238     brouard  11790:        fprintf(ficrespl,"%.0f ",age );
1.337     brouard  11791:        /* for(j=1;j<=cptcoveff;j++) */
                   11792:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11793:        for(j=1;j<=cptcovs;j++)
                   11794:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  11795:        tot=0.;
                   11796:        for(i=1; i<=nlstate;i++){
                   11797:          tot +=  prlim[i][i];
                   11798:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   11799:        }
                   11800:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   11801:       } /* Age */
                   11802:       /* was end of cptcod */
1.337     brouard  11803:     } /* nres */
                   11804:   /* } /\* for each combination *\/ */
1.219     brouard  11805:   return 0;
1.180     brouard  11806: }
                   11807: 
1.218     brouard  11808: 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  11809:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  11810:        
                   11811:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   11812:    * at any age between ageminpar and agemaxpar
                   11813:         */
1.235     brouard  11814:   int i, j, k, i1, nres=0 ;
1.217     brouard  11815:   /* double ftolpl = 1.e-10; */
                   11816:   double age, agebase, agelim;
                   11817:   double tot;
1.218     brouard  11818:   /* double ***mobaverage; */
                   11819:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  11820: 
                   11821:   strcpy(fileresplb,"PLB_");
                   11822:   strcat(fileresplb,fileresu);
                   11823:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  11824:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   11825:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  11826:   }
1.288     brouard  11827:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   11828:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  11829:   pstamp(ficresplb);
1.288     brouard  11830:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  11831:   fprintf(ficresplb,"#Age ");
                   11832:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   11833:   fprintf(ficresplb,"\n");
                   11834:   
1.218     brouard  11835:   
                   11836:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   11837:   
                   11838:   agebase=ageminpar;
                   11839:   agelim=agemaxpar;
                   11840:   
                   11841:   
1.227     brouard  11842:   i1=pow(2,cptcoveff);
1.218     brouard  11843:   if (cptcovn < 1){i1=1;}
1.227     brouard  11844:   
1.238     brouard  11845:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.338     brouard  11846:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   11847:       k=TKresult[nres];
                   11848:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   11849:      /* if(i1 != 1 && TKresult[nres]!= k) */
                   11850:      /*        continue; */
                   11851:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
1.238     brouard  11852:       fprintf(ficresplb,"#******");
                   11853:       printf("#******");
                   11854:       fprintf(ficlog,"#******");
1.338     brouard  11855:       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) */
                   11856:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11857:        fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11858:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  11859:       }
1.338     brouard  11860:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
                   11861:       /*       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11862:       /*       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11863:       /*       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11864:       /* } */
                   11865:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   11866:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11867:       /*       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11868:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11869:       /* } */
1.238     brouard  11870:       fprintf(ficresplb,"******\n");
                   11871:       printf("******\n");
                   11872:       fprintf(ficlog,"******\n");
                   11873:       if(invalidvarcomb[k]){
                   11874:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   11875:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   11876:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   11877:        continue;
                   11878:       }
1.218     brouard  11879:     
1.238     brouard  11880:       fprintf(ficresplb,"#Age ");
1.338     brouard  11881:       for(j=1;j<=cptcovs;j++) {
                   11882:        fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  11883:       }
                   11884:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   11885:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  11886:     
                   11887:     
1.238     brouard  11888:       for (age=agebase; age<=agelim; age++){
                   11889:        /* for (age=agebase; age<=agebase; age++){ */
                   11890:        if(mobilavproj > 0){
                   11891:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   11892:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11893:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  11894:        }else if (mobilavproj == 0){
                   11895:          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);
                   11896:          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);
                   11897:          exit(1);
                   11898:        }else{
                   11899:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11900:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  11901:          /* printf("TOTOT\n"); */
                   11902:           /* exit(1); */
1.238     brouard  11903:        }
                   11904:        fprintf(ficresplb,"%.0f ",age );
1.338     brouard  11905:        for(j=1;j<=cptcovs;j++)
                   11906:          fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  11907:        tot=0.;
                   11908:        for(i=1; i<=nlstate;i++){
                   11909:          tot +=  bprlim[i][i];
                   11910:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   11911:        }
                   11912:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   11913:       } /* Age */
                   11914:       /* was end of cptcod */
1.255     brouard  11915:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.338     brouard  11916:     /* } /\* end of any combination *\/ */
1.238     brouard  11917:   } /* end of nres */  
1.218     brouard  11918:   /* hBijx(p, bage, fage); */
                   11919:   /* fclose(ficrespijb); */
                   11920:   
                   11921:   return 0;
1.217     brouard  11922: }
1.218     brouard  11923:  
1.180     brouard  11924: int hPijx(double *p, int bage, int fage){
                   11925:     /*------------- h Pij x at various ages ------------*/
1.336     brouard  11926:   /* to be optimized with precov */
1.180     brouard  11927:   int stepsize;
                   11928:   int agelim;
                   11929:   int hstepm;
                   11930:   int nhstepm;
1.235     brouard  11931:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  11932: 
                   11933:   double agedeb;
                   11934:   double ***p3mat;
                   11935: 
1.337     brouard  11936:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   11937:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   11938:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11939:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11940:   }
                   11941:   printf("Computing pij: result on file '%s' \n", filerespij);
                   11942:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   11943:   
                   11944:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11945:   /*if (stepm<=24) stepsize=2;*/
                   11946:   
                   11947:   agelim=AGESUP;
                   11948:   hstepm=stepsize*YEARM; /* Every year of age */
                   11949:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   11950:   
                   11951:   /* hstepm=1;   aff par mois*/
                   11952:   pstamp(ficrespij);
                   11953:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   11954:   i1= pow(2,cptcoveff);
                   11955:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11956:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   11957:   /*   k=k+1;  */
                   11958:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11959:     k=TKresult[nres];
1.338     brouard  11960:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  11961:     /* for(k=1; k<=i1;k++){ */
                   11962:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   11963:     /*         continue; */
                   11964:     fprintf(ficrespij,"\n#****** ");
                   11965:     for(j=1;j<=cptcovs;j++){
                   11966:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11967:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11968:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11969:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11970:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11971:     }
                   11972:     fprintf(ficrespij,"******\n");
                   11973:     
                   11974:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   11975:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   11976:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   11977:       
                   11978:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   11979:       
                   11980:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11981:       oldm=oldms;savm=savms;
                   11982:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
                   11983:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   11984:       for(i=1; i<=nlstate;i++)
                   11985:        for(j=1; j<=nlstate+ndeath;j++)
                   11986:          fprintf(ficrespij," %1d-%1d",i,j);
                   11987:       fprintf(ficrespij,"\n");
                   11988:       for (h=0; h<=nhstepm; h++){
                   11989:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   11990:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.183     brouard  11991:        for(i=1; i<=nlstate;i++)
                   11992:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  11993:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.183     brouard  11994:        fprintf(ficrespij,"\n");
                   11995:       }
1.337     brouard  11996:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11997:       fprintf(ficrespij,"\n");
1.180     brouard  11998:     }
1.337     brouard  11999:   }
                   12000:   /*}*/
                   12001:   return 0;
1.180     brouard  12002: }
1.218     brouard  12003:  
                   12004:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  12005:     /*------------- h Bij x at various ages ------------*/
1.336     brouard  12006:     /* To be optimized with precov */
1.217     brouard  12007:   int stepsize;
1.218     brouard  12008:   /* int agelim; */
                   12009:        int ageminl;
1.217     brouard  12010:   int hstepm;
                   12011:   int nhstepm;
1.238     brouard  12012:   int h, i, i1, j, k, nres;
1.218     brouard  12013:        
1.217     brouard  12014:   double agedeb;
                   12015:   double ***p3mat;
1.218     brouard  12016:        
                   12017:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   12018:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   12019:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12020:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12021:   }
                   12022:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   12023:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   12024:   
                   12025:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12026:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  12027:   
1.218     brouard  12028:   /* agelim=AGESUP; */
1.289     brouard  12029:   ageminl=AGEINF; /* was 30 */
1.218     brouard  12030:   hstepm=stepsize*YEARM; /* Every year of age */
                   12031:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   12032:   
                   12033:   /* hstepm=1;   aff par mois*/
                   12034:   pstamp(ficrespijb);
1.255     brouard  12035:   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  12036:   i1= pow(2,cptcoveff);
1.218     brouard  12037:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12038:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12039:   /*   k=k+1;  */
1.238     brouard  12040:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  12041:     k=TKresult[nres];
1.338     brouard  12042:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12043:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12044:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   12045:     /*         continue; */
                   12046:     fprintf(ficrespijb,"\n#****** ");
                   12047:     for(j=1;j<=cptcovs;j++){
1.338     brouard  12048:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.337     brouard  12049:       /* for(j=1;j<=cptcoveff;j++) */
                   12050:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12051:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12052:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12053:     }
                   12054:     fprintf(ficrespijb,"******\n");
                   12055:     if(invalidvarcomb[k]){  /* Is it necessary here? */
                   12056:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   12057:       continue;
                   12058:     }
                   12059:     
                   12060:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   12061:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   12062:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   12063:       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 */
                   12064:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
                   12065:       
                   12066:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12067:       
                   12068:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   12069:       /* and memory limitations if stepm is small */
                   12070:       
                   12071:       /* oldm=oldms;savm=savms; */
                   12072:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   12073:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
                   12074:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   12075:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
                   12076:       for(i=1; i<=nlstate;i++)
                   12077:        for(j=1; j<=nlstate+ndeath;j++)
                   12078:          fprintf(ficrespijb," %1d-%1d",i,j);
                   12079:       fprintf(ficrespijb,"\n");
                   12080:       for (h=0; h<=nhstepm; h++){
                   12081:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12082:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   12083:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  12084:        for(i=1; i<=nlstate;i++)
                   12085:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12086:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.217     brouard  12087:        fprintf(ficrespijb,"\n");
1.337     brouard  12088:       }
                   12089:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12090:       fprintf(ficrespijb,"\n");
                   12091:     } /* end age deb */
                   12092:     /* } /\* end combination *\/ */
1.238     brouard  12093:   } /* end nres */
1.218     brouard  12094:   return 0;
                   12095:  } /*  hBijx */
1.217     brouard  12096: 
1.180     brouard  12097: 
1.136     brouard  12098: /***********************************************/
                   12099: /**************** Main Program *****************/
                   12100: /***********************************************/
                   12101: 
                   12102: int main(int argc, char *argv[])
                   12103: {
                   12104: #ifdef GSL
                   12105:   const gsl_multimin_fminimizer_type *T;
                   12106:   size_t iteri = 0, it;
                   12107:   int rval = GSL_CONTINUE;
                   12108:   int status = GSL_SUCCESS;
                   12109:   double ssval;
                   12110: #endif
                   12111:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  12112:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   12113:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  12114:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  12115:   int jj, ll, li, lj, lk;
1.136     brouard  12116:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  12117:   int num_filled;
1.136     brouard  12118:   int itimes;
                   12119:   int NDIM=2;
                   12120:   int vpopbased=0;
1.235     brouard  12121:   int nres=0;
1.258     brouard  12122:   int endishere=0;
1.277     brouard  12123:   int noffset=0;
1.274     brouard  12124:   int ncurrv=0; /* Temporary variable */
                   12125:   
1.164     brouard  12126:   char ca[32], cb[32];
1.136     brouard  12127:   /*  FILE *fichtm; *//* Html File */
                   12128:   /* FILE *ficgp;*/ /*Gnuplot File */
                   12129:   struct stat info;
1.191     brouard  12130:   double agedeb=0.;
1.194     brouard  12131: 
                   12132:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  12133:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  12134: 
1.165     brouard  12135:   double fret;
1.191     brouard  12136:   double dum=0.; /* Dummy variable */
1.136     brouard  12137:   double ***p3mat;
1.218     brouard  12138:   /* double ***mobaverage; */
1.319     brouard  12139:   double wald;
1.164     brouard  12140: 
                   12141:   char line[MAXLINE];
1.197     brouard  12142:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   12143: 
1.234     brouard  12144:   char  modeltemp[MAXLINE];
1.332     brouard  12145:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  12146:   
1.136     brouard  12147:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  12148:   char *tok, *val; /* pathtot */
1.334     brouard  12149:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.195     brouard  12150:   int c,  h , cpt, c2;
1.191     brouard  12151:   int jl=0;
                   12152:   int i1, j1, jk, stepsize=0;
1.194     brouard  12153:   int count=0;
                   12154: 
1.164     brouard  12155:   int *tab; 
1.136     brouard  12156:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  12157:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   12158:   /* double anprojf, mprojf, jprojf; */
                   12159:   /* double jintmean,mintmean,aintmean;   */
                   12160:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   12161:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   12162:   double yrfproj= 10.0; /* Number of years of forward projections */
                   12163:   double yrbproj= 10.0; /* Number of years of backward projections */
                   12164:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  12165:   int mobilav=0,popforecast=0;
1.191     brouard  12166:   int hstepm=0, nhstepm=0;
1.136     brouard  12167:   int agemortsup;
                   12168:   float  sumlpop=0.;
                   12169:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   12170:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   12171: 
1.191     brouard  12172:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  12173:   double ftolpl=FTOL;
                   12174:   double **prlim;
1.217     brouard  12175:   double **bprlim;
1.317     brouard  12176:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   12177:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  12178:   double ***paramstart; /* Matrix of starting parameter values */
                   12179:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  12180:   double **matcov; /* Matrix of covariance */
1.203     brouard  12181:   double **hess; /* Hessian matrix */
1.136     brouard  12182:   double ***delti3; /* Scale */
                   12183:   double *delti; /* Scale */
                   12184:   double ***eij, ***vareij;
                   12185:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  12186: 
1.136     brouard  12187:   double *epj, vepp;
1.164     brouard  12188: 
1.273     brouard  12189:   double dateprev1, dateprev2;
1.296     brouard  12190:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   12191:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   12192: 
1.217     brouard  12193: 
1.136     brouard  12194:   double **ximort;
1.145     brouard  12195:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  12196:   int *dcwave;
                   12197: 
1.164     brouard  12198:   char z[1]="c";
1.136     brouard  12199: 
                   12200:   /*char  *strt;*/
                   12201:   char strtend[80];
1.126     brouard  12202: 
1.164     brouard  12203: 
1.126     brouard  12204: /*   setlocale (LC_ALL, ""); */
                   12205: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   12206: /*   textdomain (PACKAGE); */
                   12207: /*   setlocale (LC_CTYPE, ""); */
                   12208: /*   setlocale (LC_MESSAGES, ""); */
                   12209: 
                   12210:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  12211:   rstart_time = time(NULL);  
                   12212:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   12213:   start_time = *localtime(&rstart_time);
1.126     brouard  12214:   curr_time=start_time;
1.157     brouard  12215:   /*tml = *localtime(&start_time.tm_sec);*/
                   12216:   /* strcpy(strstart,asctime(&tml)); */
                   12217:   strcpy(strstart,asctime(&start_time));
1.126     brouard  12218: 
                   12219: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  12220: /*  tp.tm_sec = tp.tm_sec +86400; */
                   12221: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  12222: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   12223: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   12224: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  12225: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  12226: /*   strt=asctime(&tmg); */
                   12227: /*   printf("Time(after) =%s",strstart);  */
                   12228: /*  (void) time (&time_value);
                   12229: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   12230: *  tm = *localtime(&time_value);
                   12231: *  strstart=asctime(&tm);
                   12232: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   12233: */
                   12234: 
                   12235:   nberr=0; /* Number of errors and warnings */
                   12236:   nbwarn=0;
1.184     brouard  12237: #ifdef WIN32
                   12238:   _getcwd(pathcd, size);
                   12239: #else
1.126     brouard  12240:   getcwd(pathcd, size);
1.184     brouard  12241: #endif
1.191     brouard  12242:   syscompilerinfo(0);
1.196     brouard  12243:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  12244:   if(argc <=1){
                   12245:     printf("\nEnter the parameter file name: ");
1.205     brouard  12246:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   12247:       printf("ERROR Empty parameter file name\n");
                   12248:       goto end;
                   12249:     }
1.126     brouard  12250:     i=strlen(pathr);
                   12251:     if(pathr[i-1]=='\n')
                   12252:       pathr[i-1]='\0';
1.156     brouard  12253:     i=strlen(pathr);
1.205     brouard  12254:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  12255:       pathr[i-1]='\0';
1.205     brouard  12256:     }
                   12257:     i=strlen(pathr);
                   12258:     if( i==0 ){
                   12259:       printf("ERROR Empty parameter file name\n");
                   12260:       goto end;
                   12261:     }
                   12262:     for (tok = pathr; tok != NULL; ){
1.126     brouard  12263:       printf("Pathr |%s|\n",pathr);
                   12264:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   12265:       printf("val= |%s| pathr=%s\n",val,pathr);
                   12266:       strcpy (pathtot, val);
                   12267:       if(pathr[0] == '\0') break; /* Dirty */
                   12268:     }
                   12269:   }
1.281     brouard  12270:   else if (argc<=2){
                   12271:     strcpy(pathtot,argv[1]);
                   12272:   }
1.126     brouard  12273:   else{
                   12274:     strcpy(pathtot,argv[1]);
1.281     brouard  12275:     strcpy(z,argv[2]);
                   12276:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  12277:   }
                   12278:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   12279:   /*cygwin_split_path(pathtot,path,optionfile);
                   12280:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   12281:   /* cutv(path,optionfile,pathtot,'\\');*/
                   12282: 
                   12283:   /* Split argv[0], imach program to get pathimach */
                   12284:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   12285:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   12286:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   12287:  /*   strcpy(pathimach,argv[0]); */
                   12288:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   12289:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   12290:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  12291: #ifdef WIN32
                   12292:   _chdir(path); /* Can be a relative path */
                   12293:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   12294: #else
1.126     brouard  12295:   chdir(path); /* Can be a relative path */
1.184     brouard  12296:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   12297: #endif
                   12298:   printf("Current directory %s!\n",pathcd);
1.126     brouard  12299:   strcpy(command,"mkdir ");
                   12300:   strcat(command,optionfilefiname);
                   12301:   if((outcmd=system(command)) != 0){
1.169     brouard  12302:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  12303:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   12304:     /* fclose(ficlog); */
                   12305: /*     exit(1); */
                   12306:   }
                   12307: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   12308: /*     perror("mkdir"); */
                   12309: /*   } */
                   12310: 
                   12311:   /*-------- arguments in the command line --------*/
                   12312: 
1.186     brouard  12313:   /* Main Log file */
1.126     brouard  12314:   strcat(filelog, optionfilefiname);
                   12315:   strcat(filelog,".log");    /* */
                   12316:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   12317:     printf("Problem with logfile %s\n",filelog);
                   12318:     goto end;
                   12319:   }
                   12320:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  12321:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  12322:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   12323:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   12324:  path=%s \n\
                   12325:  optionfile=%s\n\
                   12326:  optionfilext=%s\n\
1.156     brouard  12327:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  12328: 
1.197     brouard  12329:   syscompilerinfo(1);
1.167     brouard  12330: 
1.126     brouard  12331:   printf("Local time (at start):%s",strstart);
                   12332:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   12333:   fflush(ficlog);
                   12334: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  12335: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  12336: 
                   12337:   /* */
                   12338:   strcpy(fileres,"r");
                   12339:   strcat(fileres, optionfilefiname);
1.201     brouard  12340:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  12341:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  12342:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  12343: 
1.186     brouard  12344:   /* Main ---------arguments file --------*/
1.126     brouard  12345: 
                   12346:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  12347:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   12348:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  12349:     fflush(ficlog);
1.149     brouard  12350:     /* goto end; */
                   12351:     exit(70); 
1.126     brouard  12352:   }
                   12353: 
                   12354:   strcpy(filereso,"o");
1.201     brouard  12355:   strcat(filereso,fileresu);
1.126     brouard  12356:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   12357:     printf("Problem with Output resultfile: %s\n", filereso);
                   12358:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   12359:     fflush(ficlog);
                   12360:     goto end;
                   12361:   }
1.278     brouard  12362:       /*-------- Rewriting parameter file ----------*/
                   12363:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   12364:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   12365:   strcat(rfileres,".");    /* */
                   12366:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   12367:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   12368:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   12369:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   12370:     fflush(ficlog);
                   12371:     goto end;
                   12372:   }
                   12373:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  12374: 
1.278     brouard  12375:                                      
1.126     brouard  12376:   /* Reads comments: lines beginning with '#' */
                   12377:   numlinepar=0;
1.277     brouard  12378:   /* Is it a BOM UTF-8 Windows file? */
                   12379:   /* First parameter line */
1.197     brouard  12380:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  12381:     noffset=0;
                   12382:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   12383:     {
                   12384:       noffset=noffset+3;
                   12385:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   12386:     }
1.302     brouard  12387: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   12388:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  12389:     {
                   12390:       noffset=noffset+2;
                   12391:       printf("# File is an UTF16BE BOM file\n");
                   12392:     }
                   12393:     else if( line[0] == 0 && line[1] == 0)
                   12394:     {
                   12395:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   12396:        noffset=noffset+4;
                   12397:        printf("# File is an UTF16BE BOM file\n");
                   12398:       }
                   12399:     } else{
                   12400:       ;/*printf(" Not a BOM file\n");*/
                   12401:     }
                   12402:   
1.197     brouard  12403:     /* If line starts with a # it is a comment */
1.277     brouard  12404:     if (line[noffset] == '#') {
1.197     brouard  12405:       numlinepar++;
                   12406:       fputs(line,stdout);
                   12407:       fputs(line,ficparo);
1.278     brouard  12408:       fputs(line,ficres);
1.197     brouard  12409:       fputs(line,ficlog);
                   12410:       continue;
                   12411:     }else
                   12412:       break;
                   12413:   }
                   12414:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   12415:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   12416:     if (num_filled != 5) {
                   12417:       printf("Should be 5 parameters\n");
1.283     brouard  12418:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  12419:     }
1.126     brouard  12420:     numlinepar++;
1.197     brouard  12421:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  12422:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12423:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12424:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  12425:   }
                   12426:   /* Second parameter line */
                   12427:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  12428:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   12429:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  12430:     if (line[0] == '#') {
                   12431:       numlinepar++;
1.283     brouard  12432:       printf("%s",line);
                   12433:       fprintf(ficres,"%s",line);
                   12434:       fprintf(ficparo,"%s",line);
                   12435:       fprintf(ficlog,"%s",line);
1.197     brouard  12436:       continue;
                   12437:     }else
                   12438:       break;
                   12439:   }
1.223     brouard  12440:   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", \
                   12441:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   12442:     if (num_filled != 11) {
                   12443:       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  12444:       printf("but line=%s\n",line);
1.283     brouard  12445:       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");
                   12446:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  12447:     }
1.286     brouard  12448:     if( lastpass > maxwav){
                   12449:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12450:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12451:       fflush(ficlog);
                   12452:       goto end;
                   12453:     }
                   12454:       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  12455:     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  12456:     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  12457:     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  12458:   }
1.203     brouard  12459:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  12460:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  12461:   /* Third parameter line */
                   12462:   while(fgets(line, MAXLINE, ficpar)) {
                   12463:     /* If line starts with a # it is a comment */
                   12464:     if (line[0] == '#') {
                   12465:       numlinepar++;
1.283     brouard  12466:       printf("%s",line);
                   12467:       fprintf(ficres,"%s",line);
                   12468:       fprintf(ficparo,"%s",line);
                   12469:       fprintf(ficlog,"%s",line);
1.197     brouard  12470:       continue;
                   12471:     }else
                   12472:       break;
                   12473:   }
1.201     brouard  12474:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  12475:     if (num_filled != 1){
1.302     brouard  12476:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   12477:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  12478:       model[0]='\0';
                   12479:       goto end;
                   12480:     }
                   12481:     else{
                   12482:       if (model[0]=='+'){
                   12483:        for(i=1; i<=strlen(model);i++)
                   12484:          modeltemp[i-1]=model[i];
1.201     brouard  12485:        strcpy(model,modeltemp); 
1.197     brouard  12486:       }
                   12487:     }
1.338     brouard  12488:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  12489:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  12490:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   12491:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   12492:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  12493:   }
                   12494:   /* 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); */
                   12495:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   12496:   /* 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  12497:   /* 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); */
                   12498:   /* 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  12499:   fflush(ficlog);
1.190     brouard  12500:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   12501:   if(model[0]=='#'){
1.279     brouard  12502:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   12503:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   12504:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  12505:     if(mle != -1){
1.279     brouard  12506:       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  12507:       exit(1);
                   12508:     }
                   12509:   }
1.126     brouard  12510:   while((c=getc(ficpar))=='#' && c!= EOF){
                   12511:     ungetc(c,ficpar);
                   12512:     fgets(line, MAXLINE, ficpar);
                   12513:     numlinepar++;
1.195     brouard  12514:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   12515:       z[0]=line[1];
                   12516:     }
                   12517:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  12518:     fputs(line, stdout);
                   12519:     //puts(line);
1.126     brouard  12520:     fputs(line,ficparo);
                   12521:     fputs(line,ficlog);
                   12522:   }
                   12523:   ungetc(c,ficpar);
                   12524: 
                   12525:    
1.290     brouard  12526:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   12527:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   12528:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
1.341   ! brouard  12529:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /\**< Time varying covariate (dummy and quantitative)*\/ */
        !          12530:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /**< Might be better */
1.136     brouard  12531:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   12532:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   12533:      v1+v2*age+v2*v3 makes cptcovn = 3
                   12534:   */
                   12535:   if (strlen(model)>1) 
1.187     brouard  12536:     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  12537:   else
1.187     brouard  12538:     ncovmodel=2; /* Constant and age */
1.133     brouard  12539:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   12540:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  12541:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   12542:     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);
                   12543:     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);
                   12544:     fflush(stdout);
                   12545:     fclose (ficlog);
                   12546:     goto end;
                   12547:   }
1.126     brouard  12548:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12549:   delti=delti3[1][1];
                   12550:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   12551:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  12552: /* We could also provide initial parameters values giving by simple logistic regression 
                   12553:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   12554:       /* for(i=1;i<nlstate;i++){ */
                   12555:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12556:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12557:       /* } */
1.126     brouard  12558:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  12559:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   12560:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12561:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   12562:     fclose (ficparo);
                   12563:     fclose (ficlog);
                   12564:     goto end;
                   12565:     exit(0);
1.220     brouard  12566:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  12567:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  12568:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   12569:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12570:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12571:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12572:     hess=matrix(1,npar,1,npar);
1.220     brouard  12573:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  12574:     /* Read guessed parameters */
1.126     brouard  12575:     /* Reads comments: lines beginning with '#' */
                   12576:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12577:       ungetc(c,ficpar);
                   12578:       fgets(line, MAXLINE, ficpar);
                   12579:       numlinepar++;
1.141     brouard  12580:       fputs(line,stdout);
1.126     brouard  12581:       fputs(line,ficparo);
                   12582:       fputs(line,ficlog);
                   12583:     }
                   12584:     ungetc(c,ficpar);
                   12585:     
                   12586:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  12587:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  12588:     for(i=1; i <=nlstate; i++){
1.234     brouard  12589:       j=0;
1.126     brouard  12590:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  12591:        if(jj==i) continue;
                   12592:        j++;
1.292     brouard  12593:        while((c=getc(ficpar))=='#' && c!= EOF){
                   12594:          ungetc(c,ficpar);
                   12595:          fgets(line, MAXLINE, ficpar);
                   12596:          numlinepar++;
                   12597:          fputs(line,stdout);
                   12598:          fputs(line,ficparo);
                   12599:          fputs(line,ficlog);
                   12600:        }
                   12601:        ungetc(c,ficpar);
1.234     brouard  12602:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12603:        if ((i1 != i) || (j1 != jj)){
                   12604:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  12605: It might be a problem of design; if ncovcol and the model are correct\n \
                   12606: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  12607:          exit(1);
                   12608:        }
                   12609:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12610:        if(mle==1)
                   12611:          printf("%1d%1d",i,jj);
                   12612:        fprintf(ficlog,"%1d%1d",i,jj);
                   12613:        for(k=1; k<=ncovmodel;k++){
                   12614:          fscanf(ficpar," %lf",&param[i][j][k]);
                   12615:          if(mle==1){
                   12616:            printf(" %lf",param[i][j][k]);
                   12617:            fprintf(ficlog," %lf",param[i][j][k]);
                   12618:          }
                   12619:          else
                   12620:            fprintf(ficlog," %lf",param[i][j][k]);
                   12621:          fprintf(ficparo," %lf",param[i][j][k]);
                   12622:        }
                   12623:        fscanf(ficpar,"\n");
                   12624:        numlinepar++;
                   12625:        if(mle==1)
                   12626:          printf("\n");
                   12627:        fprintf(ficlog,"\n");
                   12628:        fprintf(ficparo,"\n");
1.126     brouard  12629:       }
                   12630:     }  
                   12631:     fflush(ficlog);
1.234     brouard  12632:     
1.251     brouard  12633:     /* Reads parameters values */
1.126     brouard  12634:     p=param[1][1];
1.251     brouard  12635:     pstart=paramstart[1][1];
1.126     brouard  12636:     
                   12637:     /* Reads comments: lines beginning with '#' */
                   12638:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12639:       ungetc(c,ficpar);
                   12640:       fgets(line, MAXLINE, ficpar);
                   12641:       numlinepar++;
1.141     brouard  12642:       fputs(line,stdout);
1.126     brouard  12643:       fputs(line,ficparo);
                   12644:       fputs(line,ficlog);
                   12645:     }
                   12646:     ungetc(c,ficpar);
                   12647: 
                   12648:     for(i=1; i <=nlstate; i++){
                   12649:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  12650:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12651:        if ( (i1-i) * (j1-j) != 0){
                   12652:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   12653:          exit(1);
                   12654:        }
                   12655:        printf("%1d%1d",i,j);
                   12656:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12657:        fprintf(ficlog,"%1d%1d",i1,j1);
                   12658:        for(k=1; k<=ncovmodel;k++){
                   12659:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   12660:          printf(" %le",delti3[i][j][k]);
                   12661:          fprintf(ficparo," %le",delti3[i][j][k]);
                   12662:          fprintf(ficlog," %le",delti3[i][j][k]);
                   12663:        }
                   12664:        fscanf(ficpar,"\n");
                   12665:        numlinepar++;
                   12666:        printf("\n");
                   12667:        fprintf(ficparo,"\n");
                   12668:        fprintf(ficlog,"\n");
1.126     brouard  12669:       }
                   12670:     }
                   12671:     fflush(ficlog);
1.234     brouard  12672:     
1.145     brouard  12673:     /* Reads covariance matrix */
1.126     brouard  12674:     delti=delti3[1][1];
1.220     brouard  12675:                
                   12676:                
1.126     brouard  12677:     /* 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  12678:                
1.126     brouard  12679:     /* Reads comments: lines beginning with '#' */
                   12680:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12681:       ungetc(c,ficpar);
                   12682:       fgets(line, MAXLINE, ficpar);
                   12683:       numlinepar++;
1.141     brouard  12684:       fputs(line,stdout);
1.126     brouard  12685:       fputs(line,ficparo);
                   12686:       fputs(line,ficlog);
                   12687:     }
                   12688:     ungetc(c,ficpar);
1.220     brouard  12689:                
1.126     brouard  12690:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12691:     hess=matrix(1,npar,1,npar);
1.131     brouard  12692:     for(i=1; i <=npar; i++)
                   12693:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  12694:                
1.194     brouard  12695:     /* Scans npar lines */
1.126     brouard  12696:     for(i=1; i <=npar; i++){
1.226     brouard  12697:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  12698:       if(count != 3){
1.226     brouard  12699:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12700: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12701: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12702:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12703: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12704: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12705:        exit(1);
1.220     brouard  12706:       }else{
1.226     brouard  12707:        if(mle==1)
                   12708:          printf("%1d%1d%d",i1,j1,jk);
                   12709:       }
                   12710:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   12711:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  12712:       for(j=1; j <=i; j++){
1.226     brouard  12713:        fscanf(ficpar," %le",&matcov[i][j]);
                   12714:        if(mle==1){
                   12715:          printf(" %.5le",matcov[i][j]);
                   12716:        }
                   12717:        fprintf(ficlog," %.5le",matcov[i][j]);
                   12718:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  12719:       }
                   12720:       fscanf(ficpar,"\n");
                   12721:       numlinepar++;
                   12722:       if(mle==1)
1.220     brouard  12723:                                printf("\n");
1.126     brouard  12724:       fprintf(ficlog,"\n");
                   12725:       fprintf(ficparo,"\n");
                   12726:     }
1.194     brouard  12727:     /* End of read covariance matrix npar lines */
1.126     brouard  12728:     for(i=1; i <=npar; i++)
                   12729:       for(j=i+1;j<=npar;j++)
1.226     brouard  12730:        matcov[i][j]=matcov[j][i];
1.126     brouard  12731:     
                   12732:     if(mle==1)
                   12733:       printf("\n");
                   12734:     fprintf(ficlog,"\n");
                   12735:     
                   12736:     fflush(ficlog);
                   12737:     
                   12738:   }    /* End of mle != -3 */
1.218     brouard  12739:   
1.186     brouard  12740:   /*  Main data
                   12741:    */
1.290     brouard  12742:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   12743:   /* num=lvector(1,n); */
                   12744:   /* moisnais=vector(1,n); */
                   12745:   /* annais=vector(1,n); */
                   12746:   /* moisdc=vector(1,n); */
                   12747:   /* andc=vector(1,n); */
                   12748:   /* weight=vector(1,n); */
                   12749:   /* agedc=vector(1,n); */
                   12750:   /* cod=ivector(1,n); */
                   12751:   /* for(i=1;i<=n;i++){ */
                   12752:   num=lvector(firstobs,lastobs);
                   12753:   moisnais=vector(firstobs,lastobs);
                   12754:   annais=vector(firstobs,lastobs);
                   12755:   moisdc=vector(firstobs,lastobs);
                   12756:   andc=vector(firstobs,lastobs);
                   12757:   weight=vector(firstobs,lastobs);
                   12758:   agedc=vector(firstobs,lastobs);
                   12759:   cod=ivector(firstobs,lastobs);
                   12760:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  12761:     num[i]=0;
                   12762:     moisnais[i]=0;
                   12763:     annais[i]=0;
                   12764:     moisdc[i]=0;
                   12765:     andc[i]=0;
                   12766:     agedc[i]=0;
                   12767:     cod[i]=0;
                   12768:     weight[i]=1.0; /* Equal weights, 1 by default */
                   12769:   }
1.290     brouard  12770:   mint=matrix(1,maxwav,firstobs,lastobs);
                   12771:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  12772:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
1.336     brouard  12773:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
1.126     brouard  12774:   tab=ivector(1,NCOVMAX);
1.144     brouard  12775:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  12776:   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  12777: 
1.136     brouard  12778:   /* Reads data from file datafile */
                   12779:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   12780:     goto end;
                   12781: 
                   12782:   /* Calculation of the number of parameters from char model */
1.234     brouard  12783:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  12784:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   12785:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   12786:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   12787:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  12788:   */
                   12789:   
                   12790:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   12791:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  12792:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335     brouard  12793:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  12794:   TvarsD=ivector(1,NCOVMAX); /*  */
                   12795:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   12796:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  12797:   TvarF=ivector(1,NCOVMAX); /*  */
                   12798:   TvarFind=ivector(1,NCOVMAX); /*  */
                   12799:   TvarV=ivector(1,NCOVMAX); /*  */
                   12800:   TvarVind=ivector(1,NCOVMAX); /*  */
                   12801:   TvarA=ivector(1,NCOVMAX); /*  */
                   12802:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  12803:   TvarFD=ivector(1,NCOVMAX); /*  */
                   12804:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   12805:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   12806:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   12807:   TvarVD=ivector(1,NCOVMAX); /*  */
                   12808:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   12809:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   12810:   TvarVQind=ivector(1,NCOVMAX); /*  */
1.339     brouard  12811:   TvarVV=ivector(1,NCOVMAX); /*  */
                   12812:   TvarVVind=ivector(1,NCOVMAX); /*  */
1.231     brouard  12813: 
1.230     brouard  12814:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  12815:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  12816:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   12817:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   12818:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  12819:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   12820:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   12821:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   12822:   */
                   12823:   /* For model-covariate k tells which data-covariate to use but
                   12824:     because this model-covariate is a construction we invent a new column
                   12825:     ncovcol + k1
                   12826:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   12827:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  12828:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   12829:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  12830:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   12831:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  12832:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  12833:   */
1.145     brouard  12834:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   12835:   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  12836:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   12837:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.330     brouard  12838:   Tvardk=imatrix(1,NCOVMAX,1,2);
1.145     brouard  12839:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  12840:                         4 covariates (3 plus signs)
                   12841:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  12842:                           */  
                   12843:   for(i=1;i<NCOVMAX;i++)
                   12844:     Tage[i]=0;
1.230     brouard  12845:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  12846:                                * individual dummy, fixed or varying:
                   12847:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   12848:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  12849:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   12850:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   12851:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   12852:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   12853:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  12854:                                * individual quantitative, fixed or varying:
                   12855:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   12856:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   12857:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  12858: /* Main decodemodel */
                   12859: 
1.187     brouard  12860: 
1.223     brouard  12861:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  12862:     goto end;
                   12863: 
1.137     brouard  12864:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   12865:     nbwarn++;
                   12866:     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); 
                   12867:     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); 
                   12868:   }
1.136     brouard  12869:     /*  if(mle==1){*/
1.137     brouard  12870:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   12871:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  12872:   }
                   12873: 
                   12874:     /*-calculation of age at interview from date of interview and age at death -*/
                   12875:   agev=matrix(1,maxwav,1,imx);
                   12876: 
                   12877:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   12878:     goto end;
                   12879: 
1.126     brouard  12880: 
1.136     brouard  12881:   agegomp=(int)agemin;
1.290     brouard  12882:   free_vector(moisnais,firstobs,lastobs);
                   12883:   free_vector(annais,firstobs,lastobs);
1.126     brouard  12884:   /* free_matrix(mint,1,maxwav,1,n);
                   12885:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  12886:   /* free_vector(moisdc,1,n); */
                   12887:   /* free_vector(andc,1,n); */
1.145     brouard  12888:   /* */
                   12889:   
1.126     brouard  12890:   wav=ivector(1,imx);
1.214     brouard  12891:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12892:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12893:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12894:   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.*/
                   12895:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   12896:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  12897:    
                   12898:   /* Concatenates waves */
1.214     brouard  12899:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   12900:      Death is a valid wave (if date is known).
                   12901:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   12902:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   12903:      and mw[mi+1][i]. dh depends on stepm.
                   12904:   */
                   12905: 
1.126     brouard  12906:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  12907:   /* Concatenates waves */
1.145     brouard  12908:  
1.290     brouard  12909:   free_vector(moisdc,firstobs,lastobs);
                   12910:   free_vector(andc,firstobs,lastobs);
1.215     brouard  12911: 
1.126     brouard  12912:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   12913:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   12914:   ncodemax[1]=1;
1.145     brouard  12915:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  12916:   cptcoveff=0;
1.220     brouard  12917:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335     brouard  12918:     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  12919:   }
                   12920:   
                   12921:   ncovcombmax=pow(2,cptcoveff);
1.338     brouard  12922:   invalidvarcomb=ivector(0, ncovcombmax); 
                   12923:   for(i=0;i<ncovcombmax;i++)
1.227     brouard  12924:     invalidvarcomb[i]=0;
                   12925:   
1.211     brouard  12926:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  12927:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  12928:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  12929:   
1.200     brouard  12930:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  12931:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  12932:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  12933:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   12934:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   12935:    * (currently 0 or 1) in the data.
                   12936:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   12937:    * corresponding modality (h,j).
                   12938:    */
                   12939: 
1.145     brouard  12940:   h=0;
                   12941:   /*if (cptcovn > 0) */
1.126     brouard  12942:   m=pow(2,cptcoveff);
                   12943:  
1.144     brouard  12944:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  12945:           * For k=4 covariates, h goes from 1 to m=2**k
                   12946:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   12947:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  12948:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   12949:           *______________________________   *______________________
                   12950:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   12951:           *     2     2     1     1     1   *     1     0  0  0  1 
                   12952:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   12953:           *     4     2     2     1     1   *     3     0  0  1  1 
                   12954:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   12955:           *     6     2     1     2     1   *     5     0  1  0  1 
                   12956:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   12957:           *     8     2     2     2     1   *     7     0  1  1  1 
                   12958:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   12959:           *    10     2     1     1     2   *     9     1  0  0  1 
                   12960:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   12961:           *    12     2     2     1     2   *    11     1  0  1  1 
                   12962:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   12963:           *    14     2     1     2     2   *    13     1  1  0  1 
                   12964:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   12965:           *    16     2     2     2     2   *    15     1  1  1  1          
                   12966:           */                                     
1.212     brouard  12967:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  12968:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   12969:      * and the value of each covariate?
                   12970:      * V1=1, V2=1, V3=2, V4=1 ?
                   12971:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   12972:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   12973:      * In order to get the real value in the data, we use nbcode
                   12974:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   12975:      * We are keeping this crazy system in order to be able (in the future?) 
                   12976:      * to have more than 2 values (0 or 1) for a covariate.
                   12977:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   12978:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   12979:      *              bbbbbbbb
                   12980:      *              76543210     
                   12981:      *   h-1        00000101 (6-1=5)
1.219     brouard  12982:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  12983:      *           &
                   12984:      *     1        00000001 (1)
1.219     brouard  12985:      *              00000000        = 1 & ((h-1) >> (k-1))
                   12986:      *          +1= 00000001 =1 
1.211     brouard  12987:      *
                   12988:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   12989:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   12990:      *    >>k'            11
                   12991:      *          &   00000001
                   12992:      *            = 00000001
                   12993:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   12994:      * Reverse h=6 and m=16?
                   12995:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   12996:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   12997:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   12998:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   12999:      * V3=decodtabm(14,3,2**4)=2
                   13000:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   13001:      *(h-1) >> (j-1)    0011 =13 >> 2
                   13002:      *          &1 000000001
                   13003:      *           = 000000001
                   13004:      *         +1= 000000010 =2
                   13005:      *                  2211
                   13006:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   13007:      *                  V3=2
1.220     brouard  13008:                 * codtabm and decodtabm are identical
1.211     brouard  13009:      */
                   13010: 
1.145     brouard  13011: 
                   13012:  free_ivector(Ndum,-1,NCOVMAX);
                   13013: 
                   13014: 
1.126     brouard  13015:     
1.186     brouard  13016:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  13017:   strcpy(optionfilegnuplot,optionfilefiname);
                   13018:   if(mle==-3)
1.201     brouard  13019:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  13020:   strcat(optionfilegnuplot,".gp");
                   13021: 
                   13022:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   13023:     printf("Problem with file %s",optionfilegnuplot);
                   13024:   }
                   13025:   else{
1.204     brouard  13026:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  13027:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  13028:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   13029:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  13030:   }
                   13031:   /*  fclose(ficgp);*/
1.186     brouard  13032: 
                   13033: 
                   13034:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  13035: 
                   13036:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   13037:   if(mle==-3)
1.201     brouard  13038:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  13039:   strcat(optionfilehtm,".htm");
                   13040:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  13041:     printf("Problem with %s \n",optionfilehtm);
                   13042:     exit(0);
1.126     brouard  13043:   }
                   13044: 
                   13045:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   13046:   strcat(optionfilehtmcov,"-cov.htm");
                   13047:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   13048:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   13049:   }
                   13050:   else{
                   13051:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   13052: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13053: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  13054:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   13055:   }
                   13056: 
1.335     brouard  13057:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   13058: <title>IMaCh %s</title></head>\n\
                   13059:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   13060: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   13061: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   13062: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   13063: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   13064:   
                   13065:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13066: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  13067: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.337     brouard  13068: 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  13069: \n\
                   13070: <hr  size=\"2\" color=\"#EC5E5E\">\
                   13071:  <ul><li><h4>Parameter files</h4>\n\
                   13072:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   13073:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   13074:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   13075:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   13076:  - Date and time at start: %s</ul>\n",\
1.335     brouard  13077:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  13078:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   13079:          fileres,fileres,\
                   13080:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   13081:   fflush(fichtm);
                   13082: 
                   13083:   strcpy(pathr,path);
                   13084:   strcat(pathr,optionfilefiname);
1.184     brouard  13085: #ifdef WIN32
                   13086:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   13087: #else
1.126     brouard  13088:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  13089: #endif
                   13090:          
1.126     brouard  13091:   
1.220     brouard  13092:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   13093:                 and for any valid combination of covariates
1.126     brouard  13094:      and prints on file fileres'p'. */
1.251     brouard  13095:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  13096:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  13097: 
                   13098:   fprintf(fichtm,"\n");
1.286     brouard  13099:   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  13100:          ftol, stepm);
                   13101:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   13102:   ncurrv=1;
                   13103:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   13104:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   13105:   ncurrv=i;
                   13106:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  13107:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  13108:   ncurrv=i;
                   13109:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  13110:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  13111:   ncurrv=i;
                   13112:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   13113:   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", \
                   13114:           nlstate, ndeath, maxwav, mle, weightopt);
                   13115: 
                   13116:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   13117: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   13118: 
                   13119:   
1.317     brouard  13120:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  13121: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   13122: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  13123:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  13124:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  13125:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13126:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13127:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13128:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  13129: 
1.126     brouard  13130:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   13131:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   13132:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   13133: 
                   13134:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  13135:   /* For mortality only */
1.126     brouard  13136:   if (mle==-3){
1.136     brouard  13137:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  13138:     for(i=1;i<=NDIM;i++)
                   13139:       for(j=1;j<=NDIM;j++)
                   13140:        ximort[i][j]=0.;
1.186     brouard  13141:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  13142:     cens=ivector(firstobs,lastobs);
                   13143:     ageexmed=vector(firstobs,lastobs);
                   13144:     agecens=vector(firstobs,lastobs);
                   13145:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  13146:                
1.126     brouard  13147:     for (i=1; i<=imx; i++){
                   13148:       dcwave[i]=-1;
                   13149:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  13150:        if (s[m][i]>nlstate) {
                   13151:          dcwave[i]=m;
                   13152:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   13153:          break;
                   13154:        }
1.126     brouard  13155:     }
1.226     brouard  13156:     
1.126     brouard  13157:     for (i=1; i<=imx; i++) {
                   13158:       if (wav[i]>0){
1.226     brouard  13159:        ageexmed[i]=agev[mw[1][i]][i];
                   13160:        j=wav[i];
                   13161:        agecens[i]=1.; 
                   13162:        
                   13163:        if (ageexmed[i]> 1 && wav[i] > 0){
                   13164:          agecens[i]=agev[mw[j][i]][i];
                   13165:          cens[i]= 1;
                   13166:        }else if (ageexmed[i]< 1) 
                   13167:          cens[i]= -1;
                   13168:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   13169:          cens[i]=0 ;
1.126     brouard  13170:       }
                   13171:       else cens[i]=-1;
                   13172:     }
                   13173:     
                   13174:     for (i=1;i<=NDIM;i++) {
                   13175:       for (j=1;j<=NDIM;j++)
1.226     brouard  13176:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  13177:     }
                   13178:     
1.302     brouard  13179:     p[1]=0.0268; p[NDIM]=0.083;
                   13180:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  13181:     
                   13182:     
1.136     brouard  13183: #ifdef GSL
                   13184:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  13185: #else
1.126     brouard  13186:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  13187: #endif
1.201     brouard  13188:     strcpy(filerespow,"POW-MORT_"); 
                   13189:     strcat(filerespow,fileresu);
1.126     brouard  13190:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   13191:       printf("Problem with resultfile: %s\n", filerespow);
                   13192:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   13193:     }
1.136     brouard  13194: #ifdef GSL
                   13195:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  13196: #else
1.126     brouard  13197:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  13198: #endif
1.126     brouard  13199:     /*  for (i=1;i<=nlstate;i++)
                   13200:        for(j=1;j<=nlstate+ndeath;j++)
                   13201:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   13202:     */
                   13203:     fprintf(ficrespow,"\n");
1.136     brouard  13204: #ifdef GSL
                   13205:     /* gsl starts here */ 
                   13206:     T = gsl_multimin_fminimizer_nmsimplex;
                   13207:     gsl_multimin_fminimizer *sfm = NULL;
                   13208:     gsl_vector *ss, *x;
                   13209:     gsl_multimin_function minex_func;
                   13210: 
                   13211:     /* Initial vertex size vector */
                   13212:     ss = gsl_vector_alloc (NDIM);
                   13213:     
                   13214:     if (ss == NULL){
                   13215:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   13216:     }
                   13217:     /* Set all step sizes to 1 */
                   13218:     gsl_vector_set_all (ss, 0.001);
                   13219: 
                   13220:     /* Starting point */
1.126     brouard  13221:     
1.136     brouard  13222:     x = gsl_vector_alloc (NDIM);
                   13223:     
                   13224:     if (x == NULL){
                   13225:       gsl_vector_free(ss);
                   13226:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   13227:     }
                   13228:   
                   13229:     /* Initialize method and iterate */
                   13230:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  13231:     /*     gsl_vector_set(x, 0, 0.0268); */
                   13232:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  13233:     gsl_vector_set(x, 0, p[1]);
                   13234:     gsl_vector_set(x, 1, p[2]);
                   13235: 
                   13236:     minex_func.f = &gompertz_f;
                   13237:     minex_func.n = NDIM;
                   13238:     minex_func.params = (void *)&p; /* ??? */
                   13239:     
                   13240:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   13241:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   13242:     
                   13243:     printf("Iterations beginning .....\n\n");
                   13244:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   13245: 
                   13246:     iteri=0;
                   13247:     while (rval == GSL_CONTINUE){
                   13248:       iteri++;
                   13249:       status = gsl_multimin_fminimizer_iterate(sfm);
                   13250:       
                   13251:       if (status) printf("error: %s\n", gsl_strerror (status));
                   13252:       fflush(0);
                   13253:       
                   13254:       if (status) 
                   13255:         break;
                   13256:       
                   13257:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   13258:       ssval = gsl_multimin_fminimizer_size (sfm);
                   13259:       
                   13260:       if (rval == GSL_SUCCESS)
                   13261:         printf ("converged to a local maximum at\n");
                   13262:       
                   13263:       printf("%5d ", iteri);
                   13264:       for (it = 0; it < NDIM; it++){
                   13265:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   13266:       }
                   13267:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   13268:     }
                   13269:     
                   13270:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   13271:     
                   13272:     gsl_vector_free(x); /* initial values */
                   13273:     gsl_vector_free(ss); /* inital step size */
                   13274:     for (it=0; it<NDIM; it++){
                   13275:       p[it+1]=gsl_vector_get(sfm->x,it);
                   13276:       fprintf(ficrespow," %.12lf", p[it]);
                   13277:     }
                   13278:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   13279: #endif
                   13280: #ifdef POWELL
                   13281:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   13282: #endif  
1.126     brouard  13283:     fclose(ficrespow);
                   13284:     
1.203     brouard  13285:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  13286: 
                   13287:     for(i=1; i <=NDIM; i++)
                   13288:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  13289:                                matcov[i][j]=matcov[j][i];
1.126     brouard  13290:     
                   13291:     printf("\nCovariance matrix\n ");
1.203     brouard  13292:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  13293:     for(i=1; i <=NDIM; i++) {
                   13294:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  13295:                                printf("%f ",matcov[i][j]);
                   13296:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  13297:       }
1.203     brouard  13298:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  13299:     }
                   13300:     
                   13301:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  13302:     for (i=1;i<=NDIM;i++) {
1.126     brouard  13303:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  13304:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   13305:     }
1.302     brouard  13306:     lsurv=vector(agegomp,AGESUP);
                   13307:     lpop=vector(agegomp,AGESUP);
                   13308:     tpop=vector(agegomp,AGESUP);
1.126     brouard  13309:     lsurv[agegomp]=100000;
                   13310:     
                   13311:     for (k=agegomp;k<=AGESUP;k++) {
                   13312:       agemortsup=k;
                   13313:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   13314:     }
                   13315:     
                   13316:     for (k=agegomp;k<agemortsup;k++)
                   13317:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   13318:     
                   13319:     for (k=agegomp;k<agemortsup;k++){
                   13320:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   13321:       sumlpop=sumlpop+lpop[k];
                   13322:     }
                   13323:     
                   13324:     tpop[agegomp]=sumlpop;
                   13325:     for (k=agegomp;k<(agemortsup-3);k++){
                   13326:       /*  tpop[k+1]=2;*/
                   13327:       tpop[k+1]=tpop[k]-lpop[k];
                   13328:     }
                   13329:     
                   13330:     
                   13331:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   13332:     for (k=agegomp;k<(agemortsup-2);k++) 
                   13333:       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]);
                   13334:     
                   13335:     
                   13336:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  13337:                ageminpar=50;
                   13338:                agemaxpar=100;
1.194     brouard  13339:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   13340:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   13341: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13342: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   13343:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   13344: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13345: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  13346:     }else{
                   13347:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   13348:                        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  13349:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  13350:                }
1.201     brouard  13351:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  13352:                     stepm, weightopt,\
                   13353:                     model,imx,p,matcov,agemortsup);
                   13354:     
1.302     brouard  13355:     free_vector(lsurv,agegomp,AGESUP);
                   13356:     free_vector(lpop,agegomp,AGESUP);
                   13357:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  13358:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  13359:     free_ivector(dcwave,firstobs,lastobs);
                   13360:     free_vector(agecens,firstobs,lastobs);
                   13361:     free_vector(ageexmed,firstobs,lastobs);
                   13362:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  13363: #ifdef GSL
1.136     brouard  13364: #endif
1.186     brouard  13365:   } /* Endof if mle==-3 mortality only */
1.205     brouard  13366:   /* Standard  */
                   13367:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   13368:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   13369:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  13370:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  13371:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   13372:     for (k=1; k<=npar;k++)
                   13373:       printf(" %d %8.5f",k,p[k]);
                   13374:     printf("\n");
1.205     brouard  13375:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   13376:       /* mlikeli uses func not funcone */
1.247     brouard  13377:       /* for(i=1;i<nlstate;i++){ */
                   13378:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   13379:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   13380:       /* } */
1.205     brouard  13381:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   13382:     }
                   13383:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   13384:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   13385:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   13386:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13387:     }
                   13388:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  13389:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13390:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335     brouard  13391:           /* exit(0); */
1.126     brouard  13392:     for (k=1; k<=npar;k++)
                   13393:       printf(" %d %8.5f",k,p[k]);
                   13394:     printf("\n");
                   13395:     
                   13396:     /*--------- results files --------------*/
1.283     brouard  13397:     /* 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  13398:     
                   13399:     
                   13400:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13401:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  13402:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13403: 
                   13404:     printf("#model=  1      +     age ");
                   13405:     fprintf(ficres,"#model=  1      +     age ");
                   13406:     fprintf(ficlog,"#model=  1      +     age ");
                   13407:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   13408: </ul>", model);
                   13409: 
                   13410:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   13411:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13412:     if(nagesqr==1){
                   13413:       printf("  + age*age  ");
                   13414:       fprintf(ficres,"  + age*age  ");
                   13415:       fprintf(ficlog,"  + age*age  ");
                   13416:       fprintf(fichtm, "<th>+ age*age</th>");
                   13417:     }
                   13418:     for(j=1;j <=ncovmodel-2;j++){
                   13419:       if(Typevar[j]==0) {
                   13420:        printf("  +      V%d  ",Tvar[j]);
                   13421:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   13422:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   13423:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13424:       }else if(Typevar[j]==1) {
                   13425:        printf("  +    V%d*age ",Tvar[j]);
                   13426:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   13427:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   13428:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13429:       }else if(Typevar[j]==2) {
                   13430:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13431:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13432:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13433:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13434:       }
                   13435:     }
                   13436:     printf("\n");
                   13437:     fprintf(ficres,"\n");
                   13438:     fprintf(ficlog,"\n");
                   13439:     fprintf(fichtm, "</tr>");
                   13440:     fprintf(fichtm, "\n");
                   13441:     
                   13442:     
1.126     brouard  13443:     for(i=1,jk=1; i <=nlstate; i++){
                   13444:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  13445:        if (k != i) {
1.319     brouard  13446:          fprintf(fichtm, "<tr>");
1.225     brouard  13447:          printf("%d%d ",i,k);
                   13448:          fprintf(ficlog,"%d%d ",i,k);
                   13449:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  13450:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13451:          for(j=1; j <=ncovmodel; j++){
                   13452:            printf("%12.7f ",p[jk]);
                   13453:            fprintf(ficlog,"%12.7f ",p[jk]);
                   13454:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  13455:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  13456:            jk++; 
                   13457:          }
                   13458:          printf("\n");
                   13459:          fprintf(ficlog,"\n");
                   13460:          fprintf(ficres,"\n");
1.319     brouard  13461:          fprintf(fichtm, "</tr>\n");
1.225     brouard  13462:        }
1.126     brouard  13463:       }
                   13464:     }
1.319     brouard  13465:     /* fprintf(fichtm,"</tr>\n"); */
                   13466:     fprintf(fichtm,"</table>\n");
                   13467:     fprintf(fichtm, "\n");
                   13468: 
1.203     brouard  13469:     if(mle != 0){
                   13470:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  13471:       ftolhess=ftol; /* Usually correct */
1.203     brouard  13472:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   13473:       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");
                   13474:       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  13475:       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  13476:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   13477:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13478:       if(nagesqr==1){
                   13479:        printf("  + age*age  ");
                   13480:        fprintf(ficres,"  + age*age  ");
                   13481:        fprintf(ficlog,"  + age*age  ");
                   13482:        fprintf(fichtm, "<th>+ age*age</th>");
                   13483:       }
                   13484:       for(j=1;j <=ncovmodel-2;j++){
                   13485:        if(Typevar[j]==0) {
                   13486:          printf("  +      V%d  ",Tvar[j]);
                   13487:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13488:        }else if(Typevar[j]==1) {
                   13489:          printf("  +    V%d*age ",Tvar[j]);
                   13490:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13491:        }else if(Typevar[j]==2) {
                   13492:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13493:        }
                   13494:       }
                   13495:       fprintf(fichtm, "</tr>\n");
                   13496:  
1.203     brouard  13497:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  13498:        for(k=1; k <=(nlstate+ndeath); k++){
                   13499:          if (k != i) {
1.319     brouard  13500:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  13501:            printf("%d%d ",i,k);
                   13502:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  13503:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13504:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  13505:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  13506:              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]));
                   13507:              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  13508:              if(fabs(wald) > 1.96){
1.321     brouard  13509:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  13510:              }else{
                   13511:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   13512:              }
1.324     brouard  13513:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  13514:              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  13515:              jk++; 
                   13516:            }
                   13517:            printf("\n");
                   13518:            fprintf(ficlog,"\n");
1.319     brouard  13519:            fprintf(fichtm, "</tr>\n");
1.225     brouard  13520:          }
                   13521:        }
1.193     brouard  13522:       }
1.203     brouard  13523:     } /* end of hesscov and Wald tests */
1.319     brouard  13524:     fprintf(fichtm,"</table>\n");
1.225     brouard  13525:     
1.203     brouard  13526:     /*  */
1.126     brouard  13527:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   13528:     printf("# Scales (for hessian or gradient estimation)\n");
                   13529:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   13530:     for(i=1,jk=1; i <=nlstate; i++){
                   13531:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  13532:        if (j!=i) {
                   13533:          fprintf(ficres,"%1d%1d",i,j);
                   13534:          printf("%1d%1d",i,j);
                   13535:          fprintf(ficlog,"%1d%1d",i,j);
                   13536:          for(k=1; k<=ncovmodel;k++){
                   13537:            printf(" %.5e",delti[jk]);
                   13538:            fprintf(ficlog," %.5e",delti[jk]);
                   13539:            fprintf(ficres," %.5e",delti[jk]);
                   13540:            jk++;
                   13541:          }
                   13542:          printf("\n");
                   13543:          fprintf(ficlog,"\n");
                   13544:          fprintf(ficres,"\n");
                   13545:        }
1.126     brouard  13546:       }
                   13547:     }
                   13548:     
                   13549:     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.203     brouard  13550:     if(mle >= 1) /* To big for the screen */
1.126     brouard  13551:       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");
                   13552:     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");
                   13553:     /* # 121 Var(a12)\n\ */
                   13554:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   13555:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   13556:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   13557:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   13558:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   13559:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   13560:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   13561:     
                   13562:     
                   13563:     /* Just to have a covariance matrix which will be more understandable
                   13564:        even is we still don't want to manage dictionary of variables
                   13565:     */
                   13566:     for(itimes=1;itimes<=2;itimes++){
                   13567:       jj=0;
                   13568:       for(i=1; i <=nlstate; i++){
1.225     brouard  13569:        for(j=1; j <=nlstate+ndeath; j++){
                   13570:          if(j==i) continue;
                   13571:          for(k=1; k<=ncovmodel;k++){
                   13572:            jj++;
                   13573:            ca[0]= k+'a'-1;ca[1]='\0';
                   13574:            if(itimes==1){
                   13575:              if(mle>=1)
                   13576:                printf("#%1d%1d%d",i,j,k);
                   13577:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   13578:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   13579:            }else{
                   13580:              if(mle>=1)
                   13581:                printf("%1d%1d%d",i,j,k);
                   13582:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   13583:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   13584:            }
                   13585:            ll=0;
                   13586:            for(li=1;li <=nlstate; li++){
                   13587:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   13588:                if(lj==li) continue;
                   13589:                for(lk=1;lk<=ncovmodel;lk++){
                   13590:                  ll++;
                   13591:                  if(ll<=jj){
                   13592:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   13593:                    if(ll<jj){
                   13594:                      if(itimes==1){
                   13595:                        if(mle>=1)
                   13596:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13597:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13598:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13599:                      }else{
                   13600:                        if(mle>=1)
                   13601:                          printf(" %.5e",matcov[jj][ll]); 
                   13602:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   13603:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   13604:                      }
                   13605:                    }else{
                   13606:                      if(itimes==1){
                   13607:                        if(mle>=1)
                   13608:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   13609:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   13610:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   13611:                      }else{
                   13612:                        if(mle>=1)
                   13613:                          printf(" %.7e",matcov[jj][ll]); 
                   13614:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   13615:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   13616:                      }
                   13617:                    }
                   13618:                  }
                   13619:                } /* end lk */
                   13620:              } /* end lj */
                   13621:            } /* end li */
                   13622:            if(mle>=1)
                   13623:              printf("\n");
                   13624:            fprintf(ficlog,"\n");
                   13625:            fprintf(ficres,"\n");
                   13626:            numlinepar++;
                   13627:          } /* end k*/
                   13628:        } /*end j */
1.126     brouard  13629:       } /* end i */
                   13630:     } /* end itimes */
                   13631:     
                   13632:     fflush(ficlog);
                   13633:     fflush(ficres);
1.225     brouard  13634:     while(fgets(line, MAXLINE, ficpar)) {
                   13635:       /* If line starts with a # it is a comment */
                   13636:       if (line[0] == '#') {
                   13637:        numlinepar++;
                   13638:        fputs(line,stdout);
                   13639:        fputs(line,ficparo);
                   13640:        fputs(line,ficlog);
1.299     brouard  13641:        fputs(line,ficres);
1.225     brouard  13642:        continue;
                   13643:       }else
                   13644:        break;
                   13645:     }
                   13646:     
1.209     brouard  13647:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   13648:     /*   ungetc(c,ficpar); */
                   13649:     /*   fgets(line, MAXLINE, ficpar); */
                   13650:     /*   fputs(line,stdout); */
                   13651:     /*   fputs(line,ficparo); */
                   13652:     /* } */
                   13653:     /* ungetc(c,ficpar); */
1.126     brouard  13654:     
                   13655:     estepm=0;
1.209     brouard  13656:     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  13657:       
                   13658:       if (num_filled != 6) {
                   13659:        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);
                   13660:        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);
                   13661:        goto end;
                   13662:       }
                   13663:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   13664:     }
                   13665:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   13666:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   13667:     
1.209     brouard  13668:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  13669:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   13670:     if (fage <= 2) {
                   13671:       bage = ageminpar;
                   13672:       fage = agemaxpar;
                   13673:     }
                   13674:     
                   13675:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  13676:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   13677:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  13678:                
1.186     brouard  13679:     /* Other stuffs, more or less useful */    
1.254     brouard  13680:     while(fgets(line, MAXLINE, ficpar)) {
                   13681:       /* If line starts with a # it is a comment */
                   13682:       if (line[0] == '#') {
                   13683:        numlinepar++;
                   13684:        fputs(line,stdout);
                   13685:        fputs(line,ficparo);
                   13686:        fputs(line,ficlog);
1.299     brouard  13687:        fputs(line,ficres);
1.254     brouard  13688:        continue;
                   13689:       }else
                   13690:        break;
                   13691:     }
                   13692: 
                   13693:     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){
                   13694:       
                   13695:       if (num_filled != 7) {
                   13696:        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);
                   13697:        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);
                   13698:        goto end;
                   13699:       }
                   13700:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   13701:       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);
                   13702:       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);
                   13703:       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  13704:     }
1.254     brouard  13705: 
                   13706:     while(fgets(line, MAXLINE, ficpar)) {
                   13707:       /* If line starts with a # it is a comment */
                   13708:       if (line[0] == '#') {
                   13709:        numlinepar++;
                   13710:        fputs(line,stdout);
                   13711:        fputs(line,ficparo);
                   13712:        fputs(line,ficlog);
1.299     brouard  13713:        fputs(line,ficres);
1.254     brouard  13714:        continue;
                   13715:       }else
                   13716:        break;
1.126     brouard  13717:     }
                   13718:     
                   13719:     
                   13720:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   13721:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   13722:     
1.254     brouard  13723:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   13724:       if (num_filled != 1) {
                   13725:        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);
                   13726:        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);
                   13727:        goto end;
                   13728:       }
                   13729:       printf("pop_based=%d\n",popbased);
                   13730:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   13731:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   13732:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   13733:     }
                   13734:      
1.258     brouard  13735:     /* Results */
1.332     brouard  13736:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
                   13737:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   13738:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  13739:     endishere=0;
1.258     brouard  13740:     nresult=0;
1.308     brouard  13741:     parameterline=0;
1.258     brouard  13742:     do{
                   13743:       if(!fgets(line, MAXLINE, ficpar)){
                   13744:        endishere=1;
1.308     brouard  13745:        parameterline=15;
1.258     brouard  13746:       }else if (line[0] == '#') {
                   13747:        /* If line starts with a # it is a comment */
1.254     brouard  13748:        numlinepar++;
                   13749:        fputs(line,stdout);
                   13750:        fputs(line,ficparo);
                   13751:        fputs(line,ficlog);
1.299     brouard  13752:        fputs(line,ficres);
1.254     brouard  13753:        continue;
1.258     brouard  13754:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   13755:        parameterline=11;
1.296     brouard  13756:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  13757:        parameterline=12;
1.307     brouard  13758:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  13759:        parameterline=13;
1.307     brouard  13760:       }
1.258     brouard  13761:       else{
                   13762:        parameterline=14;
1.254     brouard  13763:       }
1.308     brouard  13764:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  13765:       case 11:
1.296     brouard  13766:        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)){
                   13767:                  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  13768:          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);
                   13769:          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);
                   13770:          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);
                   13771:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  13772:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   13773:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  13774:           prvforecast = 1;
                   13775:        } 
                   13776:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  13777:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13778:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13779:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  13780:           prvforecast = 2;
                   13781:        }
                   13782:        else {
                   13783:          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);
                   13784:          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);
                   13785:          goto end;
1.258     brouard  13786:        }
1.254     brouard  13787:        break;
1.258     brouard  13788:       case 12:
1.296     brouard  13789:        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)){
                   13790:           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);
                   13791:          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);
                   13792:          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);
                   13793:          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);
                   13794:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  13795:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   13796:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  13797:           prvbackcast = 1;
                   13798:        } 
                   13799:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  13800:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13801:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13802:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  13803:           prvbackcast = 2;
                   13804:        }
                   13805:        else {
                   13806:          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);
                   13807:          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);
                   13808:          goto end;
1.258     brouard  13809:        }
1.230     brouard  13810:        break;
1.258     brouard  13811:       case 13:
1.332     brouard  13812:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  13813:        nresult++; /* Sum of resultlines */
1.332     brouard  13814:        printf("Result %d: result:%s\n",nresult, resultlineori);
                   13815:        /* removefirstspace(&resultlineori); */
                   13816:        
                   13817:        if(strstr(resultlineori,"v") !=0){
                   13818:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   13819:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   13820:          return 1;
                   13821:        }
                   13822:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
                   13823:        printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori);
1.318     brouard  13824:        if(nresult > MAXRESULTLINESPONE-1){
                   13825:          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);
                   13826:          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  13827:          goto end;
                   13828:        }
1.332     brouard  13829:        
1.310     brouard  13830:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  13831:          fprintf(ficparo,"result: %s\n",resultline);
                   13832:          fprintf(ficres,"result: %s\n",resultline);
                   13833:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  13834:        } else
                   13835:          goto end;
1.307     brouard  13836:        break;
                   13837:       case 14:
                   13838:        printf("Error: Unknown command '%s'\n",line);
                   13839:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  13840:        if(line[0] == ' ' || line[0] == '\n'){
                   13841:          printf("It should not be an empty line '%s'\n",line);
                   13842:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   13843:        }         
1.307     brouard  13844:        if(ncovmodel >=2 && nresult==0 ){
                   13845:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   13846:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  13847:        }
1.307     brouard  13848:        /* goto end; */
                   13849:        break;
1.308     brouard  13850:       case 15:
                   13851:        printf("End of resultlines.\n");
                   13852:        fprintf(ficlog,"End of resultlines.\n");
                   13853:        break;
                   13854:       default: /* parameterline =0 */
1.307     brouard  13855:        nresult=1;
                   13856:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  13857:       } /* End switch parameterline */
                   13858:     }while(endishere==0); /* End do */
1.126     brouard  13859:     
1.230     brouard  13860:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  13861:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  13862:     
                   13863:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  13864:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  13865:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  13866: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13867: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  13868:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  13869: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13870: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  13871:     }else{
1.270     brouard  13872:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  13873:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   13874:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   13875:       if(prvforecast==1){
                   13876:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   13877:         jprojd=jproj1;
                   13878:         mprojd=mproj1;
                   13879:         anprojd=anproj1;
                   13880:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   13881:         jprojf=jproj2;
                   13882:         mprojf=mproj2;
                   13883:         anprojf=anproj2;
                   13884:       } else if(prvforecast == 2){
                   13885:         dateprojd=dateintmean;
                   13886:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   13887:         dateprojf=dateintmean+yrfproj;
                   13888:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   13889:       }
                   13890:       if(prvbackcast==1){
                   13891:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   13892:         jbackd=jback1;
                   13893:         mbackd=mback1;
                   13894:         anbackd=anback1;
                   13895:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   13896:         jbackf=jback2;
                   13897:         mbackf=mback2;
                   13898:         anbackf=anback2;
                   13899:       } else if(prvbackcast == 2){
                   13900:         datebackd=dateintmean;
                   13901:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   13902:         datebackf=dateintmean-yrbproj;
                   13903:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   13904:       }
                   13905:       
                   13906:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  13907:     }
                   13908:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  13909:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   13910:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  13911:                
1.225     brouard  13912:     /*------------ free_vector  -------------*/
                   13913:     /*  chdir(path); */
1.220     brouard  13914:                
1.215     brouard  13915:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   13916:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   13917:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   13918:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  13919:     free_lvector(num,firstobs,lastobs);
                   13920:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  13921:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   13922:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   13923:     fclose(ficparo);
                   13924:     fclose(ficres);
1.220     brouard  13925:                
                   13926:                
1.186     brouard  13927:     /* Other results (useful)*/
1.220     brouard  13928:                
                   13929:                
1.126     brouard  13930:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  13931:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   13932:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  13933:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  13934:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  13935:     fclose(ficrespl);
                   13936: 
                   13937:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  13938:     /*#include "hpijx.h"*/
1.332     brouard  13939:     /** 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?*/
                   13940:     /* calls hpxij with combination k */
1.180     brouard  13941:     hPijx(p, bage, fage);
1.145     brouard  13942:     fclose(ficrespij);
1.227     brouard  13943:     
1.220     brouard  13944:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  13945:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  13946:     k=1;
1.126     brouard  13947:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  13948:     
1.269     brouard  13949:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   13950:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13951:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  13952:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  13953:        for(k=1;k<=ncovcombmax;k++)
                   13954:          probs[i][j][k]=0.;
1.269     brouard  13955:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   13956:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  13957:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  13958:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13959:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  13960:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  13961:          for(k=1;k<=ncovcombmax;k++)
                   13962:            mobaverages[i][j][k]=0.;
1.219     brouard  13963:       mobaverage=mobaverages;
                   13964:       if (mobilav!=0) {
1.235     brouard  13965:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  13966:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  13967:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   13968:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   13969:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   13970:        }
1.269     brouard  13971:       } else if (mobilavproj !=0) {
1.235     brouard  13972:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  13973:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  13974:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   13975:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13976:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13977:        }
1.269     brouard  13978:       }else{
                   13979:        printf("Internal error moving average\n");
                   13980:        fflush(stdout);
                   13981:        exit(1);
1.219     brouard  13982:       }
                   13983:     }/* end if moving average */
1.227     brouard  13984:     
1.126     brouard  13985:     /*---------- Forecasting ------------------*/
1.296     brouard  13986:     if(prevfcast==1){ 
                   13987:       /*   /\*    if(stepm ==1){*\/ */
                   13988:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13989:       /*This done previously after freqsummary.*/
                   13990:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   13991:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   13992:       
                   13993:       /* } else if (prvforecast==2){ */
                   13994:       /*   /\*    if(stepm ==1){*\/ */
                   13995:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13996:       /* } */
                   13997:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   13998:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  13999:     }
1.269     brouard  14000: 
1.296     brouard  14001:     /* Prevbcasting */
                   14002:     if(prevbcast==1){
1.219     brouard  14003:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14004:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14005:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   14006: 
                   14007:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   14008: 
                   14009:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  14010: 
1.219     brouard  14011:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   14012:       fclose(ficresplb);
                   14013: 
1.222     brouard  14014:       hBijx(p, bage, fage, mobaverage);
                   14015:       fclose(ficrespijb);
1.219     brouard  14016: 
1.296     brouard  14017:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   14018:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   14019:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   14020:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   14021:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   14022:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   14023: 
                   14024:       
1.269     brouard  14025:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14026: 
                   14027:       
1.269     brouard  14028:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  14029:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14030:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14031:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  14032:     }    /* end  Prevbcasting */
1.268     brouard  14033:  
1.186     brouard  14034:  
                   14035:     /* ------ Other prevalence ratios------------ */
1.126     brouard  14036: 
1.215     brouard  14037:     free_ivector(wav,1,imx);
                   14038:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   14039:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   14040:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  14041:                
                   14042:                
1.127     brouard  14043:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  14044:                
1.201     brouard  14045:     strcpy(filerese,"E_");
                   14046:     strcat(filerese,fileresu);
1.126     brouard  14047:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   14048:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14049:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14050:     }
1.208     brouard  14051:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   14052:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  14053: 
                   14054:     pstamp(ficreseij);
1.219     brouard  14055:                
1.235     brouard  14056:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   14057:     if (cptcovn < 1){i1=1;}
                   14058:     
                   14059:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   14060:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  14061:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  14062:        continue;
1.219     brouard  14063:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  14064:       printf("\n#****** ");
1.225     brouard  14065:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  14066:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   14067:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.235     brouard  14068:       }
                   14069:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.337     brouard  14070:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   14071:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  14072:       }
                   14073:       fprintf(ficreseij,"******\n");
1.235     brouard  14074:       printf("******\n");
1.219     brouard  14075:       
                   14076:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14077:       oldm=oldms;savm=savms;
1.330     brouard  14078:       /* 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  14079:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  14080:       
1.219     brouard  14081:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  14082:     }
                   14083:     fclose(ficreseij);
1.208     brouard  14084:     printf("done evsij\n");fflush(stdout);
                   14085:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  14086: 
1.218     brouard  14087:                
1.227     brouard  14088:     /*---------- State-specific expectancies and variances ------------*/
1.336     brouard  14089:     /* Should be moved in a function */                
1.201     brouard  14090:     strcpy(filerest,"T_");
                   14091:     strcat(filerest,fileresu);
1.127     brouard  14092:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   14093:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   14094:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   14095:     }
1.208     brouard  14096:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   14097:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  14098:     strcpy(fileresstde,"STDE_");
                   14099:     strcat(fileresstde,fileresu);
1.126     brouard  14100:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  14101:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   14102:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  14103:     }
1.227     brouard  14104:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   14105:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  14106: 
1.201     brouard  14107:     strcpy(filerescve,"CVE_");
                   14108:     strcat(filerescve,fileresu);
1.126     brouard  14109:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  14110:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   14111:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  14112:     }
1.227     brouard  14113:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   14114:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  14115: 
1.201     brouard  14116:     strcpy(fileresv,"V_");
                   14117:     strcat(fileresv,fileresu);
1.126     brouard  14118:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   14119:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   14120:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   14121:     }
1.227     brouard  14122:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   14123:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  14124: 
1.235     brouard  14125:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   14126:     if (cptcovn < 1){i1=1;}
                   14127:     
1.334     brouard  14128:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   14129:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   14130:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   14131:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   14132:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   14133:       /* */
                   14134:       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  14135:        continue;
1.321     brouard  14136:       printf("\n# model %s \n#****** Result for:", model);
                   14137:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   14138:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.334     brouard  14139:       /* It might not be a good idea to mix dummies and quantitative */
                   14140:       /* 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 *\/ */
                   14141:       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 */
                   14142:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   14143:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   14144:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   14145:         * (V5 is quanti) V4 and V3 are dummies
                   14146:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   14147:         *                                                              l=1 l=2
                   14148:         *                                                           k=1  1   1   0   0
                   14149:         *                                                           k=2  2   1   1   0
                   14150:         *                                                           k=3 [1] [2]  0   1
                   14151:         *                                                           k=4  2   2   1   1
                   14152:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   14153:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   14154:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   14155:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   14156:         */
                   14157:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   14158:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   14159: /* We give up with the combinations!! */
                   14160:        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 */
                   14161: 
                   14162:        if(Dummy[modelresult[nres][j]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to j in resultline  */
1.337     brouard  14163:          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  */
                   14164:          fprintf(ficlog,"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  */
                   14165:          fprintf(ficrest,"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  */
1.334     brouard  14166:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   14167:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   14168:          }else{
                   14169:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   14170:          }
                   14171:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14172:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14173:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   14174:          /* For each selected (single) quantitative value */
1.337     brouard  14175:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   14176:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   14177:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
1.334     brouard  14178:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   14179:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   14180:          }else{
                   14181:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   14182:          }
                   14183:        }else{
                   14184:          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 */
                   14185:          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 */
                   14186:          exit(1);
                   14187:        }
1.335     brouard  14188:       } /* End loop for each variable in the resultline */
1.334     brouard  14189:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   14190:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   14191:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14192:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14193:       /* }      */
1.208     brouard  14194:       fprintf(ficrest,"******\n");
1.227     brouard  14195:       fprintf(ficlog,"******\n");
                   14196:       printf("******\n");
1.208     brouard  14197:       
                   14198:       fprintf(ficresstdeij,"\n#****** ");
                   14199:       fprintf(ficrescveij,"\n#****** ");
1.337     brouard  14200:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
                   14201:       /* But it won't be sorted and depends on how the resultline is ordered */
1.225     brouard  14202:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  14203:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   14204:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14205:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14206:       }
                   14207:       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  14208:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   14209:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  14210:       }        
1.208     brouard  14211:       fprintf(ficresstdeij,"******\n");
                   14212:       fprintf(ficrescveij,"******\n");
                   14213:       
                   14214:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  14215:       /* pstamp(ficresvij); */
1.225     brouard  14216:       for(j=1;j<=cptcoveff;j++) 
1.335     brouard  14217:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   14218:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  14219:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  14220:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
1.337     brouard  14221:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  14222:       }        
1.208     brouard  14223:       fprintf(ficresvij,"******\n");
                   14224:       
                   14225:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14226:       oldm=oldms;savm=savms;
1.235     brouard  14227:       printf(" cvevsij ");
                   14228:       fprintf(ficlog, " cvevsij ");
                   14229:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  14230:       printf(" end cvevsij \n ");
                   14231:       fprintf(ficlog, " end cvevsij \n ");
                   14232:       
                   14233:       /*
                   14234:        */
                   14235:       /* goto endfree; */
                   14236:       
                   14237:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14238:       pstamp(ficrest);
                   14239:       
1.269     brouard  14240:       epj=vector(1,nlstate+1);
1.208     brouard  14241:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  14242:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   14243:        cptcod= 0; /* To be deleted */
                   14244:        printf("varevsij vpopbased=%d \n",vpopbased);
                   14245:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  14246:        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  14247:        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 ");
                   14248:        if(vpopbased==1)
                   14249:          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);
                   14250:        else
1.288     brouard  14251:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.335     brouard  14252:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  14253:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   14254:        fprintf(ficrest,"\n");
                   14255:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  14256:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   14257:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  14258:        for(age=bage; age <=fage ;age++){
1.235     brouard  14259:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  14260:          if (vpopbased==1) {
                   14261:            if(mobilav ==0){
                   14262:              for(i=1; i<=nlstate;i++)
                   14263:                prlim[i][i]=probs[(int)age][i][k];
                   14264:            }else{ /* mobilav */ 
                   14265:              for(i=1; i<=nlstate;i++)
                   14266:                prlim[i][i]=mobaverage[(int)age][i][k];
                   14267:            }
                   14268:          }
1.219     brouard  14269:          
1.227     brouard  14270:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   14271:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   14272:          /* printf(" age %4.0f ",age); */
                   14273:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   14274:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   14275:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   14276:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   14277:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   14278:            }
                   14279:            epj[nlstate+1] +=epj[j];
                   14280:          }
                   14281:          /* printf(" age %4.0f \n",age); */
1.219     brouard  14282:          
1.227     brouard  14283:          for(i=1, vepp=0.;i <=nlstate;i++)
                   14284:            for(j=1;j <=nlstate;j++)
                   14285:              vepp += vareij[i][j][(int)age];
                   14286:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   14287:          for(j=1;j <=nlstate;j++){
                   14288:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   14289:          }
                   14290:          fprintf(ficrest,"\n");
                   14291:        }
1.208     brouard  14292:       } /* End vpopbased */
1.269     brouard  14293:       free_vector(epj,1,nlstate+1);
1.208     brouard  14294:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   14295:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  14296:       printf("done selection\n");fflush(stdout);
                   14297:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  14298:       
1.335     brouard  14299:     } /* End k selection or end covariate selection for nres */
1.227     brouard  14300: 
                   14301:     printf("done State-specific expectancies\n");fflush(stdout);
                   14302:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   14303: 
1.335     brouard  14304:     /* variance-covariance of forward period prevalence */
1.269     brouard  14305:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14306: 
1.227     brouard  14307:     
1.290     brouard  14308:     free_vector(weight,firstobs,lastobs);
1.330     brouard  14309:     free_imatrix(Tvardk,1,NCOVMAX,1,2);
1.227     brouard  14310:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  14311:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   14312:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   14313:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   14314:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  14315:     free_ivector(tab,1,NCOVMAX);
                   14316:     fclose(ficresstdeij);
                   14317:     fclose(ficrescveij);
                   14318:     fclose(ficresvij);
                   14319:     fclose(ficrest);
                   14320:     fclose(ficpar);
                   14321:     
                   14322:     
1.126     brouard  14323:     /*---------- End : free ----------------*/
1.219     brouard  14324:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  14325:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   14326:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  14327:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   14328:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  14329:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  14330:   /* endfree:*/
                   14331:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   14332:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   14333:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.341   ! brouard  14334:   /* if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs); */
        !          14335:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);
1.290     brouard  14336:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   14337:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   14338:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  14339:   free_matrix(matcov,1,npar,1,npar);
                   14340:   free_matrix(hess,1,npar,1,npar);
                   14341:   /*free_vector(delti,1,npar);*/
                   14342:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   14343:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  14344:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  14345:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   14346:   
                   14347:   free_ivector(ncodemax,1,NCOVMAX);
                   14348:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   14349:   free_ivector(Dummy,-1,NCOVMAX);
                   14350:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  14351:   free_ivector(DummyV,1,NCOVMAX);
                   14352:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  14353:   free_ivector(Typevar,-1,NCOVMAX);
                   14354:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  14355:   free_ivector(TvarsQ,1,NCOVMAX);
                   14356:   free_ivector(TvarsQind,1,NCOVMAX);
                   14357:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  14358:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  14359:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  14360:   free_ivector(TvarFD,1,NCOVMAX);
                   14361:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  14362:   free_ivector(TvarF,1,NCOVMAX);
                   14363:   free_ivector(TvarFind,1,NCOVMAX);
                   14364:   free_ivector(TvarV,1,NCOVMAX);
                   14365:   free_ivector(TvarVind,1,NCOVMAX);
                   14366:   free_ivector(TvarA,1,NCOVMAX);
                   14367:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  14368:   free_ivector(TvarFQ,1,NCOVMAX);
                   14369:   free_ivector(TvarFQind,1,NCOVMAX);
                   14370:   free_ivector(TvarVD,1,NCOVMAX);
                   14371:   free_ivector(TvarVDind,1,NCOVMAX);
                   14372:   free_ivector(TvarVQ,1,NCOVMAX);
                   14373:   free_ivector(TvarVQind,1,NCOVMAX);
1.339     brouard  14374:   free_ivector(TvarVV,1,NCOVMAX);
                   14375:   free_ivector(TvarVVind,1,NCOVMAX);
                   14376:   
1.230     brouard  14377:   free_ivector(Tvarsel,1,NCOVMAX);
                   14378:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  14379:   free_ivector(Tposprod,1,NCOVMAX);
                   14380:   free_ivector(Tprod,1,NCOVMAX);
                   14381:   free_ivector(Tvaraff,1,NCOVMAX);
1.338     brouard  14382:   free_ivector(invalidvarcomb,0,ncovcombmax);
1.227     brouard  14383:   free_ivector(Tage,1,NCOVMAX);
                   14384:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  14385:   free_ivector(TmodelInvind,1,NCOVMAX);
                   14386:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  14387: 
                   14388:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
                   14389: 
1.227     brouard  14390:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   14391:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  14392:   fflush(fichtm);
                   14393:   fflush(ficgp);
                   14394:   
1.227     brouard  14395:   
1.126     brouard  14396:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  14397:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   14398:     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  14399:   }else{
                   14400:     printf("End of Imach\n");
                   14401:     fprintf(ficlog,"End of Imach\n");
                   14402:   }
                   14403:   printf("See log file on %s\n",filelog);
                   14404:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  14405:   /*(void) gettimeofday(&end_time,&tzp);*/
                   14406:   rend_time = time(NULL);  
                   14407:   end_time = *localtime(&rend_time);
                   14408:   /* tml = *localtime(&end_time.tm_sec); */
                   14409:   strcpy(strtend,asctime(&end_time));
1.126     brouard  14410:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   14411:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  14412:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  14413:   
1.157     brouard  14414:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   14415:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   14416:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  14417:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   14418: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   14419:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14420:   fclose(fichtm);
                   14421:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14422:   fclose(fichtmcov);
                   14423:   fclose(ficgp);
                   14424:   fclose(ficlog);
                   14425:   /*------ End -----------*/
1.227     brouard  14426:   
1.281     brouard  14427: 
                   14428: /* Executes gnuplot */
1.227     brouard  14429:   
                   14430:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  14431: #ifdef WIN32
1.227     brouard  14432:   if (_chdir(pathcd) != 0)
                   14433:     printf("Can't move to directory %s!\n",path);
                   14434:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  14435: #else
1.227     brouard  14436:     if(chdir(pathcd) != 0)
                   14437:       printf("Can't move to directory %s!\n", path);
                   14438:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  14439: #endif 
1.126     brouard  14440:     printf("Current directory %s!\n",pathcd);
                   14441:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   14442:   sprintf(plotcmd,"gnuplot");
1.157     brouard  14443: #ifdef _WIN32
1.126     brouard  14444:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   14445: #endif
                   14446:   if(!stat(plotcmd,&info)){
1.158     brouard  14447:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14448:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  14449:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  14450:     }else
                   14451:       strcpy(pplotcmd,plotcmd);
1.157     brouard  14452: #ifdef __unix
1.126     brouard  14453:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   14454:     if(!stat(plotcmd,&info)){
1.158     brouard  14455:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14456:     }else
                   14457:       strcpy(pplotcmd,plotcmd);
                   14458: #endif
                   14459:   }else
                   14460:     strcpy(pplotcmd,plotcmd);
                   14461:   
                   14462:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  14463:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  14464:   strcpy(pplotcmd,plotcmd);
1.227     brouard  14465:   
1.126     brouard  14466:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  14467:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  14468:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  14469:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  14470:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  14471:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  14472:       strcpy(plotcmd,pplotcmd);
                   14473:     }
1.126     brouard  14474:   }
1.158     brouard  14475:   printf(" Successful, please wait...");
1.126     brouard  14476:   while (z[0] != 'q') {
                   14477:     /* chdir(path); */
1.154     brouard  14478:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  14479:     scanf("%s",z);
                   14480: /*     if (z[0] == 'c') system("./imach"); */
                   14481:     if (z[0] == 'e') {
1.158     brouard  14482: #ifdef __APPLE__
1.152     brouard  14483:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  14484: #elif __linux
                   14485:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  14486: #else
1.152     brouard  14487:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  14488: #endif
                   14489:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   14490:       system(pplotcmd);
1.126     brouard  14491:     }
                   14492:     else if (z[0] == 'g') system(plotcmd);
                   14493:     else if (z[0] == 'q') exit(0);
                   14494:   }
1.227     brouard  14495: end:
1.126     brouard  14496:   while (z[0] != 'q') {
1.195     brouard  14497:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  14498:     scanf("%s",z);
                   14499:   }
1.283     brouard  14500:   printf("End\n");
1.282     brouard  14501:   exit(0);
1.126     brouard  14502: }

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